diff --git a/western_ai/usa/pytorch/aten/src/ATen/CPUApplyUtils.h b/western_ai/usa/pytorch/aten/src/ATen/CPUApplyUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..a053739db42aeeb09397f51afb6d1a4e7f7ae542 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/CPUApplyUtils.h @@ -0,0 +1,351 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace at { + +/* + * The basic strategy for apply is as follows: + * + * 1. Starting with the outermost index, loop until we reach a dimension where + * the data is no longer contiguous, i.e. the stride at that dimension is not + * equal to the size of the tensor defined by the outer dimensions. Let's call + * this outer (contiguous) tensor A. Note that if the Tensor is contiguous, then + * A is equal to the entire Tensor. Let's call the inner tensor B. + * + * 2. We loop through the indices in B, starting at its outermost dimension. For + * example, if B is a 2x2 matrix, then we do: + * + * B[0][0] + * B[0][1] + * B[1][0] + * B[1][1] + * + * We set the offset into the underlying storage as (storageOffset + stride_B * + * index_B), i.e. basically we compute the offset into the storage as we would + * normally for a Tensor. But because we are guaranteed the subsequent data is + * contiguous in memory, we can simply loop for sizeof(A) iterations and perform + * the operation, without having to follow the order described by the strides of + * A. + * + * 3. As an optimization, we merge dimensions of A that are contiguous in + * memory. For example, if A is a 3x3x3x3 tensor narrowed from a 3x3x4x3 tensor, + * then the first two dimensions can be merged for the purposes of APPLY, + * reducing the number of nested loops. + */ + +inline Tensor sort_strides(Tensor& tensor_) { + IntArrayRef strides = tensor_.strides(); + std::vector indices; + indices.reserve(tensor_.ndimension()); + for (const auto i : c10::irange(tensor_.ndimension())) { + indices.push_back(i); + } + std::sort(indices.begin(), indices.end(), [&strides](int64_t i1, int64_t i2) { + return strides[i1] > strides[i2]; + }); + Tensor tensor = tensor_.permute(indices); + return tensor; +} + +template +struct strided_tensor_iter_fixed { + public: + T* data_ = NULL; + int64_t dim_ = 0; + + // NOLINTNEXTLINE(*array*) + int64_t counter_[N] = {0}; + // NOLINTNEXTLINE(*array*) + int64_t sizes_[N] = {0}; + // NOLINTNEXTLINE(*array*) + int64_t strides_[N] = {0}; + + strided_tensor_iter_fixed(strided_tensor_iter_fixed const&) = delete; + strided_tensor_iter_fixed& operator=(strided_tensor_iter_fixed const& x) = + delete; + strided_tensor_iter_fixed(strided_tensor_iter_fixed&&) noexcept = default; + strided_tensor_iter_fixed& operator=(strided_tensor_iter_fixed&& x) noexcept = + default; + ~strided_tensor_iter_fixed() noexcept = default; + strided_tensor_iter_fixed( + Tensor& tensor, + [[maybe_unused]] bool sort_strides = false) + : data_(tensor.data_ptr()) { + std::memset(counter_, 0, sizeof(int64_t) * N); + if (tensor.dim() > 0) { + std::memcpy( + sizes_, tensor.sizes().data(), tensor.dim() * sizeof(int64_t)); + std::memcpy( + strides_, tensor.strides().data(), tensor.dim() * sizeof(int64_t)); + } + dim_ = std::get<1>(collapse_dims(sizes_, strides_, tensor.ndimension())); + } +}; + +template +struct strided_tensor_iter { + private: + public: + T* data_ = NULL; + int64_t dim_; + + std::vector counter_; + std::vector sizes_; + std::vector strides_; + + strided_tensor_iter(strided_tensor_iter const&) = delete; + strided_tensor_iter& operator=(strided_tensor_iter const& x) = delete; + strided_tensor_iter(strided_tensor_iter&&) noexcept = default; + strided_tensor_iter& operator=(strided_tensor_iter&&) noexcept = default; + ~strided_tensor_iter() noexcept = default; + strided_tensor_iter(Tensor& tensor) + : data_(tensor.data_ptr()), + dim_(tensor.ndimension()), + counter_(dim_, 0), + sizes_(tensor.sizes().vec()), + strides_(tensor.strides().vec()) { + dim_ = std::get<1>(collapse_dims(sizes_.data(), strides_.data(), dim_)); + } +}; + +inline bool _all_equal_numel(at::ArrayRef tensors) { + if (tensors.empty()) + return true; + int64_t all_numel = tensors[0].numel(); + for (const auto i : c10::irange(1, tensors.size())) { + if (tensors[i].numel() != all_numel) + return false; + } + return true; +} + +inline std::string _all_equal_numel_error(at::ArrayRef tensors) { + std::ostringstream oss; + oss << "inconsistent tensor size, expected "; + for (size_t i = 0; i < tensors.size() - 1; i++) { + oss << tensors[i].sizes() << ", "; + } + oss << "and " << tensors[tensors.size() - 1].sizes() + << " to have the same number of elements, but got "; + for (size_t i = 0; i < tensors.size() - 1; i++) { + oss << tensors[i].numel() << ", "; + } + oss << "and " << tensors[tensors.size() - 1].numel() + << " elements respectively"; + return oss.str(); +} + +inline bool _apply_preamble(ArrayRef tensors) { + checkDeviceType("CPU_tensor_apply", tensors, kCPU); + checkLayout("CPU_tensor_apply", tensors, kStrided); + TORCH_CHECK(_all_equal_numel(tensors), _all_equal_numel_error(tensors)); + // An empty tensor has no elements + for (auto& t : tensors) + if (t.numel() == 0) + return false; + return true; +} + +inline int64_t _max_dim_tensors(ArrayRef tensors) { + int64_t dim = 0; + for (auto& t : tensors) + dim = std::max(dim, t.ndimension()); + return dim; +} + +inline void iterate(int64_t /*size*/) {} + +template +inline void iterate(int64_t size, Arg& iter, Args&... iter_tail) { + iter.counter_[iter.dim_ - 1] += size; + iter.data_ = iter.data_ + size * iter.strides_[iter.dim_ - 1]; + iterate(size, iter_tail...); +} + +inline bool iterate_continue() { + return true; +} + +template +inline bool iterate_continue(Arg& iter, Args&... iter_tail) { + return iter.counter_[iter.dim_ - 1] < iter.sizes_[iter.dim_ - 1] && + iterate_continue(iter_tail...); +} + +inline int64_t max_iterate_size() { + return std::numeric_limits::max(); +} + +template +inline int64_t max_iterate_size(Arg& iter, Args&... iter_tail) { + return std::min( + (iter.sizes_[iter.dim_ - 1] - iter.counter_[iter.dim_ - 1]), + max_iterate_size(iter_tail...)); +} + +inline void iterate_overflow() {} + +template +inline void iterate_overflow(Arg& iter, Args&... iter_tail) { + if (iter.counter_[iter.dim_ - 1] == iter.sizes_[iter.dim_ - 1]) { + for (int64_t i = iter.dim_ - 1; i > 0; i--) { + if (iter.counter_[i] == iter.sizes_[i]) { + iter.counter_[i] = 0; + iter.counter_[i - 1]++; + iter.data_ = iter.data_ - (iter.sizes_[i] * iter.strides_[i]) + + iter.strides_[i - 1]; + } + } + } + iterate_overflow(iter_tail...); +} + +inline void forward(int64_t /*offset*/) {} + +template +inline void forward(int64_t offset, Arg& iter, Args&... iter_tail) { + int64_t multi = offset; + for (int64_t i = iter.dim_ - 1; i >= 0; i--) { + int64_t inc = multi % iter.sizes_[i]; + multi = multi / iter.sizes_[i]; + iter.data_ = iter.data_ + inc * iter.strides_[i]; + iter.counter_[i] += inc; + } + forward(offset, iter_tail...); +} + +inline int64_t max_dim() { + return 0; +} + +template +inline int64_t max_dim(Arg& iter, Args&... iter_tail) { + return std::max(iter.dim_, max_dim(iter_tail...)); +} + +inline void apply_op() {} + +template +inline void apply_op( + int64_t numel, + int64_t offset, + const Op& op, + Args... iters) { + // For 0-dim tensors + if (numel == 1 && max_dim(iters...) == 0) { + op(*iters.data_...); + return; + } + if (offset > 0) + forward(offset, iters...); + // Splitting this into chunks helps the compiler create faster assembly + for (int64_t i = 0; i < numel;) { + for (; iterate_continue(iters...) && i < numel;) { + op(*iters.data_...); + iterate(1, iters...); + i++; + } + iterate_overflow(iters...); + } +} + +/* + Apply a pointwise operator to sequence of tensors + + The calling convention for op is a function/functor that takes the same + number of pointers of type scalar as the number of given tensors. For example, + to compute a = b * c, op would be of the form: + [](scalar* a_val, const scalar* b_val, const scalar* c_val) { a_val[0] = + b_val[0] * c_val[0]; }; +*/ + +template +inline void CPU_tensor_apply2(Tensor tensor1, Tensor tensor2, const Op op) { + if (!_apply_preamble({tensor1, tensor2})) + return; + if (_max_dim_tensors({tensor1, tensor2}) <= 8) { + apply_op( + tensor1.numel(), + 0, + op, + strided_tensor_iter_fixed(tensor1), + strided_tensor_iter_fixed(tensor2)); + } else { + apply_op( + tensor1.numel(), + 0, + op, + strided_tensor_iter(tensor1), + strided_tensor_iter(tensor2)); + } +} + +template +inline void CPU_tensor_apply3( + Tensor tensor1, + Tensor tensor2, + Tensor tensor3, + const Op op) { + if (!_apply_preamble({tensor1, tensor2, tensor3})) + return; + if (_max_dim_tensors({tensor1, tensor2, tensor3}) <= 8) { + apply_op( + tensor1.numel(), + 0, + op, + strided_tensor_iter_fixed(tensor1), + strided_tensor_iter_fixed(tensor2), + strided_tensor_iter_fixed(tensor3)); + } else { + apply_op( + tensor1.numel(), + 0, + op, + strided_tensor_iter(tensor1), + strided_tensor_iter(tensor2), + strided_tensor_iter(tensor3)); + } +} + +template < + typename scalar1, + typename scalar2, + typename scalar3, + typename scalar4, + typename Op> +inline void CPU_tensor_apply4( + Tensor tensor1, + Tensor tensor2, + Tensor tensor3, + Tensor tensor4, + const Op op) { + if (!_apply_preamble({tensor1, tensor2, tensor3, tensor4})) + return; + if (_max_dim_tensors({tensor1, tensor2, tensor3, tensor4}) <= 8) { + apply_op( + tensor1.numel(), + 0, + op, + strided_tensor_iter_fixed(tensor1), + strided_tensor_iter_fixed(tensor2), + strided_tensor_iter_fixed(tensor3), + strided_tensor_iter_fixed(tensor4)); + } else { + apply_op( + tensor1.numel(), + 0, + op, + strided_tensor_iter(tensor1), + strided_tensor_iter(tensor2), + strided_tensor_iter(tensor3), + strided_tensor_iter(tensor4)); + } +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e17403ee7e998021bd44bc9d73caa891f6ce2ead --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.cpp @@ -0,0 +1,311 @@ +#include +#include +#include +#include + +namespace at { + +namespace detail { + +/** + * CPUGeneratorImplStateLegacy is a POD class needed for memcpys + * in torch.get_rng_state() and torch.set_rng_state(). + * It is a legacy class and even though it is replaced with + * at::CPUGeneratorImpl, we need this class and some of its fields + * to support backward compatibility on loading checkpoints. + */ +struct CPUGeneratorImplStateLegacy { + /* The initial seed. */ + uint64_t the_initial_seed; + int left; /* = 1; */ + int seeded; /* = 0; */ + uint64_t next; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + uint64_t state[at::MERSENNE_STATE_N]; /* the array for the state vector */ + + /********************************/ + + /* For normal distribution */ + double normal_x; + double normal_y; + double normal_rho; + int normal_is_valid; /* = 0; */ +}; + +/** + * CPUGeneratorImplState is a POD class containing + * new data introduced in at::CPUGeneratorImpl and the legacy state. It is used + * as a helper for torch.get_rng_state() and torch.set_rng_state() + * functions. + */ +struct CPUGeneratorImplState { + CPUGeneratorImplStateLegacy legacy_pod; + float next_float_normal_sample; + bool is_next_float_normal_sample_valid; +}; + +/** + * PyTorch maintains a collection of default generators that get + * initialized once. The purpose of these default generators is to + * maintain a global running state of the pseudo random number generation, + * when a user does not explicitly mention any generator. + * getDefaultCPUGenerator gets the default generator for a particular + * device. + */ +const Generator& getDefaultCPUGenerator() { + static auto default_gen_cpu = createCPUGenerator(c10::detail::getNonDeterministicRandom()); + return default_gen_cpu; +} + +/** + * Utility to create a CPUGeneratorImpl. Returns a shared_ptr + */ +Generator createCPUGenerator(uint64_t seed_val) { + return make_generator(seed_val); +} + +/** + * Helper function to concatenate two 32 bit unsigned int + * and return them as a 64 bit unsigned int + */ +inline static uint64_t make64BitsFrom32Bits(uint32_t hi, uint32_t lo) { + return (static_cast(hi) << 32) | lo; +} + +} // namespace detail + +/** + * CPUGeneratorImpl class implementation + */ +CPUGeneratorImpl::CPUGeneratorImpl(uint64_t seed_in) + : c10::GeneratorImpl{Device(DeviceType::CPU), DispatchKeySet(c10::DispatchKey::CPU)}, + engine_{seed_in}, + next_float_normal_sample_{std::optional()}, + next_double_normal_sample_{std::optional()} { } + +/** + * Manually seeds the engine with the seed input + * See Note [Acquire lock when using random generators] + */ +void CPUGeneratorImpl::set_current_seed(uint64_t seed) { + next_float_normal_sample_.reset(); + next_double_normal_sample_.reset(); + engine_ = mt19937(seed); +} + +/** + * Sets the offset of RNG state. + * See Note [Acquire lock when using random generators] + */ +void CPUGeneratorImpl::set_offset(uint64_t offset [[maybe_unused]]) { + TORCH_CHECK(false, "CPU Generator does not use offset"); +} + +/** + * Gets the current offset of CPUGeneratorImpl. + */ +uint64_t CPUGeneratorImpl::get_offset() const { + TORCH_CHECK(false, "CPU Generator does not use offset"); +} + +/** + * Gets the current seed of CPUGeneratorImpl. + */ +uint64_t CPUGeneratorImpl::current_seed() const { + return engine_.seed(); +} + +/** + * Gets a nondeterministic random number from /dev/urandom or time, + * seeds the CPUGeneratorImpl with it and then returns that number. + * + * FIXME: You can move this function to Generator.cpp if the algorithm + * in getNonDeterministicRandom is unified for both CPU and CUDA + */ +uint64_t CPUGeneratorImpl::seed() { + auto random = c10::detail::getNonDeterministicRandom(); + this->set_current_seed(random); + return random; +} + +/** + * Sets the internal state of CPUGeneratorImpl. The new internal state + * must be a strided CPU byte tensor and of the same size as CPUGeneratorImplState. + */ +void CPUGeneratorImpl::set_state(const c10::TensorImpl& new_state) { + using detail::CPUGeneratorImplState; + using detail::CPUGeneratorImplStateLegacy; + + static_assert(std::is_standard_layout_v, "CPUGeneratorImplState is not a PODType"); + constexpr size_t size = sizeof(CPUGeneratorImplState); + + detail::check_rng_state(new_state); + + at::mt19937 engine; + auto new_state_size = new_state.numel(); + + TORCH_CHECK(new_state_size == size, "Expected a CPUGeneratorImplState of size ", size, + " but found the input RNG state size to be ", new_state_size); + + auto rng_state = new_state.data_ptr_impl(); + auto legacy_pod = &(rng_state->legacy_pod); + // construct engine_ + // Note that CPUGeneratorImplStateLegacy stored a state array of 64 bit uints, whereas in our + // redefined mt19937, we have changed to a state array of 32 bit uints. Hence, we are + // doing a std::copy. + at::mt19937_data_pod rng_data{}; + std::copy(std::begin(legacy_pod->state), std::end(legacy_pod->state), rng_data.state_.begin()); + rng_data.seed_ = legacy_pod->the_initial_seed; + rng_data.left_ = legacy_pod->left; + rng_data.seeded_ = legacy_pod->seeded; + rng_data.next_ = static_cast(legacy_pod->next); + engine.set_data(rng_data); + TORCH_CHECK(engine.is_valid(), "Invalid mt19937 state"); + this->engine_ = engine; + this->next_float_normal_sample_ = rng_state->is_next_float_normal_sample_valid + ? std::optional(rng_state->next_float_normal_sample) + : std::optional(); + this->next_double_normal_sample_ = legacy_pod->normal_is_valid + ? std::optional(legacy_pod->normal_y) + : std::optional(); +} + +/** + * Gets the current internal state of CPUGeneratorImpl. The internal + * state is returned as a CPU byte tensor. + */ +c10::intrusive_ptr CPUGeneratorImpl::get_state() const { + using detail::CPUGeneratorImplState; + + static const size_t size = sizeof(CPUGeneratorImplState); + static_assert(std::is_standard_layout_v, "CPUGeneratorImplState is not a PODType"); + + auto state_tensor = at::detail::empty_cpu({static_cast(size)}, ScalarType::Byte, std::nullopt, std::nullopt, std::nullopt, std::nullopt); + auto rng_state = state_tensor.data_ptr(); + + // accumulate generator data to be copied into byte tensor + auto accum_state = std::make_unique(); + auto rng_data = this->engine_.data(); + accum_state->legacy_pod.the_initial_seed = rng_data.seed_; + accum_state->legacy_pod.left = rng_data.left_; + accum_state->legacy_pod.seeded = rng_data.seeded_; + accum_state->legacy_pod.next = rng_data.next_; + std::copy(rng_data.state_.begin(), rng_data.state_.end(), std::begin(accum_state->legacy_pod.state)); + accum_state->legacy_pod.normal_x = 0.0; // we don't use it anymore and this is just a dummy + accum_state->legacy_pod.normal_rho = 0.0; // we don't use it anymore and this is just a dummy + accum_state->legacy_pod.normal_is_valid = false; + accum_state->legacy_pod.normal_y = 0.0; + accum_state->next_float_normal_sample = 0.0f; + accum_state->is_next_float_normal_sample_valid = false; + if (this->next_double_normal_sample_) { + accum_state->legacy_pod.normal_is_valid = true; + accum_state->legacy_pod.normal_y = *(this->next_double_normal_sample_); + } + if (this->next_float_normal_sample_) { + accum_state->is_next_float_normal_sample_valid = true; + accum_state->next_float_normal_sample = *(this->next_float_normal_sample_); + } + + memcpy(rng_state, accum_state.get(), size); + return state_tensor.getIntrusivePtr(); +} + +/** + * Gets the DeviceType of CPUGeneratorImpl. + * Used for type checking during run time. + */ +DeviceType CPUGeneratorImpl::device_type() { + return DeviceType::CPU; +} + +/** + * Gets a random 32 bit unsigned integer from the engine + * + * See Note [Acquire lock when using random generators] + */ +uint32_t CPUGeneratorImpl::random() { + return engine_(); +} + +/** + * Gets a random 64 bit unsigned integer from the engine + * + * See Note [Acquire lock when using random generators] + */ +uint64_t CPUGeneratorImpl::random64() { + uint32_t random1 = engine_(); + uint32_t random2 = engine_(); + return detail::make64BitsFrom32Bits(random1, random2); +} + +/** + * Get the cached normal random in float + */ +std::optional CPUGeneratorImpl::next_float_normal_sample() { + return next_float_normal_sample_; +} + +/** + * Get the cached normal random in double + */ +std::optional CPUGeneratorImpl::next_double_normal_sample() { + return next_double_normal_sample_; +} + +/** + * Cache normal random in float + * + * See Note [Acquire lock when using random generators] + */ +void CPUGeneratorImpl::set_next_float_normal_sample(std::optional randn) { + next_float_normal_sample_ = randn; +} + +/** + * Cache normal random in double + * + * See Note [Acquire lock when using random generators] + */ +void CPUGeneratorImpl::set_next_double_normal_sample(std::optional randn) { + next_double_normal_sample_ = randn; +} + +/** + * Get the engine of the CPUGeneratorImpl + */ +at::mt19937 CPUGeneratorImpl::engine() { + return engine_; +} + +/** + * Set the engine of the CPUGeneratorImpl + * + * See Note [Acquire lock when using random generators] + */ +void CPUGeneratorImpl::set_engine(at::mt19937 engine) { + engine_ = engine; +} + +/** + * Public clone method implementation + * + * See Note [Acquire lock when using random generators] + */ +std::shared_ptr CPUGeneratorImpl::clone() const { + return std::shared_ptr(this->clone_impl()); +} + +/** + * Private clone method implementation + * + * See Note [Acquire lock when using random generators] + */ +CPUGeneratorImpl* CPUGeneratorImpl::clone_impl() const { + auto gen = new CPUGeneratorImpl(); + gen->set_engine(engine_); + gen->set_next_float_normal_sample(next_float_normal_sample_); + gen->set_next_double_normal_sample(next_double_normal_sample_); + return gen; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.h b/western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..a0f9cfea8a89c1a88d120f1b0005ee6a33e277f1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/CPUGeneratorImpl.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include +#include + +namespace at { + +struct TORCH_API CPUGeneratorImpl : public c10::GeneratorImpl { + // Constructors + CPUGeneratorImpl(uint64_t seed_in = default_rng_seed_val); + ~CPUGeneratorImpl() override = default; + + // CPUGeneratorImpl methods + std::shared_ptr clone() const; + void set_current_seed(uint64_t seed) override; + void set_offset(uint64_t offset) override; + uint64_t get_offset() const override; + uint64_t current_seed() const override; + uint64_t seed() override; + void set_state(const c10::TensorImpl& new_state) override; + c10::intrusive_ptr get_state() const override; + static c10::DeviceType device_type(); + uint32_t random(); + uint64_t random64(); + std::optional next_float_normal_sample(); + std::optional next_double_normal_sample(); + void set_next_float_normal_sample(std::optional randn); + void set_next_double_normal_sample(std::optional randn); + at::mt19937 engine(); + void set_engine(at::mt19937 engine); + + private: + CPUGeneratorImpl* clone_impl() const override; + at::mt19937 engine_; + std::optional next_float_normal_sample_; + std::optional next_double_normal_sample_; +}; + +namespace detail { + +TORCH_API const Generator& getDefaultCPUGenerator(); +TORCH_API Generator +createCPUGenerator(uint64_t seed_val = default_rng_seed_val); + +} // namespace detail + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DLConvertor.cpp b/western_ai/usa/pytorch/aten/src/ATen/DLConvertor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e514a1b682c6ee809b8c3145c0069e1eb312542 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DLConvertor.cpp @@ -0,0 +1,560 @@ +#include +#include + +using namespace std; +namespace at { + +DLDataType getDLDataType(const Tensor& t) { + DLDataType dtype; + dtype.lanes = 1; + dtype.bits = t.element_size() * 8; + switch (t.scalar_type()) { + case ScalarType::UInt1: + case ScalarType::UInt2: + case ScalarType::UInt3: + case ScalarType::UInt4: + case ScalarType::UInt5: + case ScalarType::UInt6: + case ScalarType::UInt7: + case ScalarType::Byte: + case ScalarType::UInt16: + case ScalarType::UInt32: + case ScalarType::UInt64: + dtype.code = DLDataTypeCode::kDLUInt; + break; + case ScalarType::Int1: + case ScalarType::Int2: + case ScalarType::Int3: + case ScalarType::Int4: + case ScalarType::Int5: + case ScalarType::Int6: + case ScalarType::Int7: + case ScalarType::Char: + dtype.code = DLDataTypeCode::kDLInt; + break; + // NOLINTNEXTLINE(bugprone-branch-clone) + case ScalarType::Double: + dtype.code = DLDataTypeCode::kDLFloat; + break; + case ScalarType::Float: + dtype.code = DLDataTypeCode::kDLFloat; + break; + // NOLINTNEXTLINE(bugprone-branch-clone) + case ScalarType::Int: + dtype.code = DLDataTypeCode::kDLInt; + break; + case ScalarType::Long: + dtype.code = DLDataTypeCode::kDLInt; + break; + case ScalarType::Short: + dtype.code = DLDataTypeCode::kDLInt; + break; + case ScalarType::Half: + dtype.code = DLDataTypeCode::kDLFloat; + break; + case ScalarType::Bool: + dtype.code = DLDataTypeCode::kDLBool; + break; + case ScalarType::ComplexHalf: + case ScalarType::ComplexFloat: + case ScalarType::ComplexDouble: + dtype.code = DLDataTypeCode::kDLComplex; + break; + case ScalarType::BComplex32: + TORCH_CHECK_BUFFER(false, "BComplex32 type is not supported by dlpack"); + break; + case ScalarType::BFloat16: + dtype.code = DLDataTypeCode::kDLBfloat; + break; + // TODO(#146647): use macro here instead of spelling out each shell dtype + case ScalarType::Float8_e5m2: + dtype.code = DLDataTypeCode::kDLFloat8_e5m2; + break; + case ScalarType::Float8_e5m2fnuz: + dtype.code = DLDataTypeCode::kDLFloat8_e5m2fnuz; + break; + case ScalarType::Float8_e4m3fn: + dtype.code = DLDataTypeCode::kDLFloat8_e4m3fn; + break; + case ScalarType::Float8_e4m3fnuz: + dtype.code = DLDataTypeCode::kDLFloat8_e4m3fnuz; + break; + case ScalarType::Float8_e8m0fnu: + dtype.code = DLDataTypeCode::kDLFloat8_e8m0fnu; + break; + case ScalarType::Float4_e2m1fn_x2: + dtype.code = DLDataTypeCode::kDLFloat4_e2m1fn; + dtype.lanes = 2; + dtype.bits = 4; + break; + case ScalarType::QInt8: + case ScalarType::QUInt8: + case ScalarType::QInt32: + case ScalarType::QUInt4x2: + case ScalarType::QUInt2x4: + TORCH_CHECK_BUFFER(false, "QUInt/QInt types are not supported by dlpack"); + break; + case ScalarType::Bits1x8: + case ScalarType::Bits2x4: + case ScalarType::Bits4x2: + case ScalarType::Bits8: + case ScalarType::Bits16: + TORCH_CHECK_BUFFER(false, "Bit types are not supported by dlpack"); + break; + case ScalarType::Undefined: + TORCH_CHECK_BUFFER(false, "Undefined is not a valid ScalarType"); + case ScalarType::NumOptions: + TORCH_CHECK_BUFFER(false, "NumOptions is not a valid ScalarType"); + } + return dtype; +} + +DLDevice torchDeviceToDLDevice(at::Device device) { + DLDevice ctx; + + ctx.device_id = + (device.is_cuda() || device.is_privateuseone() || device.is_mtia()) + ? static_cast(static_cast(device.index())) + : 0; + + switch (device.type()) { + case DeviceType::CPU: + ctx.device_type = DLDeviceType::kDLCPU; + break; + case DeviceType::CUDA: +#ifdef USE_ROCM + // ROCM, if enabled will look like cuda to PyTorch + // while everyone else should see HIP + ctx.device_type = DLDeviceType::kDLROCM; +#else + ctx.device_type = DLDeviceType::kDLCUDA; +#endif + break; + case DeviceType::OPENCL: + ctx.device_type = DLDeviceType::kDLOpenCL; + break; + case DeviceType::HIP: + ctx.device_type = DLDeviceType::kDLROCM; + break; + case DeviceType::XPU: + ctx.device_type = DLDeviceType::kDLOneAPI; + ctx.device_id = at::detail::getXPUHooks().getGlobalIdxFromDevice(device); + break; + case DeviceType::MAIA: + ctx.device_type = DLDeviceType::kDLMAIA; + break; + case DeviceType::PrivateUse1: + ctx.device_type = DLDeviceType::kDLExtDev; + break; + case DeviceType::MTIA: + ctx.device_type = DLDeviceType::kDLExtDev; + break; + case DeviceType::MPS: + ctx.device_type = DLDeviceType::kDLMetal; + break; + default: + TORCH_CHECK_BUFFER(false, "Cannot pack tensors on " + device.str()); + } + + return ctx; +} + +Device dlDeviceToTorchDevice( + DLDeviceType type, + c10::DeviceIndex index, + void* data) { + switch (type) { + case DLDeviceType::kDLCPU: + return at::Device(DeviceType::CPU); +#ifndef USE_ROCM + // if we are compiled under HIP, we cannot do cuda + case DLDeviceType::kDLCUDA: + return at::Device(DeviceType::CUDA, index); +#endif + case DLDeviceType::kDLOpenCL: + return at::Device(DeviceType::OPENCL, index); + case DLDeviceType::kDLROCM: +#ifdef USE_ROCM + // this looks funny, we need to return CUDA here to masquerade + return at::Device(DeviceType::CUDA, index); +#else + return at::Device(DeviceType::HIP, index); +#endif + case DLDeviceType::kDLOneAPI: + TORCH_CHECK(data != nullptr, "Can't get ATen device for XPU without XPU data."); + return at::detail::getXPUHooks().getDeviceFromPtr(data); + case DLDeviceType::kDLMAIA: + return at::Device(DeviceType::MAIA, index); + case DLDeviceType::kDLExtDev: + return at::Device(DeviceType::PrivateUse1, index); + case DLDeviceType::kDLMetal: + return at::Device(DeviceType::MPS, index); + default: + TORCH_CHECK_BUFFER( + false, "Unsupported device_type: ", std::to_string(type)); + } +} + +ScalarType toScalarType(const DLDataType& dtype) { + ScalarType stype = ScalarType::Undefined; + if (dtype.code != DLDataTypeCode::kDLFloat4_e2m1fn) { + TORCH_CHECK_BUFFER( + dtype.lanes == 1, + "ATen does not support lanes != 1 for dtype code", std::to_string(dtype.code)); + } + switch (dtype.code) { + case DLDataTypeCode::kDLUInt: + switch (dtype.bits) { + case 8: + stype = ScalarType::Byte; + break; + case 16: + stype = ScalarType::UInt16; + break; + case 32: + stype = ScalarType::UInt32; + break; + case 64: + stype = ScalarType::UInt64; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kUInt bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLInt: + switch (dtype.bits) { + case 8: + stype = ScalarType::Char; + break; + case 16: + stype = ScalarType::Short; + break; + case 32: + stype = ScalarType::Int; + break; + case 64: + stype = ScalarType::Long; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kInt bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat: + switch (dtype.bits) { + case 16: + stype = ScalarType::Half; + break; + case 32: + stype = ScalarType::Float; + break; + case 64: + stype = ScalarType::Double; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kFloat bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLBfloat: + switch (dtype.bits) { + case 16: + stype = ScalarType::BFloat16; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kFloat bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLComplex: + switch (dtype.bits) { + case 32: + stype = ScalarType::ComplexHalf; + break; + case 64: + stype = ScalarType::ComplexFloat; + break; + case 128: + stype = ScalarType::ComplexDouble; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kFloat bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLBool: + switch (dtype.bits) { + case 8: + stype = ScalarType::Bool; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLBool bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat8_e5m2: + switch (dtype.bits) { + case 8: + stype = ScalarType::Float8_e5m2; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat8_e5m2 bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat8_e5m2fnuz: + switch (dtype.bits) { + case 8: + stype = ScalarType::Float8_e5m2fnuz; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat8_e5m2fnuz bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat8_e4m3fn: + switch (dtype.bits) { + case 8: + stype = ScalarType::Float8_e4m3fn; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat8_e4m3fn bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat8_e4m3fnuz: + switch (dtype.bits) { + case 8: + stype = ScalarType::Float8_e4m3fnuz; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat8_e4m3fnuz bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat8_e8m0fnu: + switch (dtype.bits) { + case 8: + stype = ScalarType::Float8_e8m0fnu; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat8_e8m0fnu bits ", std::to_string(dtype.bits)); + } + break; + case DLDataTypeCode::kDLFloat4_e2m1fn: + switch (dtype.bits) { + case 4: + switch (dtype.lanes) { + case 2: + stype = ScalarType::Float4_e2m1fn_x2; + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat4_e2m1fn lanes ", std::to_string(dtype.lanes)); + } + break; + default: + TORCH_CHECK_BUFFER( + false, "Unsupported kDLFloat4_e2m1fn bits ", std::to_string(dtype.bits)); + } + break; + default: + TORCH_CHECK_BUFFER(false, "Unsupported code ", std::to_string(dtype.code)); + } + return stype; +} + + +namespace { + +int64_t toStorageOffset(int64_t byte_offset, ScalarType stype) { + if (byte_offset == 0) { + return 0; + } + const auto element_size = c10::elementSize(stype); + TORCH_CHECK_VALUE(byte_offset % element_size == 0, "byte offset must be multiple of element size"); + return byte_offset / element_size; +} + +// The templated classes below are needed for supporting both: +// - DLManagedTensor +// - DLManagedTensorVersioned +template +struct ATenDLMTensor { + Tensor handle; + T tensor{}; +}; + +template +void deleter(T* arg) { + delete static_cast*>(arg->manager_ctx); +} + +// Adds version information for DLManagedTensorVersioned. +// This is a no-op for the other types. read_only only applies to the versioned +// struct; the legacy DLManagedTensor has no flags field. +template +void fillVersion(T* tensor, bool read_only) {} + +template <> +void fillVersion( + DLManagedTensorVersioned* tensor, + bool read_only) { + tensor->flags = read_only ? DLPACK_FLAG_BITMASK_READ_ONLY : 0; + tensor->version.major = DLPACK_MAJOR_VERSION; + tensor->version.minor = DLPACK_MINOR_VERSION; +} + +// This function returns a shared_ptr to memory managed DLpack tensor +// constructed out of ATen tensor. When read_only is set, the data is exported +// through const_data_ptr() (avoiding a copy-on-write materialization) and the +// DLPACK_FLAG_BITMASK_READ_ONLY flag is set on the versioned struct. +template +T* toDLPackImpl(const Tensor& src, bool read_only) { + auto atDLMTensor = std::make_unique>(); + atDLMTensor->handle = src; + atDLMTensor->tensor.manager_ctx = atDLMTensor.get(); + atDLMTensor->tensor.deleter = &deleter; + // DLTensor::data is a plain void*, so the read-only path const_casts away the + // const from const_data_ptr(). This is safe: const_data_ptr() does not + // materialize a copy-on-write tensor, and DLPACK_FLAG_BITMASK_READ_ONLY is + // set on the versioned struct (see fillVersion) so the consumer is told not + // to write through the pointer. The mutable path uses mutable_data_ptr(). + if (src.device().type() == kMPS) { + atDLMTensor->tensor.dl_tensor.data = read_only + ? const_cast(src.storage().data()) + : src.storage().mutable_data(); + atDLMTensor->tensor.dl_tensor.byte_offset = src.storage_offset() * c10::elementSize(src.scalar_type()); + } else { + atDLMTensor->tensor.dl_tensor.data = read_only + ? const_cast(src.const_data_ptr()) + : src.mutable_data_ptr(); + atDLMTensor->tensor.dl_tensor.byte_offset = 0; + } + atDLMTensor->tensor.dl_tensor.device = torchDeviceToDLDevice(src.device()); + atDLMTensor->tensor.dl_tensor.ndim = static_cast(src.dim()); + atDLMTensor->tensor.dl_tensor.dtype = getDLDataType(src); + atDLMTensor->tensor.dl_tensor.shape = const_cast(src.sizes().data()); + atDLMTensor->tensor.dl_tensor.strides = const_cast(src.strides().data()); + fillVersion(&atDLMTensor->tensor, read_only); + + return &(atDLMTensor.release()->tensor); +} + +// Explicitly instantiate the template above for both classes. +template DLManagedTensor* toDLPackImpl(const Tensor&, bool); +template DLManagedTensorVersioned* toDLPackImpl(const Tensor&, bool); + +// This function constructs a Tensor from a memory managed DLPack which +// may be represented as either: DLManagedTensor and DLManagedTensorVersioned. +template +at::Tensor fromDLPackImpl(T* src, std::function deleter) { + if (!deleter) { + deleter = [src](void* self [[maybe_unused]]) { + if (src->deleter) { + src->deleter(src); + } + }; + } + + DLTensor& dl_tensor = src->dl_tensor; + Device device = dlDeviceToTorchDevice( + dl_tensor.device.device_type, dl_tensor.device.device_id, dl_tensor.data); + ScalarType stype = toScalarType(dl_tensor.dtype); + + if (!dl_tensor.strides) { + TORCH_CHECK_VALUE(dl_tensor.byte_offset == 0, "Expected zero byte_offset"); + return at::from_blob( + dl_tensor.data, + IntArrayRef(dl_tensor.shape, dl_tensor.ndim), + std::move(deleter), + at::device(device).dtype(stype), + {device}); + } + return at::from_blob( + dl_tensor.data, + IntArrayRef(dl_tensor.shape, dl_tensor.ndim), + IntArrayRef(dl_tensor.strides, dl_tensor.ndim), + toStorageOffset(dl_tensor.byte_offset, stype), + deleter, + at::device(device).dtype(stype), + {device}); +} + +// Explicitly instantiate the template above for both classes. +template at::Tensor fromDLPackImpl(DLManagedTensor* src, std::function deleter); +template at::Tensor fromDLPackImpl(DLManagedTensorVersioned* src, std::function deleter); + +} // namespace + +void toDLPackNonOwning(const Tensor& src, DLTensor* out, bool read_only) { + // Fill in the pre-allocated DLTensor struct with direct pointers + // This is a non-owning conversion - the caller owns the tensor + // and must keep it alive for the duration of DLTensor usage + // See toDLPackImpl for why the read-only const_cast is safe. + out->data = read_only ? const_cast(src.const_data_ptr()) + : src.mutable_data_ptr(); + out->device = torchDeviceToDLDevice(src.device()); + out->ndim = static_cast(src.dim()); + out->dtype = getDLDataType(src); + // sizes() and strides() return pointers to TensorImpl's stable storage + // which remains valid as long as the tensor is alive + out->shape = const_cast(src.sizes().data()); + out->strides = const_cast(src.strides().data()); + out->byte_offset = 0; +} + +DLManagedTensor* toDLPack(const Tensor& src) { + return toDLPackImpl(src, /*read_only=*/false); +} + +DLManagedTensorVersioned* toDLPackVersioned(const Tensor& src) { + return toDLPackImpl(src, /*read_only=*/false); +} + +DLManagedTensorVersioned* toDLPackVersionedReadOnly(const Tensor& src) { + return toDLPackImpl(src, /*read_only=*/true); +} + +Tensor fromDLPack(DLManagedTensor* src, std::function deleter) { + return fromDLPackImpl(src, std::move(deleter)); +} + +Tensor fromDLPackVersioned(DLManagedTensorVersioned* src, std::function deleter) { + return fromDLPackImpl(src, std::move(deleter)); +} + +Tensor maybeCopyTensor( + const Tensor& data, + std::optional optional_dl_device, + std::optional copy) { + bool force_copy = copy.has_value() && *copy; + bool force_move = copy.has_value() && !*copy; + + if (optional_dl_device.has_value()) { + auto device = at::dlDeviceToTorchDevice( + optional_dl_device->device_type, + static_cast(optional_dl_device->device_id)); + + if (device != data.device()) { + TORCH_CHECK_VALUE( + !force_move, + "cannot move (i.e. copy=False) tensor from ", + data.device(), + " to ", + device, + " without copying."); + return data.to(device); + } + } + + if (force_copy) { + return data.clone(); + } + + return data; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DLConvertor.h b/western_ai/usa/pytorch/aten/src/ATen/DLConvertor.h new file mode 100644 index 0000000000000000000000000000000000000000..e0b20243f596072239963c7601572b2744d12398 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DLConvertor.h @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include + +// this converter will: +// 1) take a Tensor object and wrap it in the DLPack tensor +// 2) take a dlpack tensor and convert it to the ATen Tensor + +namespace at { + +TORCH_API ScalarType toScalarType(const DLDataType& dtype); +TORCH_API DLManagedTensor* toDLPack(const Tensor& src); +TORCH_API struct DLManagedTensorVersioned* toDLPackVersioned(const Tensor& src); +// Read-only variant: sets DLPACK_FLAG_BITMASK_READ_ONLY and exports through +// const_data_ptr() so the conversion does not materialize a copy-on-write +// tensor. The consumer must not mutate the data. +TORCH_API struct DLManagedTensorVersioned* toDLPackVersionedReadOnly( + const Tensor& src); +TORCH_API void toDLPackNonOwning( + const Tensor& src, + DLTensor* out, + bool read_only = false); +TORCH_API Tensor +fromDLPack(DLManagedTensor* src, std::function deleter = {}); +TORCH_API Tensor fromDLPackVersioned( + DLManagedTensorVersioned* src, + std::function deleter = {}); +TORCH_API DLDataType getDLDataType(const Tensor& t); +TORCH_API DLDevice getDLContext(const Tensor& tensor, const int64_t& device_id); + +// Copies the Tensor if there's a device mismatch or copy is forced. +// This should be used before actually creating the DLPack capsule. +TORCH_API Tensor maybeCopyTensor( + const Tensor& data, + std::optional optional_dl_device, + std::optional copy); + +// Converts the given at::Device into a DLDevice. +TORCH_API DLDevice torchDeviceToDLDevice(at::Device device); + +// Converts the DLDevice to an ATen device. +TORCH_API Device dlDeviceToTorchDevice( + DLDeviceType type, + c10::DeviceIndex index, + void* data = nullptr); + +// This trait class is used for retrieving different attributes, such as the +// PyCapsule names and conversion functions for both DLPack tensor classes: +// `DLManagedTensor` and `DLManagedTensorVersioned`. +// +// Each specialization should contain the following 2 traits: +// - `capsule`: actual name of the capsule +// - `used`: name of the capsule after using it +// - `toDLPack`: function for converting a tensor into a DLPack capsule +// - `fromDLPack`: function for creating a tensor from a DLPack capsule +// +// While `toDLPack` is the directly exposed to Python, `fromDLPack` is not. +// Although it contains the core implementation, it lacks the required book +// keeping logic contained in its caller `tensor_fromDLPack`. +// +// That said, `fromDLPack` is used directly in a few DLPack tests that live +// inside ATen (no Python available). +template +struct DLPackTraits {}; + +template <> +struct DLPackTraits { + inline static constexpr const char* capsule = "dltensor"; + inline static constexpr const char* used = "used_dltensor"; + inline static auto toDLPack = at::toDLPack; + inline static auto fromDLPack = at::fromDLPack; +}; + +template <> +struct DLPackTraits { + inline static constexpr const char* capsule = "dltensor_versioned"; + inline static constexpr const char* used = "used_dltensor_versioned"; + inline static auto toDLPack = at::toDLPackVersioned; + inline static auto fromDLPack = at::fromDLPackVersioned; +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DTensorState.cpp b/western_ai/usa/pytorch/aten/src/ATen/DTensorState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce64917eb6f19d9f2b9a250e513c141c22b4d3f6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DTensorState.cpp @@ -0,0 +1,17 @@ +#include + +namespace at { + +namespace { +thread_local bool kDTensorAllowImplicitReplication = false; +} + +bool get_dtensor_allow_implicit_replication() { + return kDTensorAllowImplicitReplication; +} + +void set_dtensor_allow_implicit_replication(bool enabled) { + kDTensorAllowImplicitReplication = enabled; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DTensorState.h b/western_ai/usa/pytorch/aten/src/ATen/DTensorState.h new file mode 100644 index 0000000000000000000000000000000000000000..2f9dac4cfcea8a36eb9d8fcff0492af624569c2f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DTensorState.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +namespace at { + +TORCH_API bool get_dtensor_allow_implicit_replication(); +TORCH_API void set_dtensor_allow_implicit_replication(bool enabled); + +struct DTensorAllowImplicitReplication { + DTensorAllowImplicitReplication() + : prev_dtensor_allow_implicit_replication_( + get_dtensor_allow_implicit_replication()) { + set_dtensor_allow_implicit_replication(true); + } + + DTensorAllowImplicitReplication(const DTensorAllowImplicitReplication&) = + delete; + DTensorAllowImplicitReplication& operator=( + const DTensorAllowImplicitReplication&) = delete; + DTensorAllowImplicitReplication(DTensorAllowImplicitReplication&&) = delete; + DTensorAllowImplicitReplication& operator=( + DTensorAllowImplicitReplication&&) = delete; + + ~DTensorAllowImplicitReplication() { + set_dtensor_allow_implicit_replication( + prev_dtensor_allow_implicit_replication_); + } + + private: + bool prev_dtensor_allow_implicit_replication_; +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/Device.h b/western_ai/usa/pytorch/aten/src/ATen/Device.h new file mode 100644 index 0000000000000000000000000000000000000000..77626cce2465850485e137b148845ee38b9ebb4d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Device.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.cpp b/western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc31ffe0ace2bb63d3a04d1a436e8d32594437f1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.cpp @@ -0,0 +1,154 @@ +#include +#include +#include +#include + +namespace at::accelerator { + +std::optional getAccelerator(bool checked) { + // 1. Check PrivateUse1 backends + // We explicitly allow PrivateUse1 and another device at the same time as we + // use this for testing. Whenever a PrivateUse1 device is registered, use it + // first. + // Note that this check is only for hook registration and thus is NOT initializing + // the device or poisoning fork. + if (is_privateuse1_backend_registered()) { + return kPrivateUse1; + } + + // 2. Check runtime backends + // This state is temporary, these runtime checks should be moved to compile-time + // once they provide the new isBuilt API and we are sure they're never in the + // same binary as another accelerator. +#define DETECT_RUNTIME_ACCELERATOR(device_name) \ + if (at::has##device_name()) { \ + return k##device_name; \ + } + + DETECT_RUNTIME_ACCELERATOR(MTIA) + +#undef DETECT_RUNTIME_ACCELERATOR + + // 2. Check compile-time backends + std::optional device_type = std::nullopt; + +#define DETECT_AND_ASSIGN_ACCELERATOR_COMP(device_name) \ + if (at::detail::get##device_name##Hooks().isBuilt()) { \ + TORCH_CHECK( \ + !device_type.has_value(), \ + "Cannot have both " #device_name " and ", \ + device_type.value(), "."); \ + device_type = k##device_name; \ + } + + DETECT_AND_ASSIGN_ACCELERATOR_COMP(CUDA) + DETECT_AND_ASSIGN_ACCELERATOR_COMP(XPU) + DETECT_AND_ASSIGN_ACCELERATOR_COMP(HIP) + DETECT_AND_ASSIGN_ACCELERATOR_COMP(MPS) + DETECT_AND_ASSIGN_ACCELERATOR_COMP(HPU) + if (checked) { + TORCH_CHECK( + device_type, "Cannot access accelerator device when none is available.") + } + return device_type; + +#undef DETECT_AND_ASSIGN_ACCELERATOR_COMP +} + +bool isAccelerator(c10::DeviceType device_type) { + switch (device_type) { + case at::kCUDA: + case at::kMTIA: + case at::kXPU: + case at::kHIP: + case at::kMPS: + case at::kHPU: + case at::kPrivateUse1: + return true; + default: + return false; + } +} + +// NOLINTBEGIN(bugprone-unchecked-optional-access) +c10::DeviceIndex deviceCount() { + const auto device_type = getAccelerator(false); + if (!device_type.has_value()) { + return static_cast(0); + } + c10::impl::VirtualGuardImpl impl(device_type.value()); + return impl.deviceCount(); +} + +void setDeviceIndex(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + impl.setDevice({device_type, device_index}); +} + +c10::DeviceIndex getDeviceIndex() { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + return impl.getDevice().index(); +} + +void setCurrentStream(c10::Stream stream) { + const auto device_type = getAccelerator(true).value(); + TORCH_CHECK( + device_type == stream.device_type(), + "stream's device type ", + c10::DeviceTypeName(stream.device_type()), + " doesn't match the current accelerator ", + c10::DeviceTypeName(device_type)); + c10::impl::VirtualGuardImpl impl(device_type); + impl.exchangeStream(stream); +} + +c10::Stream getCurrentStream(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + return impl.getStream({device_type, device_index}); +} + +void synchronizeDevice(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + // impl.synchronizeDevice should can be safely called from any device + impl.synchronizeDevice(device_index); +} + +c10::DeviceIndex exchangeDevice(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + return impl.exchangeDevice({device_type, device_index}).index(); +} + +c10::DeviceIndex maybeExchangeDevice(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + // Avoid creating a new context if the context for the given device_index + // is not initialized. + impl.uncheckedSetDevice({device_type, device_index}); + return impl.getDevice().index(); +} + +c10::DeviceCapability getDeviceCapability(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + c10::impl::VirtualGuardImpl impl(device_type); + return impl.getDeviceCapability({device_type, device_index}); +} + +void emptyHostCache() { + const auto device_type = getAccelerator(true).value(); + at::getHostAllocator(device_type)->empty_cache(); +} + +const at::Generator& getDefaultGenerator(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + return at::globalContext() + .getAcceleratorHooksInterface(device_type) + .getDefaultGenerator(device_index); +} +// NOLINTEND(bugprone-unchecked-optional-access) + +} // namespace at::accelerator diff --git a/western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.h b/western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.h new file mode 100644 index 0000000000000000000000000000000000000000..7b676fa2685eef3061dce3a2e5ed1b2b499118f4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DeviceAccelerator.h @@ -0,0 +1,126 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace at::accelerator { + +// Note [Accelerator Concept] +// This file defines the top level Accelerator concept for PyTorch. +// A device is an accelerator per the definition here if: +// - It is mutually exclusive with all other accelerators +// - It performs asynchronous compute via a Stream/Event system +// - It provides a set of common APIs as defined by AcceleratorHooksInterface +// +// As of today, accelerator devices are (in no particular order): +// CUDA, MTIA, XPU, HIP, MPS, PrivateUse1 + +// Ensures that only one accelerator is available (at +// compile time if possible) and return it. +// When checked is true, the returned optional always has a value. +TORCH_API std::optional getAccelerator(bool checked = false); + +// Check if the given device type is an accelerator. +TORCH_API bool isAccelerator(c10::DeviceType device_type); + +// Check if the given device type is an accelerator, not the excluded ones. +template < + typename... T, + typename = std::enable_if_t<(std::is_same_v && ...)>> +inline bool isAcceleratorExcluded( + c10::DeviceType device_type, + c10::DeviceType first_excluded, + T... rest_excluded) { + if constexpr (sizeof...(rest_excluded) > 0) { + return device_type != first_excluded && + isAcceleratorExcluded(device_type, rest_excluded...); + } else { + return device_type != first_excluded && isAccelerator(device_type); + } +} + +// Return the number of the device available. Note that this is *REQUIRED* to +// not raise any exception. +TORCH_API c10::DeviceIndex deviceCount(); + +// Set the current device index to the given device index. +TORCH_API void setDeviceIndex(c10::DeviceIndex device_index); + +// Get the current device index. +TORCH_API c10::DeviceIndex getDeviceIndex(); + +// Set the current stream to a given stream. Note that this API doesn't change +// the current device index. +TORCH_API void setCurrentStream(c10::Stream stream); + +// Get the current stream of the given device index. +TORCH_API c10::Stream getCurrentStream(c10::DeviceIndex device_index); + +// Wait (by blocking the calling thread) until all the work previously enqueued +// on the given device index has been completed. +TORCH_API void synchronizeDevice(c10::DeviceIndex device_index); + +// Set the current device index to the given device_index and return the +// original device index that was active before the change. +TORCH_API c10::DeviceIndex exchangeDevice(c10::DeviceIndex device_index); + +// Set the current device index to the given device_index. Avoid creating a new +// context if the context for device_index is not initialized. Return the +// original device index that was active before the change. +TORCH_API c10::DeviceIndex maybeExchangeDevice(c10::DeviceIndex device_index); + +// Get the device capability of the given device index. +TORCH_API c10::DeviceCapability getDeviceCapability( + c10::DeviceIndex device_index); + +// Releases all unused device memory currently held by the accelerator's +// device-side caching allocator. The freed memory becomes available for reuse +// by other applications or processes. +TORCH_API inline void emptyCache() { + const auto device_type = getAccelerator(true).value(); + at::getDeviceAllocator(device_type)->emptyCache(); +} + +// Releases all unused host (pinned) memory currently held by the accelerator's +// host-side caching allocator. The freed memory becomes available for reuse by +// other applications or processes. +TORCH_API void emptyHostCache(); + +TORCH_API inline at::CachingDeviceAllocator::DeviceStats getDeviceStats( + c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + return at::getDeviceAllocator(device_type)->getDeviceStats(device_index); +} + +TORCH_API inline void resetAccumulatedStats(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + at::getDeviceAllocator(device_type)->resetAccumulatedStats(device_index); +} + +TORCH_API inline void resetPeakStats(c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + at::getDeviceAllocator(device_type)->resetPeakStats(device_index); +} + +TORCH_API inline std::pair getMemoryInfo( + c10::DeviceIndex device_index) { + const auto device_type = getAccelerator(true).value(); + return at::getDeviceAllocator(device_type)->getMemoryInfo(device_index); +} + +TORCH_API const at::Generator& getDefaultGenerator( + c10::DeviceIndex device_index); + +} // namespace at::accelerator + +namespace at { +// Keep BC only +using at::accelerator::getAccelerator; +using at::accelerator::isAccelerator; +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DeviceGuard.h b/western_ai/usa/pytorch/aten/src/ATen/DeviceGuard.h new file mode 100644 index 0000000000000000000000000000000000000000..234e00b06c4091c632c5f4637915c8919f276a7c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DeviceGuard.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include // TensorList whyyyyy + +namespace at { + +// Are you here because you're wondering why DeviceGuard(tensor) no +// longer works? For code organization reasons, we have temporarily(?) +// removed this constructor from DeviceGuard. The new way to +// spell it is: +// +// OptionalDeviceGuard guard(device_of(tensor)); + +/// Return the Device of a Tensor, if the Tensor is defined. +inline std::optional device_of(const Tensor& t) { + if (t.defined()) { + return t.device(); + } else { + return std::nullopt; + } +} + +inline std::optional device_of(const std::optional& t) { + return t.has_value() ? device_of(t.value()) : std::nullopt; +} + +/// Return the Device of a TensorList, if the list is non-empty and +/// the first Tensor is defined. (This function implicitly assumes +/// that all tensors in the list have the same device.) +inline std::optional device_of(ITensorListRef t) { + if (!t.empty()) { + return device_of(t.front()); + } else { + return std::nullopt; + } +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DimVector.h b/western_ai/usa/pytorch/aten/src/ATen/DimVector.h new file mode 100644 index 0000000000000000000000000000000000000000..0a854a378782824f756ff054d39965d259054351 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DimVector.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/Dispatch.cpp b/western_ai/usa/pytorch/aten/src/ATen/Dispatch.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f09f0852fc2ccc95c896e7554a70b9890df7d991 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Dispatch.cpp @@ -0,0 +1,15 @@ +#include +#if defined ENABLE_RECORD_KERNEL_FUNCTION_DTYPE +#include + +namespace at::detail { + +void record_kernel_function_dtype(std::string name) { + RECORD_FUNCTION_WITH_SCOPE( + at::RecordScope::KERNEL_FUNCTION_DTYPE, + std::move(name), + c10::ArrayRef{}); +} + +} // namespace at::detail +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/Dispatch.h b/western_ai/usa/pytorch/aten/src/ATen/Dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..043daa20ffd79344cd1e383445d42beb242124c8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Dispatch.h @@ -0,0 +1,798 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __CUDACC__ +#include // For CUDA_VERSION +#endif + +#ifdef TEMPLATE_SELECTIVE_BUILD +#include +#else +namespace at { +/** + * The method should_include_kernel_dtype() returns true/false + * based on whether the switching code for a specific dtype should be + * included based on build time constants generated from tracing model + * execution. This method will be implemented via code-generation and + * included in this file when code-gen is ready. + */ +inline constexpr bool should_include_kernel_dtype( + const char* /*kernel_tag_str*/, + at::ScalarType /*scalar_type*/ +) { + return true; +} +} // namespace at +#endif + +/** + * In the Facebook internal build (using BUCK), this macro is enabled by + * passing in -c pt.enable_record_kernel_dtype=1 when building the tracer + * binary. + */ +#if defined ENABLE_RECORD_KERNEL_FUNCTION_DTYPE +namespace at::detail { +TORCH_API void record_kernel_function_dtype(std::string name); +} // namespace at::detail + +#define RECORD_KERNEL_FUNCTION_DTYPE(NAME, enum_type) \ + at::detail::record_kernel_function_dtype( \ + std::string(NAME) + "$" + toString(enum_type)); +#else +#define RECORD_KERNEL_FUNCTION_DTYPE(NAME, enum_type) +#endif + +#define AT_PRIVATE_CHECK_SELECTIVE_BUILD(enum_type) \ + do { \ + if constexpr (!at::should_include_kernel_dtype( \ + at_dispatch_name, enum_type)) { \ + TORCH_CHECK( \ + false, \ + "dtype '", \ + toString(enum_type), \ + "' not selected for kernel tag ", \ + at_dispatch_name); \ + } \ + } while (0) + +#define AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, HINT, ...) \ + THO_PRIVATE_CASE_TYPE_USING_HINT_TMPL( \ + AT_PRIVATE_CHECK_SELECTIVE_BUILD, enum_type, HINT, __VA_ARGS__) + +#define AT_DISPATCH_CASE(enum_type, ...) \ + AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__) + +#define AT_DISPATCH_CASE_QINT(enum_type, scalar_type, ...) \ + case enum_type: { \ + AT_PRIVATE_CHECK_SELECTIVE_BUILD(enum_type); \ + using scalar_t = scalar_type; \ + using underlying_t [[maybe_unused]] = typename scalar_t::underlying; \ + [[maybe_unused]] const auto& SCALAR_TYPE = enum_type; \ + [[maybe_unused]] const auto& UNDERLYING_TYPE = toUnderlying(enum_type); \ + return __VA_ARGS__(); \ + } + +#define AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \ + enum_type, scalar_type, bitwidth, qmin, qmax, ...) \ + case enum_type: { \ + AT_PRIVATE_CHECK_SELECTIVE_BUILD(enum_type); \ + using scalar_t = scalar_type; \ + using underlying_t [[maybe_unused]] = typename scalar_t::underlying; \ + [[maybe_unused]] const auto& SCALAR_TYPE = enum_type; \ + [[maybe_unused]] const auto& UNDERLYING_TYPE = toUnderlying(enum_type); \ + [[maybe_unused]] int bit_width = bitwidth; \ + [[maybe_unused]] int64_t quant_min = qmin; \ + [[maybe_unused]] int64_t quant_max = qmax; \ + return __VA_ARGS__(); \ + } + +// The AT_DISPATCH_* family of macros provides the ability to +// conveniently generate specializations of a kernel over all of the +// dtypes we care about in PyTorch. We call it "dispatch" because +// we are "dispatching" to the correct, dtype-specific kernel. +// +// A standard usage looks like: +// +// AT_DISPATCH_ALL_TYPES(self.scalar_type(), "op_name", [&] { +// // Your code here, with 'scalar_t' now defined to +// // be the dtype in question +// }); +// +// There are many variations of this macro, so it's important to +// understand exactly /which/ dtypes you want to get instantiated, as +// well as what the "default" set is. +// +// The default set of dtypes that are instantiated (e.g., by +// AT_DISPATCH_ALL_TYPES) are floating point types (float, double), +// and integral types (int32_t, int64_t, int16_t, int8_t, uint8_t), +// but NOT booleans (bool), half-precision floats (Half) or +// complex number (c10::complex, c10::complex). +// This "cut" is somewhat historical (the default types are the +// ones that TH historically supported), but it also reflects the +// fact that the non-default types are "poorly" behaved (booleans +// are NOT integers mod 2, half precision operations ~essentially +// don't exist on CPU, complex numbers are an experimental application). +// +// Here are the questions you should generally ask to decide which +// dispatch you want: +// +// 1. Is this an integral or floating point specific operation? +// (If so, you'll want one of the FLOATING or INTEGRAL macros.) +// +// 2. Should half be supported? (If you're on CPU, the answer is almost +// definitely no. If you do want support, use one of the AND_HALF +// macros) +// +// Much rarer situations: +// +// 3. Should bool be supported? (You often have to write your kernel +// differently if arithmetic operations are involved.) If so, +// Use AT_DISPATCH_ALL_TYPES_AND along with ScalarType::Bool +// +// 4. Should complex be supported? The answer is almost always no, +// unless you are working on "generic" code that should work on +// all dtypes. +// +// Parameters: +// ----------- +// +// 1. The NAME argument is a "tag" that is used to trace and then +// conditionally compile fragments of the case statements such +// that the kernel functions are specialized only for the dtypes +// that are needed. The NAME parameter *must* be a build time +// const char* (can't be std::string, etc...) +// +// Please ensure that the NAME is unique for every implementation +// or you run the risk of over-including code for the kernel +// functions. There is no risk of missing out on any code, so +// it's mostly a risk of a Type-2 error, and not a Type-1 error. +// +// Switch-like syntax: +// ------------------- +// There is also a switch-case like syntax which is useful if a kernel +// needs to be specialized for particular scalar types +// +// AT_DISPATCH_SWITCH(self.scalar_type(), "op_name", +// AT_DISPATCH_CASE_INTEGRAL_TYPES([&] { +// op_integral(iter); +// }) +// AT_DISPATCH_CASE_FLOATING_TYPES([&] { +// op_floating(iter); +// }) +// AT_DISPATCH_CASE(kBool, [&] { +// op_bool(iter); +// }) +// ); +// +// For each AT_DISPATCH_FOO macro, there is a corresponding +// AT_DISPATCH_CASE_FOO macro which can be used inside of an +// AT_DISPATCH_SWITCH block. + +// NB: the the_type variable is not used, but we have kept it for +// backwards compatibility. It's probably not used by anyone though; +// but we're just being safe (and it doesn't hurt.) Note we must +// use it to shut up warnings about unused store. + +#define AT_DISPATCH_SWITCH(TYPE, NAME, ...) \ + THO_DISPATCH_SWITCH_TMPL( \ + RECORD_KERNEL_FUNCTION_DTYPE, \ + TORCH_CHECK_NOT_IMPLEMENTED, \ + TYPE, \ + NAME, \ + __VA_ARGS__) + +#define AT_DISPATCH_CASE_FLOATING_TYPES(...) \ + AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Float, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_TYPES_AND_HALF(...) \ + AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Float, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Half, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_TYPES_AND_HALF(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES_AND_HALF(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_REDUCED_FLOATING_TYPES(...) \ + AT_DISPATCH_CASE(at::ScalarType::Half, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::BFloat16, __VA_ARGS__) + +#define AT_DISPATCH_REDUCED_FLOATING_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_REDUCED_FLOATING_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_TYPES_AND(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_TYPES_AND(SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, ...) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_TYPES_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, ...) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) + +#define AT_DISPATCH_CASE_FLOATING_TYPES_AND5( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, SCALARTYPE5, ...) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_TYPES_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_TYPES_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, __VA_ARGS__)) + +#define AT_DISPATCH_FLOATING_TYPES_AND5( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_TYPES_AND5( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_COMPLEX_TYPES(...) \ + AT_DISPATCH_CASE(at::ScalarType::ComplexDouble, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::ComplexFloat, __VA_ARGS__) + +#define AT_DISPATCH_COMPLEX_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_COMPLEX_TYPES_AND(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_CASE_COMPLEX_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, ...) \ + AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) + +#define AT_DISPATCH_COMPLEX_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_COMPLEX_TYPES_AND(SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_COMPLEX_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_COMPLEX_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(...) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND1(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND1( \ + SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND1( \ + SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, ...) \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND2( \ + SCALARTYPE1, SCALARTYPE2, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, ...) \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND5( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, SCALARTYPE5, ...) \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND5( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND5( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND6( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + ...) \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__) + +#define AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND6( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_FLOATING_AND_COMPLEX_TYPES_AND6( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_INTEGRAL_TYPES(...) \ + AT_DISPATCH_CASE(at::ScalarType::Byte, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Char, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Int, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Long, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Short, __VA_ARGS__) + +#define AT_DISPATCH_INTEGRAL_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_INTEGRAL_TYPES_AND(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_INTEGRAL_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_INTEGRAL_TYPES_AND(SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES(...) \ + AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_QINT_TYPES(...) \ + AT_DISPATCH_CASE_QINT(at::kQInt8, at::qint8, __VA_ARGS__) \ + AT_DISPATCH_CASE_QINT(at::kQUInt8, at::quint8, __VA_ARGS__) \ + AT_DISPATCH_CASE_QINT(at::kQInt32, at::qint32, __VA_ARGS__) + +#define AT_DISPATCH_QINT_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_QINT_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_QINT_TYPES_AND(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_QINT_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_QINT_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_QINT_TYPES_AND(SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_QINT_BYTE_TYPES(...) \ + AT_DISPATCH_CASE_QINT(at::kQInt8, at::qint8, __VA_ARGS__) \ + AT_DISPATCH_CASE_QINT(at::kQUInt8, at::quint8, __VA_ARGS__) + +#define AT_DISPATCH_QINT_BYTE_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_QINT_BYTE_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_QINT_AND_SUB_BYTE_TYPES(...) \ + AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \ + at::kQInt8, at::qint8, CHAR_BIT, SCHAR_MIN, SCHAR_MAX, __VA_ARGS__) \ + AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \ + at::kQUInt8, at::quint8, CHAR_BIT, 0, UCHAR_MAX, __VA_ARGS__) \ + AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \ + at::kQInt32, \ + at::qint32, \ + CHAR_BIT * sizeof(int), \ + INT_MIN, \ + INT_MAX, \ + __VA_ARGS__) \ + AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \ + at::kQUInt4x2, at::quint4x2, 4, 0, 15, __VA_ARGS__) \ + AT_QINT_SUB_BYTE_PRIVATE_CASE_TYPE( \ + at::kQUInt2x4, at::quint2x4, 2, 0, 3, __VA_ARGS__) + +#define AT_DISPATCH_QINT_AND_SUB_BYTE_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_QINT_AND_SUB_BYTE_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(...) \ + AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE_COMPLEX_TYPES(__VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND(SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES_AND(SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND(SCALARTYPE, ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND(SCALARTYPE, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND(SCALARTYPE, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, ...) \ + AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND2(SCALARTYPE1, SCALARTYPE2, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND2( \ + SCALARTYPE1, SCALARTYPE2, ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( \ + SCALARTYPE1, SCALARTYPE2, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND2( \ + SCALARTYPE1, SCALARTYPE2, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \ + AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND3( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND4( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND5( \ + SCALARTYPE1, SCALARTYPE2, SCALARTYPE3, SCALARTYPE4, SCALARTYPE5, ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND5( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND6( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND6( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND6( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND7( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE7, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND7( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND7( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND8( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + SCALARTYPE8, \ + ...) \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX(__VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE1, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE2, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE3, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE4, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE5, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE6, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE7, __VA_ARGS__) \ + AT_DISPATCH_CASE(SCALARTYPE8, __VA_ARGS__) + +#define AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND8( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + SCALARTYPE8, \ + TYPE, \ + NAME, \ + ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_DISPATCH_CASE_ALL_TYPES_AND_COMPLEX_AND8( \ + SCALARTYPE1, \ + SCALARTYPE2, \ + SCALARTYPE3, \ + SCALARTYPE4, \ + SCALARTYPE5, \ + SCALARTYPE6, \ + SCALARTYPE7, \ + SCALARTYPE8, \ + __VA_ARGS__)) + +#define AT_DISPATCH_CASE_BIT_TYPES(...) \ + AT_DISPATCH_CASE(at::ScalarType::Bits1x8, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Bits2x4, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Bits4x2, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Bits8, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Bits16, __VA_ARGS__) + +#define AT_DISPATCH_BIT_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_BIT_TYPES(__VA_ARGS__)) + +#define AT_DISPATCH_INDEX_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::Int, index_t, __VA_ARGS__) \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::Long, index_t, __VA_ARGS__)) diff --git a/western_ai/usa/pytorch/aten/src/ATen/Dispatch_v2.h b/western_ai/usa/pytorch/aten/src/ATen/Dispatch_v2.h new file mode 100644 index 0000000000000000000000000000000000000000..ab8a01833db88d104e89c398dbd102ad14eb2db0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Dispatch_v2.h @@ -0,0 +1,177 @@ +#pragma once + +#include + +// Get AT_DISPATCH_SWITCH and AT_DISPATCH_CASE: +#include + +// This is a new implementation of the AT_DISPATCH macro family from +// ATen/Dispatch.h +// +// The intended usage is: +// +// ScalarType scalar_type; +// +// AT_DISPATCH_V2( +// scalar_type, +// "debug string", +// AT_WRAP([&] { +// ... code to specialize with scalar_t ... +// }), +// kHalf, +// AT_EXPAND(AT_ALL_TYPES), +// ... as many types arguments as needed ... +// ) +// +// For example, given an old style: +// +// AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( +// kComplexHalf, +// kHalf, +// self.scalar_type(), +// "_local_scalar_dense_cpu", +// [&] { +// scalar_t value = *self.data_ptr(); +// r = Scalar(value); +// } +// ) +// +// You now write: +// +// AT_DISPATCH_V2( +// self.scalar_type(), +// "_local_scalar_dense_cpu", +// AT_WRAP([&] { +// scalar_t value = *self.data_ptr(); +// r = Scalar(value); +// }), +// AT_EXPAND(AT_ALL_TYPES), +// AT_EXPAND(AT_COMPLEX_TYPES), +// kComplexHalf, +// kHalf, +// ) +// +// Notably, it sports the following improvements: +// +// - It is not necessary to specify the arity (e.g., +// AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND{2,3,4,...}) +// when using the macro +// +// - It is not necessary to specify each dtype individually; if +// there is a set of related dtypes and you want to dispatch +// over all of them, you can simply say, e.g., AT_EXPAND(AT_INTEGRAL_TYPES) +// in your argument list. +// +// However, you must remember to wrap the payload body in AT_WRAP, or commas +// inside your lambda will be improperly handled. Furthermore, if you more +// entries to ScalarType than can be supported by this macro, it will fail +// with an obscure error (due to attempting to concatenate AT_AP with +// something that is not a number). +// +// The implementation strategy is to use the count arguments trick +// (e.g., as described in https://stackoverflow.com/a/2124385/23845) +// to discover how many dtypes have been passed, and then dispatch to a +// hand-written macro for each arity that applies as many DISPATCH_CASE as +// necessary. The hand-written macros can be regenerated for other arities +// with the script below. +// +// There is some delicacy in the implementation in controlling when +// macro expansion occurs, mediated with AT_EXPAND and AT_GUARD. I mostly +// relied on GPT4 to help me get it right. + +// See documentation above +#define AT_DISPATCH_V2(TYPE, NAME, BODY, ...) \ + THO_DISPATCH_V2_TMPL( \ + AT_DISPATCH_SWITCH, \ + AT_DISPATCH_CASE, \ + TYPE, \ + NAME, \ + AT_WRAP(BODY), \ + __VA_ARGS__) + +// Unused helper macros, kept for BC: +#define AT_AP_VAR(N, T, ...) \ + AT_EXPAND(AT_CONCAT(AT_AP, AT_NUM_ARGS(__VA_ARGS__))(AT_WRAP(N), __VA_ARGS__)) + +// Ensure we never have too many scalar types for the expansion here to +// support. To bump this, you must regenerate the macros below. +static_assert(static_cast(c10::ScalarType::NumOptions) < 60); + +// Python code to regenerate generate code below: +#if 0 + +num_args = 60 + +for i in range(1, num_args+1): + args = ', '.join(f'_{i}' for i in range(1, i+1)) + cases = ' '.join([f'AT_DISPATCH_CASE(_{j}, N)' for j in range(1, i+1)]) + print(f'#define AT_AP{i}(N, {args}) {cases}') + +#endif + +// Begin generated code +// clang-format off + +#define AT_AP1(N, _1) AT_DISPATCH_CASE(_1, N) +#define AT_AP2(N, _1, _2) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) +#define AT_AP3(N, _1, _2, _3) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) +#define AT_AP4(N, _1, _2, _3, _4) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) +#define AT_AP5(N, _1, _2, _3, _4, _5) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) +#define AT_AP6(N, _1, _2, _3, _4, _5, _6) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) +#define AT_AP7(N, _1, _2, _3, _4, _5, _6, _7) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) +#define AT_AP8(N, _1, _2, _3, _4, _5, _6, _7, _8) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) +#define AT_AP9(N, _1, _2, _3, _4, _5, _6, _7, _8, _9) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) +#define AT_AP10(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) +#define AT_AP11(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) +#define AT_AP12(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) +#define AT_AP13(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) +#define AT_AP14(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) +#define AT_AP15(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) +#define AT_AP16(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) +#define AT_AP17(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) +#define AT_AP18(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) +#define AT_AP19(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) +#define AT_AP20(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) +#define AT_AP21(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) +#define AT_AP22(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) +#define AT_AP23(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) +#define AT_AP24(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) +#define AT_AP25(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) +#define AT_AP26(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) +#define AT_AP27(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) +#define AT_AP28(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) +#define AT_AP29(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) +#define AT_AP30(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) +#define AT_AP31(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) +#define AT_AP32(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) +#define AT_AP33(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) +#define AT_AP34(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) +#define AT_AP35(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) +#define AT_AP36(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) +#define AT_AP37(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) +#define AT_AP38(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) +#define AT_AP39(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) +#define AT_AP40(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) +#define AT_AP41(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) +#define AT_AP42(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) +#define AT_AP43(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) +#define AT_AP44(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) +#define AT_AP45(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) +#define AT_AP46(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) +#define AT_AP47(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) +#define AT_AP48(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) +#define AT_AP49(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) +#define AT_AP50(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) +#define AT_AP51(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) +#define AT_AP52(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) +#define AT_AP53(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) +#define AT_AP54(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) +#define AT_AP55(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) +#define AT_AP56(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) +#define AT_AP57(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) +#define AT_AP58(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) AT_DISPATCH_CASE(_58, N) +#define AT_AP59(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) AT_DISPATCH_CASE(_58, N) AT_DISPATCH_CASE(_59, N) +#define AT_AP60(N, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60) AT_DISPATCH_CASE(_1, N) AT_DISPATCH_CASE(_2, N) AT_DISPATCH_CASE(_3, N) AT_DISPATCH_CASE(_4, N) AT_DISPATCH_CASE(_5, N) AT_DISPATCH_CASE(_6, N) AT_DISPATCH_CASE(_7, N) AT_DISPATCH_CASE(_8, N) AT_DISPATCH_CASE(_9, N) AT_DISPATCH_CASE(_10, N) AT_DISPATCH_CASE(_11, N) AT_DISPATCH_CASE(_12, N) AT_DISPATCH_CASE(_13, N) AT_DISPATCH_CASE(_14, N) AT_DISPATCH_CASE(_15, N) AT_DISPATCH_CASE(_16, N) AT_DISPATCH_CASE(_17, N) AT_DISPATCH_CASE(_18, N) AT_DISPATCH_CASE(_19, N) AT_DISPATCH_CASE(_20, N) AT_DISPATCH_CASE(_21, N) AT_DISPATCH_CASE(_22, N) AT_DISPATCH_CASE(_23, N) AT_DISPATCH_CASE(_24, N) AT_DISPATCH_CASE(_25, N) AT_DISPATCH_CASE(_26, N) AT_DISPATCH_CASE(_27, N) AT_DISPATCH_CASE(_28, N) AT_DISPATCH_CASE(_29, N) AT_DISPATCH_CASE(_30, N) AT_DISPATCH_CASE(_31, N) AT_DISPATCH_CASE(_32, N) AT_DISPATCH_CASE(_33, N) AT_DISPATCH_CASE(_34, N) AT_DISPATCH_CASE(_35, N) AT_DISPATCH_CASE(_36, N) AT_DISPATCH_CASE(_37, N) AT_DISPATCH_CASE(_38, N) AT_DISPATCH_CASE(_39, N) AT_DISPATCH_CASE(_40, N) AT_DISPATCH_CASE(_41, N) AT_DISPATCH_CASE(_42, N) AT_DISPATCH_CASE(_43, N) AT_DISPATCH_CASE(_44, N) AT_DISPATCH_CASE(_45, N) AT_DISPATCH_CASE(_46, N) AT_DISPATCH_CASE(_47, N) AT_DISPATCH_CASE(_48, N) AT_DISPATCH_CASE(_49, N) AT_DISPATCH_CASE(_50, N) AT_DISPATCH_CASE(_51, N) AT_DISPATCH_CASE(_52, N) AT_DISPATCH_CASE(_53, N) AT_DISPATCH_CASE(_54, N) AT_DISPATCH_CASE(_55, N) AT_DISPATCH_CASE(_56, N) AT_DISPATCH_CASE(_57, N) AT_DISPATCH_CASE(_58, N) AT_DISPATCH_CASE(_59, N) AT_DISPATCH_CASE(_60, N) + +// End generated code +// clang-format on diff --git a/western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.cpp b/western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..faa6d46560fd72034fd36e4912f3f7af55d33704 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.cpp @@ -0,0 +1,107 @@ +#include +#include + +#ifndef _WIN32 +#include +#include +#else +#include +#include +#endif + +namespace at { + + +#ifndef C10_MOBILE +#ifndef _WIN32 + +// Unix + +static void* checkDL(void* x) { + if (!x) { + TORCH_CHECK_WITH(DynamicLibraryError, false, "Error in dlopen or dlsym: ", dlerror()); + } + + return x; +} +DynamicLibrary::DynamicLibrary(const char* name, const char* alt_name, bool leak_handle_): leak_handle(leak_handle_), handle(dlopen(name, RTLD_LOCAL | RTLD_NOW)) { + if (!handle) { + if (alt_name) { + handle = dlopen(alt_name, RTLD_LOCAL | RTLD_NOW); + if (!handle) { + TORCH_CHECK_WITH(DynamicLibraryError, false, "Error in dlopen for library ", name, "and ", alt_name); + } + } else { + TORCH_CHECK_WITH(DynamicLibraryError, false, "Error in dlopen: ", dlerror()); + } + } +} + +void* DynamicLibrary::sym(const char* name) { + AT_ASSERT(handle); + return checkDL(dlsym(handle, name)); +} + +DynamicLibrary::~DynamicLibrary() { + if (!handle || leak_handle) { + return; + } + dlclose(handle); +} + +#else + +// Windows + +DynamicLibrary::DynamicLibrary(const char* name, const char* alt_name, bool leak_handle_): leak_handle(leak_handle_) { + // NOLINTNEXTLINE(hicpp-signed-bitwise) + HMODULE theModule; + bool reload = true; + auto wname = c10::u8u16(name); + // Check if LOAD_LIBRARY_SEARCH_DEFAULT_DIRS is supported + if (GetProcAddress(GetModuleHandleW(L"KERNEL32.DLL"), "AddDllDirectory") != NULL) { + theModule = LoadLibraryExW( + wname.c_str(), + NULL, + LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (theModule != NULL || (GetLastError() != ERROR_MOD_NOT_FOUND)) { + reload = false; + } + } + + if (reload) { + theModule = LoadLibraryW(wname.c_str()); + } + + if (theModule) { + handle = theModule; + } else { + char buf[256]; + DWORD dw = GetLastError(); + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + buf, (sizeof(buf) / sizeof(char)), NULL); + TORCH_CHECK_WITH(DynamicLibraryError, false, "error in LoadLibrary for ", name, ". WinError ", dw, ": ", buf); + } +} + +void* DynamicLibrary::sym(const char* name) { + AT_ASSERT(handle); + FARPROC procAddress = GetProcAddress((HMODULE)handle, name); + if (!procAddress) { + TORCH_CHECK_WITH(DynamicLibraryError, false, "error in GetProcAddress"); + } + return (void*)procAddress; +} + +DynamicLibrary::~DynamicLibrary() { + if (!handle || leak_handle) { + return; + } + FreeLibrary((HMODULE)handle); +} + +#endif +#endif + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.h b/western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.h new file mode 100644 index 0000000000000000000000000000000000000000..8529b4025ab01871f6b0e9da7074e25e2d617adc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/DynamicLibrary.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include + +namespace c10 { + +class DynamicLibraryError : public Error { + using Error::Error; +}; + +} // namespace c10 + +namespace at { + +struct DynamicLibrary { + AT_DISALLOW_COPY_AND_ASSIGN(DynamicLibrary); + DynamicLibrary(DynamicLibrary&& other) = delete; + DynamicLibrary& operator=(DynamicLibrary&&) = delete; + + TORCH_API DynamicLibrary( + const char* name, + const char* alt_name = nullptr, + bool leak_handle = false); + + TORCH_API void* sym(const char* name); + + TORCH_API ~DynamicLibrary(); + + private: + bool leak_handle; + void* handle = nullptr; +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.cpp b/western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d45d49401f4ebfda32b792c942bc428b91ef55a8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.cpp @@ -0,0 +1,483 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include + +#include + +namespace at::detail { +namespace { +c10::Allocator* GetCPUAllocatorMaybePinned(bool pin_memory) { + if (pin_memory) { + // NB: This is not quite right, if you somehow had both CUDA and PrivateUse1 initialized + // in the same PyTorch build, you would ONLY ever get the CUDA pinned memory allocator. + // To properly support this, see https://github.com/pytorch/pytorch/issues/14560 + + std::optional opt_device_type = std::nullopt; + // As mentioned in Note [Accelerator Context], the accelerators in PyTorch should be mutually exclusive, + // and PrivateUse1 has the highest priority, followed by CUDA; + // However, since exclusivity between accelerators cannot be guaranteed at present, + // in order to ensure backward compatibility (previously the default was CUDA), CUDA are prioritized. + if (at::globalContext().hasCUDA()) { + opt_device_type = c10::DeviceType::CUDA; + } else { + opt_device_type = at::getAccelerator(false); + } + if (opt_device_type.has_value()) { + return at::globalContext().getPinnedMemoryAllocator(opt_device_type); + } else { + TORCH_CHECK( + false, + "pin_memory=True requires a CUDA or other accelerator backend; " + "no pinned memory allocator is available on this system.") + } + } + + return c10::GetCPUAllocator(); +} + +#ifndef C10_MOBILE +constexpr uint64_t storage_max() { + // int64_t and size_t are used somewhat inconsistently throughout ATen. + // To be safe, storage size calculations must fit in both types. + constexpr auto int64_max = static_cast( + std::numeric_limits::max()); + constexpr auto size_max = static_cast( + std::numeric_limits::max()); + return std::min(int64_max, size_max); +} +#endif + +inline void raise_warning_for_complex_half(ScalarType dtype) { + if (dtype == kComplexHalf) { + TORCH_WARN_ONCE( + "ComplexHalf support is experimental and many operators don't support it yet."); + } else if (dtype == kBComplex32) { + TORCH_WARN_ONCE( + "BComplex32 support is experimental and many operators don't support it yet."); + } +} + +} // namespace (anonymous) + +size_t computeStorageNbytesContiguous( + IntArrayRef sizes, + size_t itemsize_bytes, + size_t storage_offset + ) { + // Ignore overflow checks on mobile +#ifndef C10_MOBILE + uint64_t size = 1; + bool overflowed = c10::safe_multiplies_u64(sizes, &size); + overflowed |= c10::add_overflows(size, storage_offset, &size); + overflowed |= c10::mul_overflows(size, itemsize_bytes, &size); + overflowed |= size > storage_max(); + TORCH_CHECK(!overflowed, + "Storage size calculation overflowed with sizes=", sizes); + return static_cast(size); +#else + const auto numel = c10::multiply_integers(sizes); + return itemsize_bytes * (storage_offset + numel); +#endif +} + +size_t computeStorageNbytes( + IntArrayRef sizes, + IntArrayRef strides, + size_t itemsize_bytes, + size_t storage_offset + ) { + TORCH_CHECK( + sizes.size() == strides.size(), + "dimensionality of sizes (", + sizes.size(), + ") must match dimensionality of strides (", + strides.size(), + ")"); + + // Ignore overflow checks on mobile +#ifndef C10_MOBILE + // size of the underlying storage is 1 bigger than the offset + // of the last element according to stride + uint64_t size = storage_offset + 1; + bool overflowed = false; + for (const auto i : c10::irange(sizes.size())) { + if (sizes[i] == 0) { + return 0; + } + + uint64_t strided_size = 0; + overflowed |= c10::mul_overflows(strides[i], sizes[i] - 1, &strided_size); + overflowed |= c10::add_overflows(size, strided_size, &size); + } + overflowed |= c10::mul_overflows(size, itemsize_bytes, &size); + overflowed |= size > storage_max(); + TORCH_CHECK(!overflowed, + "Storage size calculation overflowed with sizes=", + sizes, " and strides=", strides); + return static_cast(size); +#else + // size of the underlying storage is 1 bigger than the offset + // of the last element according to stride + uint64_t size = 1; + for (const auto i : c10::irange(sizes.size())) { + if (sizes[i] == 0) { + return 0; + } + + size += strides[i] * (sizes[i] - 1); + } + return itemsize_bytes * (storage_offset + size); +#endif +} + +SymInt computeStorageNbytesContiguous( + SymIntArrayRef sizes, + const SymInt& itemsize_bytes, + const SymInt& storage_offset + ) { + const auto numel = c10::multiply_integers(sizes); + return itemsize_bytes * (storage_offset + numel); +} + +// not including mobile-only macros in this function, +// since mobile shouldn't be using symints. +SymInt computeStorageNbytes( + SymIntArrayRef sizes, + SymIntArrayRef strides, + const SymInt& itemsize_bytes, + const SymInt& storage_offset + ) { + TORCH_CHECK( + sizes.size() == strides.size(), + "dimensionality of sizes (", + sizes.size(), + ") must match dimensionality of strides (", + strides.size(), + ")"); + + // size of the underlying storage is 1 bigger than the offset + // of the last element according to stride + SymInt size = 1; + for (const auto i : c10::irange(sizes.size())) { + if (TORCH_GUARD_OR_FALSE(sizes[i].sym_eq(0))) { + return 0; + } + + // NOTE: while this can technically return negative sizes for + // 0-element tensors, there's a check in TensorShape:set_storage_meta__symint + // that skips setting nbytes with unbacked expressions. + // Would probably be safer to wrap this with a max(*, 0), + // once our min/max symbolic reasoning improves. + size += strides[i] * (sizes[i] - 1); + } + return itemsize_bytes * (storage_offset + size); +} + +template +static TensorBase _empty_generic( + ArrayRef size, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type, + std::optional memory_format_opt) { + at::detail::check_size_nonnegative(size); + at::detail::raise_warning_for_complex_half(scalar_type); + caffe2::TypeMeta dtype = scalarTypeToTypeMeta(scalar_type); + auto size_bytes = computeStorageNbytesContiguous(size, dtype.itemsize()); + auto storage_impl = c10::make_intrusive( + c10::StorageImpl::use_byte_size_t(), + size_bytes, + allocator, + /*resizeable=*/true); + + auto tensor = detail::make_tensor_base( + std::move(storage_impl), ks, dtype); + // Default TensorImpl has size [0] + // NB: test for meta dispatch key to avoid guarding on zero-ness + if (ks.has(c10::DispatchKey::Meta) || size.size() != 1 || size[0] != 0) { + tensor.unsafeGetTensorImpl()->generic_set_sizes_contiguous(size); + } + + if (memory_format_opt.has_value()) { + // Restriding a just-created empty contiguous tensor does nothing. + if (*memory_format_opt != MemoryFormat::Contiguous) { + tensor.unsafeGetTensorImpl()->empty_tensor_restride(*memory_format_opt); + } + } + + return tensor; +} + +TensorBase empty_generic( + IntArrayRef size, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type, + std::optional memory_format_opt) { + return _empty_generic(size, allocator, ks, scalar_type, memory_format_opt); +} + +TensorBase empty_generic_symint( + SymIntArrayRef size, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type, + std::optional memory_format_opt) { + return _empty_generic(size, allocator, ks, scalar_type, memory_format_opt); +} + +template +static TensorBase _empty_strided_generic( + T size, + T stride, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type) { + at::detail::check_size_nonnegative(size); + at::detail::raise_warning_for_complex_half(scalar_type); + caffe2::TypeMeta dtype = scalarTypeToTypeMeta(scalar_type); + auto size_bytes = computeStorageNbytes(size, stride, dtype.itemsize()); + auto storage_impl = c10::make_intrusive( + c10::StorageImpl::use_byte_size_t(), + size_bytes, + allocator, + /*resizeable=*/true); + + auto tensor = detail::make_tensor_base( + std::move(storage_impl), ks, dtype); + tensor.unsafeGetTensorImpl()->set_sizes_and_strides(size, stride); + return tensor; +} + +TensorBase empty_strided_generic( + IntArrayRef size, + IntArrayRef stride, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type) { + return _empty_strided_generic(size, stride, allocator, ks, scalar_type); +} + +TensorBase empty_strided_symint_generic( + SymIntArrayRef size, + SymIntArrayRef stride, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type) { + return _empty_strided_generic(size, stride, allocator, ks, scalar_type); +} + +TensorBase empty_cpu(IntArrayRef size, ScalarType dtype, bool pin_memory, + std::optional memory_format_opt) { + auto allocator = GetCPUAllocatorMaybePinned(pin_memory); + constexpr c10::DispatchKeySet cpu_ks(c10::DispatchKey::CPU); + return empty_generic(size, allocator, cpu_ks, dtype, memory_format_opt); +} + +TensorBase empty_cpu( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::CPU); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided); + + auto pin_memory = pinned_memory_or_default(pin_memory_opt); + auto dtype = dtype_or_default(dtype_opt); + return empty_cpu(size, dtype, pin_memory, memory_format_opt); +} + +TensorBase empty_cpu( + IntArrayRef size, const TensorOptions &options) { + return at::detail::empty_cpu( + size, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt(), + options.memory_format_opt()); +} + +TensorBase empty_strided_cpu(IntArrayRef size, IntArrayRef stride, + ScalarType dtype, bool pin_memory) { + auto allocator = at::detail::GetCPUAllocatorMaybePinned(pin_memory); + constexpr c10::DispatchKeySet cpu_ks(c10::DispatchKey::CPU); + return at::detail::empty_strided_generic( + size, stride, allocator, cpu_ks, dtype); +} + +TensorBase empty_strided_cpu( + IntArrayRef size, + IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::CPU); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided); + + auto pin_memory = pinned_memory_or_default(pin_memory_opt); + auto dtype = dtype_or_default(dtype_opt); + return at::detail::empty_strided_cpu(size, stride, dtype, pin_memory); +} + +TensorBase empty_strided_cpu( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions &options) { + return at::detail::empty_strided_cpu( + size, + stride, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt()); +} + +// The meta allocator ignores whatever allocation is requested and always +// gives you nullptr +struct MetaAllocator final : public at::Allocator { + MetaAllocator() = default; + ~MetaAllocator() override = default; + static void deleter(void* const pointer) { + TORCH_INTERNAL_ASSERT(!pointer); + } + DataPtr allocate(const size_t nbytes [[maybe_unused]]) override { + return {nullptr, nullptr, &deleter, at::Device(DeviceType::Meta)}; + } + DeleterFnPtr raw_deleter() const override { + return deleter; + } + void copy_data(void* dest, const void* src, std::size_t count) const final {} +}; + +static MetaAllocator g_meta_alloc; + +REGISTER_ALLOCATOR(kMeta, &g_meta_alloc) + +TensorBase empty_meta(IntArrayRef size, ScalarType dtype, + std::optional memory_format_opt) { + auto *allocator = GetAllocator(kMeta); + constexpr c10::DispatchKeySet meta_dks(c10::DispatchKey::Meta); + return at::detail::empty_generic( + size, allocator, meta_dks, dtype, memory_format_opt); +} + +TensorBase empty_meta( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt +) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::Meta); + // NB: because there is no SparseMeta (yet), non-strided layout is + // exerciseable + TORCH_CHECK_NOT_IMPLEMENTED( + layout_or_default(layout_opt) == Layout::Strided, + "non-strided meta tensors not supported yet" + ); + + auto dtype = dtype_or_default(dtype_opt); + return empty_meta(size, dtype, memory_format_opt); +} + +TensorBase empty_symint_meta( + SymIntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt +) { + auto *allocator = GetAllocator(kMeta); + constexpr c10::DispatchKeySet ks(c10::DispatchKey::Meta); + auto scalar_type = dtype_or_default(dtype_opt); + return _empty_generic(size, allocator, ks, scalar_type, memory_format_opt); +} + +TensorBase empty_meta( + IntArrayRef size, const TensorOptions &options) { + return at::detail::empty_meta( + size, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt(), + options.memory_format_opt()); +} + +TensorBase empty_strided_meta(IntArrayRef size, IntArrayRef stride, + ScalarType dtype) { + auto *allocator = GetAllocator(kMeta); + constexpr c10::DispatchKeySet meta_dks(c10::DispatchKey::Meta); + return at::detail::empty_strided_generic( + size, stride, allocator, meta_dks, dtype); +} + +TensorBase empty_strided_meta( + IntArrayRef size, + IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::Meta); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided); + + auto dtype = dtype_or_default(dtype_opt); + return at::detail::empty_strided_meta(size, stride, dtype); +} + +TensorBase empty_strided_meta( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions &options) { + return at::detail::empty_strided_meta( + size, + stride, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt()); +} + +TensorBase empty_strided_symint_meta(SymIntArrayRef size, SymIntArrayRef stride, + ScalarType dtype) { + auto *allocator = GetAllocator(kMeta); + constexpr c10::DispatchKeySet meta_dks(c10::DispatchKey::Meta); + return at::detail::empty_strided_symint_generic( + size, stride, allocator, meta_dks, dtype); +} + +TensorBase empty_strided_symint_meta( + SymIntArrayRef size, + SymIntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device_or_default(device_opt).type() == DeviceType::Meta); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided); + + auto dtype = dtype_or_default(dtype_opt); + return at::detail::empty_strided_symint_meta(size, stride, dtype); +} + +TensorBase empty_strided_symint_meta( + SymIntArrayRef size, + SymIntArrayRef stride, + const TensorOptions &options) { + return at::detail::empty_strided_symint_meta( + size, + stride, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt()); +} + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.h b/western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.h new file mode 100644 index 0000000000000000000000000000000000000000..5dc8dc904841738e48bc0e22fe8b4e55553c1014 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/EmptyTensor.h @@ -0,0 +1,166 @@ +#pragma once +#include + +namespace at::detail { + +inline void check_size_nonnegative(ArrayRef size) { + for (const auto& x : size) { + TORCH_CHECK( + x >= 0, + "Trying to create tensor with negative dimension ", + x, + ": ", + size); + } +} + +inline void check_size_nonnegative(ArrayRef size) { + for (const auto& x : size) { + TORCH_SYM_CHECK( + x.sym_ge(0), + "Trying to create tensor with negative dimension ", + x, + ": ", + size); + } +} + +TORCH_API size_t computeStorageNbytesContiguous( + IntArrayRef sizes, + size_t itemsize, + size_t storage_offset = 0); +TORCH_API SymInt computeStorageNbytesContiguous( + SymIntArrayRef sizes, + const SymInt& itemsize, + const SymInt& storage_offset = 0); +TORCH_API size_t computeStorageNbytes( + IntArrayRef sizes, + IntArrayRef strides, + size_t itemsize, + size_t storage_offset = 0); +TORCH_API SymInt computeStorageNbytes( + SymIntArrayRef sizes, + SymIntArrayRef strides, + const SymInt& itemsize, + const SymInt& storage_offset = 0); + +TORCH_API TensorBase empty_generic( + IntArrayRef size, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type, + std::optional memory_format_opt); + +TORCH_API TensorBase empty_generic_symint( + SymIntArrayRef size, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type, + std::optional memory_format_opt); + +TORCH_API TensorBase empty_strided_generic( + IntArrayRef size, + IntArrayRef stride, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type); + +TORCH_API TensorBase empty_strided_symint_generic( + SymIntArrayRef size, + SymIntArrayRef stride, + c10::Allocator* allocator, + c10::DispatchKeySet ks, + ScalarType scalar_type); + +TORCH_API TensorBase empty_cpu( + IntArrayRef size, + ScalarType dtype, + bool pin_memory = false, + std::optional memory_format_opt = std::nullopt); + +TORCH_API TensorBase empty_cpu( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt); + +TORCH_API TensorBase empty_cpu(IntArrayRef size, const TensorOptions& options); + +TORCH_API TensorBase empty_strided_cpu( + IntArrayRef size, + IntArrayRef stride, + ScalarType dtype, + bool pin_memory = false); + +TORCH_API TensorBase empty_strided_cpu( + IntArrayRef size, + IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt); + +TORCH_API TensorBase empty_strided_cpu( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions& options); + +TORCH_API TensorBase empty_meta( + IntArrayRef size, + ScalarType dtype, + std::optional memory_format_opt = std::nullopt); + +TORCH_API TensorBase empty_meta( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt); + +TORCH_API TensorBase empty_symint_meta( + SymIntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt); + +TORCH_API TensorBase empty_meta(IntArrayRef size, const TensorOptions& options); + +TORCH_API TensorBase +empty_strided_meta(IntArrayRef size, IntArrayRef stride, ScalarType dtype); + +TORCH_API TensorBase empty_strided_meta( + IntArrayRef size, + IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt); + +TORCH_API TensorBase empty_strided_meta( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions& options); + +TORCH_API TensorBase empty_strided_symint_meta( + SymIntArrayRef size, + SymIntArrayRef stride, + ScalarType dtype); + +TORCH_API TensorBase empty_strided_symint_meta( + SymIntArrayRef size, + SymIntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt); + +TORCH_API TensorBase empty_strided_symint_meta( + SymIntArrayRef size, + SymIntArrayRef stride, + const TensorOptions& options); + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/ExpandBase.h b/western_ai/usa/pytorch/aten/src/ATen/ExpandBase.h new file mode 100644 index 0000000000000000000000000000000000000000..d59a2714455873cf776242bd04157130911c8b28 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/ExpandBase.h @@ -0,0 +1,30 @@ +#include + +// Broadcasting utilities for working with TensorBase +namespace at { +namespace internal { +TORCH_API TensorBase expand_slow_path(const TensorBase& self, IntArrayRef size); +} // namespace internal + +inline c10::MaybeOwned expand_size( + const TensorBase& self, + IntArrayRef size) { + if (size.equals(self.sizes())) { + return c10::MaybeOwned::borrowed(self); + } + return c10::MaybeOwned::owned( + at::internal::expand_slow_path(self, size)); +} +c10::MaybeOwned expand_size(TensorBase&& self, IntArrayRef size) = + delete; + +inline c10::MaybeOwned expand_inplace( + const TensorBase& tensor, + const TensorBase& to_expand) { + return expand_size(to_expand, tensor.sizes()); +} +c10::MaybeOwned expand_inplace( + const TensorBase& tensor, + TensorBase&& to_expand) = delete; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.cpp b/western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4931be60f7dfb71e44795ddf510477268e12aa5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.cpp @@ -0,0 +1,230 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#include + +namespace at { +namespace internal { +TensorBase expand_slow_path(const TensorBase &self, IntArrayRef size) { + return OptionalTensorRef(self)->expand(size); +} +} // namespace internal + +namespace { +// NOTE: are_expandable did a similar check, please keep them sync if change is needed +template +Container infer_size_impl(ArrayType a, ArrayType b) { + // Use ptrdiff_t to ensure signed comparison. + auto dimsA = static_cast(a.size()); + auto dimsB = static_cast(b.size()); + auto ndim = dimsA > dimsB ? dimsA : dimsB; + Container expandedSizes(ndim); + + for (ptrdiff_t i = ndim - 1; i >= 0; --i) { + ptrdiff_t offset = ndim - 1 - i; + ptrdiff_t dimA = dimsA - 1 - offset; + ptrdiff_t dimB = dimsB - 1 - offset; + auto sizeA = (dimA >= 0) ? a[dimA] : 1; + auto sizeB = (dimB >= 0) ? b[dimB] : 1; + + // If we know for sure one of them is 1, we are done. + // otherwise for unbacked we assume non-broadcasting path. + // Unbacked semantics should match python infer_size fake_impl. + if (!TORCH_GUARD_OR_FALSE(sym_eq(sizeA, 1)) && !TORCH_GUARD_OR_FALSE(sym_eq(sizeB, 1))) { + TORCH_MAYBE_SYM_CHECK(sym_eq(sizeA, sizeB), + "The size of tensor a (", sizeA, + ") must match the size of tensor b (", sizeB, + ") at non-singleton dimension ", i); + } + // 1s map to the other size (even 0). + expandedSizes[i] = TORCH_GUARD_OR_FALSE(sym_eq(sizeA, 1)) ? sizeB : sizeA; + } + + return expandedSizes; +} +} + +std::vector infer_size(IntArrayRef a, IntArrayRef b) { + return infer_size_impl>(a, b); +} + +std::vector infer_size_symint(SymIntArrayRef a, SymIntArrayRef b) { + return infer_size_impl>(a, b); +} + +DimVector infer_size_dimvector(IntArrayRef a, IntArrayRef b) { + return infer_size_impl(a, b); +} + +SymDimVector infer_size_symdimvector(SymIntArrayRef a, SymIntArrayRef b) { + return infer_size_impl(a, b); +} + +template +C10_ALWAYS_INLINE static InferExpandGeometryResult inferExpandGeometryImpl( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes) { + int64_t ndim = static_cast(sizes.size()); + int64_t tensor_dim = static_cast(tensor_sizes.size()); + + if (tensor_dim == 0) { + return InferExpandGeometryResult(sizes, ndim); + } + + InferExpandGeometryResult result(ndim); + auto& expandedSizes = result.sizes; + auto& expandedStrides = result.strides; + + // create a new geometry for the tensors + for (int64_t i = ndim - 1; i >= 0; --i) { + int64_t offset = ndim - 1 - i; + int64_t dim = tensor_dim - 1 - offset; + int64_t size = (dim >= 0) ? tensor_sizes[dim] : 1; + int64_t stride = (dim >= 0) ? tensor_strides[dim] + : expandedSizes[i + 1] * expandedStrides[i + 1]; + int64_t targetSize = sizes[i]; + if (targetSize == -1) { + TORCH_CHECK( + dim >= 0, + "The expanded size of the tensor (", + targetSize, + ") isn't allowed in a leading, non-existing dimension ", + i); + targetSize = size; + } + if (size != targetSize) { + TORCH_CHECK( + size == 1, + "The expanded size of the tensor (", + targetSize, + ") must match the existing size (", + size, + ") at non-singleton dimension ", + i, + ". Target sizes: ", + sizes, + ". Tensor sizes: ", + tensor_sizes); + size = targetSize; + stride = 0; + } + expandedSizes[i] = size; + expandedStrides[i] = stride; + } + return result; +} + +std::tuple, std::vector> inferExpandGeometry( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes) { + auto result = inferExpandGeometryImpl>( + tensor_sizes, tensor_strides, sizes); + return std::make_tuple(std::move(result.sizes), std::move(result.strides)); +} + +InferExpandGeometryResult inferExpandGeometry_dimvector( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes) { + return inferExpandGeometryImpl( + tensor_sizes, tensor_strides, sizes); +} + + +// This function returns a dense and non-overlapping strides, which keeps the same layout permutation +// as the input `tensor_strides`, computed based on the input `tensor_sizes`. +// Note: +// 1. This function expects the inputs `tensor_strides` and `tensor_sizes` are non-dense or overlapping, +// If the inputs are densed and non-overlapping, the output strides will be the same as `tensor_strides`. +// However, this function won't check whether inputs are dense or overlapping, so the whole function will +// still be executed even the inputs are already dense and non-overlapping, this will cause slowness. +// +// Please verify whether the inputs are non-dense or overlapping before calling this function if possible, +// if the inputs come from a tensor, you can check this through `is_non_overlapping_and_dense()` +// +// 2. The strides propagation rule that is used in this function is exactily the same as what is being used in +// TensorIterator. Please refer to https://github.com/pytorch/pytorch/pull/42922 for more details + +std::vector infer_dense_strides(IntArrayRef tensor_sizes, IntArrayRef tensor_strides) { + + TORCH_CHECK(tensor_sizes.size() == tensor_strides.size(), + "Input sizes and strides should have same size but got ", tensor_sizes.size(), " and ", tensor_strides.size()); + + size_t ndim = tensor_sizes.size(); + if (ndim == 0) { + return {}; + } + if (ndim == 1) { + return {1}; + } + + std::vector perm(ndim); + // initialize perm with n-1, n-2, ..., 1, 0 + std::iota(perm.rbegin(), perm.rend(), 0); + + // The following sorting algorithm has exactly the same behavior as TensorIterator + // This is to make sure we have the same stride propagation everywhere. + + // return -1 if dim0 should come before dim1 + // return 1 if dim0 should come after dim1 + // return 0 if comparison is ambiguous + auto should_swap = [&](size_t dim0, size_t dim1) { + int64_t stride0 = tensor_strides[dim0]; + int64_t stride1 = tensor_strides[dim1]; + + // if any stride is 0, treat it as ambiguous comparison to + // keep the same behavior as TensorIterator + if (stride0 == 0 || stride1 == 0) { + return 0; + } + if (stride0 < stride1) { + return -1; + } + if (stride0 > stride1) { + return 1; + } + // for equal strides, the dimension with smaller size goes front + if (tensor_sizes[dim0] > tensor_sizes[dim1]) { + return 1; + } + return 0; + }; + + // Insertion sort (stable) indices in `perm` based on input tensor's stride and shape, + // all dimensions with 0 stride won't move. This is the same behavior as TensorIterator. + // eg. Given tensor with size/stride (6, 5, 4, 3, 2)/(6, 0, 120, 0, 1), the initial `perm` + // is (4, 3, 2, 1, 0) and the sorted `perm` will be (4, 3, 0, 1, 2) + for (const auto i : c10::irange(1, ndim)) { + auto dim1 = i; + for (const auto j : c10::irange(1, i + 1)) { + auto dim0 = i - j; + int comparison = should_swap(perm[dim0], perm[dim1]); + if (comparison > 0) { + std::swap(perm[dim0], perm[dim1]); + dim1 = dim0; + } + else if (comparison < 0) { + break; + } + } + } + + // compute output strides which preserves the input tensor's memory layout + std::vector out_strides(ndim); + int64_t curr_stride = 1; + for (const auto i : c10::irange(ndim)) { + int64_t idx = perm[i]; + out_strides[idx] = curr_stride; + // Note: for size 0, we simply treated it as 1, it really doesn't matter here + // since the total number of element is 0. + if (tensor_sizes[idx] > 1) { + curr_stride *= tensor_sizes[idx]; + } + } + return out_strides; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.h b/western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..5600768121e9912d667ec2870796574f975cf7c4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/ExpandUtils.h @@ -0,0 +1,547 @@ +#pragma once + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace at { + +TORCH_API std::vector infer_size(IntArrayRef a, IntArrayRef b); +TORCH_API std::vector infer_size_symint( + SymIntArrayRef a, + SymIntArrayRef b); +TORCH_API DimVector infer_size_dimvector(IntArrayRef a, IntArrayRef b); +TORCH_API SymDimVector +infer_size_symdimvector(SymIntArrayRef a, SymIntArrayRef b); + +// Named type instead of a pair/tuple so that we can be sure to +// construct the vectors in place and get NRVO. +template +struct InferExpandGeometryResult { + Container sizes; + Container strides; + explicit InferExpandGeometryResult(size_t ndim) + : sizes(ndim), strides(ndim) {} + explicit InferExpandGeometryResult(IntArrayRef sizes_, size_t ndim) + : sizes(sizes_.begin(), sizes_.end()), strides(ndim) {} +}; + +TORCH_API std::tuple, std::vector> +inferExpandGeometry( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes); + +TORCH_API InferExpandGeometryResult inferExpandGeometry_dimvector( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides, + IntArrayRef sizes); + +TORCH_API std::vector infer_dense_strides( + IntArrayRef tensor_sizes, + IntArrayRef tensor_strides); + +// True if input shapes are expandable +// NOTE: infer_size did a similar check, please keep them sync if change is +// needed +inline bool are_expandable(IntArrayRef shape1, IntArrayRef shape2) { + size_t ndim1 = shape1.size(); + size_t ndim2 = shape2.size(); + size_t ndim = ndim1 < ndim2 ? ndim1 : ndim2; + + for (int64_t i = static_cast(ndim) - 1; i >= 0; --i) { + if (shape1[--ndim1] == shape2[--ndim2] || shape1[ndim1] == 1 || + shape2[ndim2] == 1) { + continue; + } + return false; + } + return true; +} + +// avoid copy-construction of Tensor by using a reference_wrapper. +inline void check_defined( + std::initializer_list> tensors, + const char* api_name) { + for (auto& t : tensors) { + if (!t.get().defined()) { + TORCH_CHECK(false, api_name, "(...) called with an undefined Tensor"); + } + } +} + +// NOTE [ ExpandUtils Borrowing ] +// +// Functions in ExpandUtils return `c10::MaybeOwned` because +// expansion may not actually be needed, in which case we can improve +// efficiency by returning +// `c10::MaybeOwned::borrowed(to_expand)`. However, this means +// that you need to be careful: the returned `c10::MaybeOwned` +// must not outlive the original `Tensor` object that `to_expand` +// referred to! The deleted rvalue reference overloads of these +// functions help with this by preventing trivial use of a temporary +// resulting from a function call, but it is still possible to make a +// mistake. + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + const Tensor& to_expand) { + auto t_sizes = tensor.sym_sizes(); + auto e_sizes = to_expand.sym_sizes(); + bool same = t_sizes.size() == e_sizes.size(); + if (same) { + for (size_t i = 0; i < t_sizes.size(); ++i) { + if (!TORCH_GUARD_OR_FALSE(sym_eq(t_sizes[i], e_sizes[i]))) { + same = false; + break; + } + } + } + if (same) { + return c10::MaybeOwned::borrowed(to_expand); + } + return c10::MaybeOwned::owned( + to_expand.expand_symint(tensor.sym_sizes())); +} + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + Tensor&& to_expand) = delete; + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + const Tensor& to_expand, + const char* api_name) { + check_defined({tensor, to_expand}, api_name); + return expand_inplace(tensor, to_expand); +} + +inline c10::MaybeOwned expand_inplace( + const Tensor& tensor, + Tensor&& to_expand, + const char* api_name) = delete; + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + const Tensor& to_expand2) { + if (tensor.sizes().equals(to_expand1.sizes()) && + tensor.sizes().equals((to_expand2.sizes()))) { + return std::make_tuple( + c10::MaybeOwned::borrowed(to_expand1), + c10::MaybeOwned::borrowed(to_expand2)); + } + + return std::make_tuple( + c10::MaybeOwned::owned(to_expand1.expand(tensor.sizes())), + c10::MaybeOwned::owned(to_expand2.expand(tensor.sizes()))); +} + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + Tensor&& to_expand1, + const Tensor& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + Tensor&& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace(const Tensor& tensor, Tensor&& to_expand1, Tensor&& to_expand2) = + delete; + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + const Tensor& to_expand2, + const char* api_name) { + check_defined({tensor, to_expand1, to_expand2}, api_name); + return expand_inplace(tensor, to_expand1, to_expand2); +} + +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + Tensor&& to_expand1, + const Tensor& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + const Tensor& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_inplace( + const Tensor& tensor, + Tensor&& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; + +// See NOTE [ ExpandUtils Borrowing ] above for `MaybeOwned` explanation. +inline std::tuple, c10::MaybeOwned> +expand_outplace(const Tensor& to_expand1, const Tensor& to_expand2) { + auto s1 = to_expand1.sym_sizes(); + auto s2 = to_expand2.sym_sizes(); + if (s1.equals(s2)) { + return std::make_tuple( + c10::MaybeOwned::borrowed(to_expand1), + c10::MaybeOwned::borrowed(to_expand2)); + } + + auto expanded_size = infer_size_symdimvector(s1, s2); + return std::make_tuple( + c10::MaybeOwned::owned(to_expand1.expand_symint(expanded_size)), + c10::MaybeOwned::owned(to_expand2.expand_symint(expanded_size))); +} + +inline std::tuple, c10::MaybeOwned> +expand_outplace(Tensor&& to_expand1, const Tensor& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace(const Tensor& to_expand1, Tensor&& to_expand2) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace(Tensor&& to_expand1, Tensor&& to_expand2) = delete; + +inline std::tuple, c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + const char* api_name) { + check_defined({to_expand1, to_expand2}, api_name); + return expand_outplace(to_expand1, to_expand2); +} + +inline std::tuple, c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; +inline std::tuple, c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + const char* api_name) = delete; + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3) { + if (to_expand1.sizes().equals(to_expand2.sizes()) && + to_expand1.sizes().equals(to_expand3.sizes())) { + return std::make_tuple( + c10::MaybeOwned::borrowed(to_expand1), + c10::MaybeOwned::borrowed(to_expand2), + c10::MaybeOwned::borrowed(to_expand3)); + } + + auto expanded_size12 = + infer_size_dimvector(to_expand1.sizes(), to_expand2.sizes()); + auto expanded_size = + infer_size_dimvector(expanded_size12, to_expand3.sizes()); + return std::make_tuple( + c10::MaybeOwned::owned(to_expand1.expand(expanded_size)), + c10::MaybeOwned::owned(to_expand2.expand(expanded_size)), + c10::MaybeOwned::owned(to_expand3.expand(expanded_size))); +} + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + Tensor&& to_expand3) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace(Tensor&& to_expand1, Tensor&& to_expand2, Tensor&& to_expand3) = + delete; + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3, + const char* api_name) { + check_defined({to_expand1, to_expand2, to_expand3}, api_name); + return expand_outplace(to_expand1, to_expand2, to_expand3); +} + +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + const Tensor& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + const Tensor& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + const Tensor& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + const Tensor& to_expand1, + Tensor&& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; +inline std::tuple< + c10::MaybeOwned, + c10::MaybeOwned, + c10::MaybeOwned> +expand_outplace( + Tensor&& to_expand1, + Tensor&& to_expand2, + Tensor&& to_expand3, + const char* api_name) = delete; + +inline c10::MaybeOwned expand_size( + const Tensor& to_expand, + IntArrayRef sizes) { + if (to_expand.sizes().equals(sizes)) { + return c10::MaybeOwned::borrowed(to_expand); + } + + return c10::MaybeOwned::owned(to_expand.expand(sizes)); +} + +inline c10::MaybeOwned expand_size( + Tensor&& to_expand, + IntArrayRef sizes) = delete; + +inline c10::MaybeOwned expand_size( + const Tensor& to_expand, + IntArrayRef sizes, + const char* api_name) { + check_defined({to_expand}, api_name); + return expand_size(to_expand, sizes); +} + +inline c10::MaybeOwned expand_size( + Tensor&& to_expand, + IntArrayRef sizes, + const char* api_name) = delete; + +inline std::vector expand_outplace(TensorList to_expand) { + // expands a list of Tensors; ignores undefined (null) tensors + bool first = true; + SymDimVector sizes; + for (const auto i : c10::irange(to_expand.size())) { + if (!to_expand[i].defined()) { + continue; + } else if (first) { + sizes = to_expand[i].sym_sizes(); + first = false; + } else { + sizes = infer_size_symdimvector(sizes, to_expand[i].sym_sizes()); + } + } + + std::vector result(to_expand.size()); + for (const auto i : c10::irange(to_expand.size())) { + if (!to_expand[i].defined()) { + continue; + } else if (to_expand[i].sym_sizes().equals(sizes)) { + result[i] = to_expand[i]; + } else { + result[i] = to_expand[i].expand_symint(sizes); + } + } + return result; +} + +template +inline Tensor _sum_to( + Tensor tensor, + const c10::ArrayRef shape, + bool always_return_non_view = false) { + if (shape.size() == 0) { + return tensor.sum(); + } + + auto sizes = at::symint::sizes(tensor); + c10::SmallVector reduce_dims; + const int64_t leading_dims = sizes.size() - shape.size(); + for (const auto i : c10::irange(leading_dims)) { + reduce_dims.push_back(i); + } + for (int64_t i = leading_dims; i < static_cast(sizes.size()); ++i) { + if (TORCH_GUARD_OR_FALSE(sym_eq(shape[i - leading_dims], 1)) && + TORCH_GUARD_OR_TRUE(sym_ne(sizes[i], 1))) { + reduce_dims.push_back(i); + } else { + // if we assume no reduction due to unbacked we ensure that at runtime. + TORCH_MAYBE_SYM_CHECK( + sym_eq(shape[i - leading_dims], sizes[i]), + "non-reduction path was assumed due to unbacked symbols expected those two sizes to be the same:", + shape[i - leading_dims], + ", ", + sizes[i]) + } + } + + if (!reduce_dims.empty()) { + tensor = tensor.sum(reduce_dims, /*keepdim=*/true); + } + + if (always_return_non_view) { + // This is only actually used by the functionalization pass. + // We want to be able to guarantee that this function doesn't return a view + // of the input. + return leading_dims > 0 ? at::symint::view_copy(tensor, shape) + : tensor.clone(); + } else { + return leading_dims > 0 ? at::symint::view(tensor, shape) : tensor; + } +} + +inline Tensor sum_to( + Tensor tensor, + const c10::SymIntArrayRef shape, + bool always_return_non_view = false) { + return _sum_to(std::move(tensor), shape, always_return_non_view); +} + +// Sums `tensor` repeatedly to produce a tensor of shape `shape`. +// Precondition: is_expandable_to(shape, tensor.sizes()) must be true +inline Tensor sum_to( + Tensor tensor, + const IntArrayRef shape, + bool always_return_non_view = false) { + return _sum_to(std::move(tensor), shape, always_return_non_view); +} + +inline bool is_expandable_to( + SymIntArrayRef shape, + c10::SymIntArrayRef desired) { + size_t ndim = shape.size(); + size_t target_dim = desired.size(); + if (ndim > target_dim) { + return false; + } + for (const auto i : c10::irange(ndim)) { + const auto& size = shape[ndim - i - 1]; + const auto& target = desired[target_dim - i - 1]; + if (size != target && size != 1) { + return false; + } + } + return true; +} + +inline bool is_expandable_to(IntArrayRef shape, IntArrayRef desired) { + auto sym_shape = c10::SymIntArrayRef( + reinterpret_cast(shape.data()), shape.size()); + auto sym_desired = c10::SymIntArrayRef( + reinterpret_cast(desired.data()), desired.size()); + return is_expandable_to(sym_shape, sym_desired); +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/Formatting.h b/western_ai/usa/pytorch/aten/src/ATen/Formatting.h new file mode 100644 index 0000000000000000000000000000000000000000..e23b27ffd373180a1857a5491694eff11705f9a1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Formatting.h @@ -0,0 +1 @@ +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.cpp b/western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.cpp new file mode 100644 index 0000000000000000000000000000000000000000..348f4876f761ad960e9751299140b761f9e7556f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.cpp @@ -0,0 +1,31 @@ +#include + +namespace at::functorch { + +namespace { + +thread_local std::unique_ptr kFuncTorchTLS = nullptr; + +} + +std::unique_ptr getCopyOfFuncTorchTLS() { + if (kFuncTorchTLS == nullptr) { + return nullptr; + } + return kFuncTorchTLS->deepcopy(); +} + +void setFuncTorchTLS(const std::shared_ptr& state) { + if (state == nullptr) { + kFuncTorchTLS = nullptr; + return; + } + kFuncTorchTLS = state->deepcopy(); +} + +std::unique_ptr& functorchTLSAccessor() { + return kFuncTorchTLS; +} + + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.h b/western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.h new file mode 100644 index 0000000000000000000000000000000000000000..6430caadfa947f57f76f1d7e218b4b4d60140f8b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FuncTorchTLS.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +namespace at::functorch { + +// NOTE [functorch TLS in pytorch/pytorch] +// +// functorch lives out-of-tree. However, it has some TLS that needs to be +// propagated. The solution for that is we store a pointer to the TLS +// inside pytorch/pytorch and extend FuncTorchTLSBase inside functorch to +// include whatever functorch needs. +// +// We need to store a pointer due to the indirection: +// inside functorch, we will create a subclass of FunctorchTLSBase called +// FuncTorchTLSImpl that actually contains metadata, like the DynamicLayerStack. +// FuncTorchTLSBase doesn't have any metadata because it hasn't been defined +// yet. +// +// Here in pytorch/pytorch, we will pass around FuncTorchTLSBase*, but inside +// functorch, we will assign a FuncTorchTLSImpl* to the FunctorchTLSBase*. +// We can't directly pass around FunctorchTLSBase (without a pointer) because +// FuncTorchTLSImpl does not fit inside a FuncTorchTLSBase by virtue of having +// more elements. +struct TORCH_API FuncTorchTLSBase { + virtual ~FuncTorchTLSBase() = default; + virtual std::unique_ptr deepcopy() const = 0; + + virtual int64_t checkSupportsSingleLevelAutogradFunction() const = 0; + virtual void checkSupportsCppAutogradFunction() const = 0; + virtual void checkSupportsInplaceRequiresGrad() const = 0; + virtual void checkSupportsRetainGrad() const = 0; +}; + +// returns deepcopy of the functorch tls +TORCH_API std::unique_ptr getCopyOfFuncTorchTLS(); + +// sets the functorch tls. always does a deep copy. +TORCH_API void setFuncTorchTLS( + const std::shared_ptr& state); + +// get a mutable reference to the functorch tls +TORCH_API std::unique_ptr& functorchTLSAccessor(); + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalInverses.cpp b/western_ai/usa/pytorch/aten/src/ATen/FunctionalInverses.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e73b1af0d4d180b10e10eb8d4dd41f845db7fc48 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalInverses.cpp @@ -0,0 +1,467 @@ + +#include + +#include +#include +#include + +#include +namespace at::functionalization { + +// This logic is similar to autograd code for view backwards calls. +// We can't easily share it though, because (eventually) these functions +// will all call `permute/unsqueeze_copy()` instead of `permute/unsqueeze`. + +static Tensor permute_inverse(const Tensor& self, IntArrayRef dims, InverseReturnMode inverse_return_mode) { + // invert the permutation + auto ndims = static_cast(dims.size()); + std::vector dims_(ndims); + for(const auto i : c10::irange(ndims)) { + dims_[at::maybe_wrap_dim(dims[i], ndims)] = i; + } + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::permute(self, dims_); + } else { + return at::permute_copy(self, dims_); + } +} + +static Tensor unsqueeze_copy_to(const Tensor & self, c10::SymIntArrayRef sizes, InverseReturnMode inverse_return_mode) { + auto result = self; + bool need_alias = (inverse_return_mode == InverseReturnMode::AlwaysView); + int64_t nDims = static_cast(sizes.size()); + for(const auto dim : c10::irange(nDims)) { + if (sizes[dim] == 1) { + need_alias = false; + if (inverse_return_mode != InverseReturnMode::NeverView) { + result = at::unsqueeze(result, dim); + } else { + result = at::unsqueeze_copy(result, dim); + } + } + } + + // return an alias to ensure the output is a view when necessary + return need_alias ? at::alias(result) : result; +} + +static Tensor unsqueeze_copy_to(const Tensor & self, IntArrayRef dim, c10::SymIntArrayRef sizes, InverseReturnMode inverse_return_mode) { + const auto ndim = static_cast(sizes.size()); + const auto mask = at::dim_list_to_bitset(dim, ndim); + Tensor result = self; + bool need_alias = (inverse_return_mode == InverseReturnMode::AlwaysView); + // in NumPy it's not an error to unsqueeze a scalar, but we still need to avoided + // unsqueezing in the backward. + if (ndim == 0) { + // return an alias to ensure the output is a view when necessary + return need_alias ? at::alias(result) : result; + } + + for (const auto d : c10::irange(ndim)) { + if (mask.test(d) && sizes[d] == 1) { + need_alias = false; + if (inverse_return_mode != InverseReturnMode::NeverView) { + result = at::unsqueeze(result, d); + } else { + result = at::unsqueeze_copy(result, d); + } + } + } + + // return an alias to ensure the output is a view when necessary + return need_alias ? at::alias(result) : result; +} + +// Note [Functionalization Pass: View Inverses]. +// This file contains the implementation of each "view inverse". +// These aren't really true inverses in the mathematically sense: each view inverse describes how to undo +// the original view (although it takes in different arguments). +// +// E.g. Below is an example of a program that has alias operations removed, and the role that view inverses play: +// +// normal program with views and mutations: +// view1 = input1.view_op(args...) +// view1.add_(1) (perform a mutation on the view, which should also modify input) + +// version of the program with no aliasing, that instead uses view_inverse functions: +// view_copy1 = input1.view_copy_op(args...) +// view_copy1.add_(1) (perform a mutation on view_copy1. At this point, input1 is NOT modified) +// x = view_op_inverse(input1, view_copy1, args...) +// +// at this point, input1 and x should be equal +// +// Note that input1 is also passed as an argument to view_op_inverse in the above example. +// This isn't actually required for most view operators: it's only required for view ops +// where you can't figure out what the size of the base tensor is given just the view tensor and arguments. +// Examples are slice/select/scatter/squeeze/as_strided. +// We happen to be passing in the base tensor in all cases, mostly to make the codegen simpler. +// But you'll see below that the "base" argument is ignored by most view_inverse implementations. + +// ---------------------------------------------------------- +// Implementations of each view_inverse() function are below. +// One of these needs to be implemented for every existing non-composite view operator. +// The codegen automatically generates the corresponding function declaration. +// ---------------------------------------------------------- + +Tensor FunctionalInverses::_fw_primal_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t level) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call _fw_primal() during the functionalization pass. For now, this is not supported."); +} + +Tensor FunctionalInverses::_make_dual_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode, const at::Tensor& tangent, int64_t level) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call _make_dual() during the functionalization pass. For now, this is not supported."); +} + +Tensor FunctionalInverses::view_as_real_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::view_as_complex(mutated_view); + } else { + return at::view_as_complex_copy(mutated_view); + } +} + +Tensor FunctionalInverses::view_as_complex_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::view_as_real(mutated_view.resolve_conj()); + } else { + return at::view_as_real_copy(mutated_view.resolve_conj()); + } +} + +Tensor FunctionalInverses::_conj_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::_conj(mutated_view); + } else { + return at::_conj_copy(mutated_view); + } +} + +Tensor FunctionalInverses::_neg_view_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::_neg_view(mutated_view); + } else { + return at::_neg_view_copy(mutated_view); + } +} + +Tensor FunctionalInverses::as_strided_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size, at::SymIntArrayRef stride, std::optional storage_offset) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.as_strided_symint( + base.sym_sizes(), base.sym_strides(), base.sym_storage_offset()); + } else { + return base.as_strided_scatter_symint(mutated_view, size, stride, std::move(storage_offset)); + } +} + +Tensor FunctionalInverses::diagonal_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t offset, int64_t dim1, int64_t dim2) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.as_strided_symint( + base.sym_sizes(), base.sym_strides(), base.sym_storage_offset()); + } else { + return base.diagonal_scatter(mutated_view, offset, dim1, dim2); + } +} + +Tensor FunctionalInverses::expand_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size, bool implicit) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is an expanded view of base. + // We should NOT do this for functionalization + return mutated_view.as_strided_symint( + base.sym_sizes(), base.sym_strides(), base.sym_storage_offset()); + } else { + return base + at::sum_to( + mutated_view - base, + base.sym_sizes(), + /*always_return_non_view=*/inverse_return_mode == InverseReturnMode::NeverView + ); + } +} + +Tensor FunctionalInverses::permute_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::IntArrayRef dims) { + return at::functionalization::permute_inverse(mutated_view, dims, inverse_return_mode); +} + +Tensor FunctionalInverses::_reshape_alias_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size, at::SymIntArrayRef stride) { + // Note that I'm directly calling reshape(), and ignoring the strides. + // _reshape_alias() isn't available from user code, and is an implementation detail of reshape(). + // Specifically, passing in the strides directly can get us into trouble in cases like: + // b = a[0]; c = b.reshape(...); c.add_(1); print(a) + // When we eventually run the _reshape_alias_inverse() call here, if we were to pass in both sizes and strides, + // The call would fail because `mutated_view` doesn't have enough bytes of storage. + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::_reshape_alias_symint(mutated_view, base.sym_sizes(), base.sym_strides()); + } else { + return at::_reshape_alias_copy_symint(mutated_view, base.sym_sizes(), base.sym_strides()); + } +} + +Tensor FunctionalInverses::select_int_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim, c10::SymInt index) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.as_strided_symint( + base.sym_sizes(), base.sym_strides(), base.sym_storage_offset()); + } else { + return base.select_scatter_symint(mutated_view, dim, std::move(index)); + } +} + +Tensor FunctionalInverses::detach_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + // the functionalization pass doesn't care about autograd metadata - as a view, I think detach() is just an identity function + return mutated_view; +} + +Tensor FunctionalInverses::lift_fresh_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + return mutated_view; +} + +Tensor FunctionalInverses::slice_Tensor_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim, std::optional start, std::optional end, c10::SymInt step) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.slice_inverse_symint( + base, dim, std::move(start), std::move(end), std::move(step)); + } else { + return base.slice_scatter_symint(mutated_view, dim, std::move(start), std::move(end), std::move(step)); + } +} + +// NOLINTNEXTLINE(performance-unnecessary-value-param) +Tensor FunctionalInverses::split_Tensor_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, c10::SymInt split_size, int64_t dim) { + // It would be nice if this logic could be reused from autograd's split_backward(), but I don't think it can. + // For functionalization, we have only have one of the tensors from the TensorList outputted by split(), and we want to layer i + // on top of the base tensor. + // For autograd, we have all of the tensors outputted by split() and we just want to stack them. + dim = at::maybe_wrap_dim(dim, base.dim()); + auto dim_size = base.sym_size(dim); + auto start = split_size * mutated_view_idx; + auto end = split_size + start; + if (end > dim_size) end = dim_size; + + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.slice_inverse_symint(base, dim, start, end, 1); + } else { + return base.slice_scatter_symint(mutated_view, dim, start, end, 1); + } +} + +Tensor FunctionalInverses::split_with_sizes_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, c10::SymIntArrayRef split_sizes, int64_t dim) { + dim = at::maybe_wrap_dim(dim, base.dim()); + auto dim_size = base.sym_size(dim); + c10::SymInt start = 0; + for (int64_t i = 0; i < mutated_view_idx; ++i) { + start += split_sizes[i]; + } + auto end = start + split_sizes[mutated_view_idx]; + if (end > dim_size) end = dim_size; + + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.slice_inverse_symint(base, dim, start, end, 1); + } else { + return base.slice_scatter_symint(mutated_view, dim, start, end, 1); + } +} + +Tensor FunctionalInverses::squeeze_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + return unsqueeze_copy_to(mutated_view, base.sym_sizes(), inverse_return_mode); +} + +Tensor FunctionalInverses::squeeze_dim_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim) { + return unsqueeze_copy_to(mutated_view, dim, base.sym_sizes(), inverse_return_mode); +} + +Tensor FunctionalInverses::squeeze_dims_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, IntArrayRef dim) { + return unsqueeze_copy_to(mutated_view, dim, base.sym_sizes(), inverse_return_mode); +} + +Tensor FunctionalInverses::t_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::t(mutated_view); + } else { + return at::t_copy(mutated_view); + } +} + +Tensor FunctionalInverses::transpose_int_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim0, int64_t dim1) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return transpose(mutated_view, dim0, dim1); + } else { + return transpose_copy(mutated_view, dim0, dim1); + } +} + +Tensor FunctionalInverses::_nested_view_from_buffer_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, const Tensor& nested_sizes, const Tensor& nested_strides, const Tensor& storage_offsets) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call _nested_view_from_buffer() during the functionalization pass. For now, nested tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::_nested_view_from_jagged_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, const Tensor& offsets, const Tensor& dummy, const std::optional& lengths, int64_t ragged_idx, const std::optional& min_seqlen, const std::optional& max_seqlen) { + auto values = at::_nested_get_values(mutated_view); + if (inverse_return_mode != InverseReturnMode::NeverView) { + return values; + } else { + return values.clone(/*memory_format=*/at::MemoryFormat::Contiguous); + } +} + +Tensor FunctionalInverses::_nested_get_values_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + auto offsets = at::_nested_get_offsets(base); + auto lengths = at::_nested_get_lengths(base); + auto ragged_idx = at::_nested_get_ragged_idx(base); + auto dummy = at::_nested_get_jagged_dummy(base); + auto min_seqlen = at::_nested_get_min_seqlen(base); + auto max_seqlen = at::_nested_get_max_seqlen(base); + auto nt = at::_nested_view_from_jagged( + mutated_view, offsets, dummy, lengths, ragged_idx, + (min_seqlen.defined() ? std::optional(min_seqlen) : std::nullopt), + (max_seqlen.defined() ? std::optional(max_seqlen) : std::nullopt)); + + if (inverse_return_mode != InverseReturnMode::NeverView) { + return nt; + } else { + return nt.clone(/*memory_format=*/at::MemoryFormat::Contiguous); + } +} + +Tensor FunctionalInverses::unsqueeze_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dim) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::squeeze(mutated_view, dim); + } else { + return at::squeeze_copy(mutated_view, dim); + } +} + +Tensor FunctionalInverses::_indices_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call _indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::_values_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call _values() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::indices_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::values_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call values() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::_sparse_broadcast_to_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::IntArrayRef size) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call _sparse_broadcast_to() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::crow_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call crow_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::col_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call col_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::ccol_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call ccol_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::row_indices_inverse(const at::Tensor& base, const at::Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + TORCH_INTERNAL_ASSERT(false, "Attempted to call row_indices() during the functionalization pass. For now, sparse tensors aren't supported during functionalization"); +} + +Tensor FunctionalInverses::unbind_int_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int64_t dim) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.as_strided_symint( + base.sym_sizes(), base.sym_strides(), base.sym_storage_offset()); + } else { + dim = at::maybe_wrap_dim(dim, static_cast(base.sizes().size())); + return base.select_scatter(mutated_view, dim, mutated_view_idx); + } +} + +Tensor FunctionalInverses::view_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::SymIntArrayRef size) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return mutated_view.view_symint(base.sym_sizes()); + } else { + return at::view_copy_symint(mutated_view, base.sym_sizes()); + } +} + + +Tensor FunctionalInverses::view_dtype_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, at::ScalarType dtype) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return mutated_view.view(base.scalar_type()); + } else { + return at::view_copy(mutated_view, base.scalar_type()); + } +} + +Tensor FunctionalInverses::unfold_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode, int64_t dimension, int64_t size, int64_t step) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.as_strided_symint( + base.sym_sizes(), base.sym_strides(), base.sym_storage_offset()); + } else { + // I think autograd and the functionalization pass want the exact same thing here, but need to test to confirm. + // unfold_backward() is safe to use here because it is NOT a view op. + // (note: technically, we'll have an extra memory copy. + // We'd need to add an aliasing version of unfold_backward to fix that though). + TORCH_CHECK( + !(inverse_return_mode == InverseReturnMode::ViewOrScatterInverse && size > step), + "While executing unfold, functionalization encountered a tensor being mutated that has internal overlap. \ +When using torch.compile (or running functionalization directly), this is banned \ +as the behavior is not well defined. Consider cloning the tensor before mutating it, \ +or removing the mutation from your model." + ); + return unfold_backward(mutated_view, base.sizes(), dimension, size, step); + } +} + +Tensor FunctionalInverses::alias_inverse(const Tensor& base, const Tensor& mutated_view, InverseReturnMode inverse_return_mode) { + if (inverse_return_mode != InverseReturnMode::NeverView) { + return at::alias(mutated_view); + } else { + return at::alias_copy(mutated_view); + } +} + +Tensor FunctionalInverses::chunk_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int64_t mutated_view_idx, int chunks, int dim) { + // TODO: Can the logic from TensorShape.cpp be reused here somehow? + const auto dim_size = base.sym_size(dim); + auto split_size = (dim_size + chunks - 1) / chunks; + std::vector split_sizes(chunks, split_size); + split_sizes[chunks - 1] = split_size - (split_size * chunks - dim_size); + return split_with_sizes_inverse(base, mutated_view, inverse_return_mode, mutated_view_idx, split_sizes, dim); +} + +// NOLINTNEXTLINE(performance-unnecessary-value-param) +Tensor FunctionalInverses::narrow_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, int dim, c10::SymInt start, c10::SymInt length) { + if (inverse_return_mode == InverseReturnMode::AlwaysView) { + // NB: assumes mutated_view is a narrowed view of base. + // We should NOT do this for functionalization + return mutated_view.slice_inverse_symint(base, dim, start, start + length, 1); + } else { + return base.slice_scatter_symint( + mutated_view, dim, start, start + length, 1); + } +} + +Tensor FunctionalInverses::slice_inverse_inverse(const at::Tensor & base, const at::Tensor & mutated_view, InverseReturnMode inverse_return_mode, const at::Tensor & src, int64_t dim, std::optional start, std::optional end, c10::SymInt step) { + // slice_inverse() inverse is just slice() + if (inverse_return_mode == InverseReturnMode::NeverView) { + return at::slice_copy_symint( + mutated_view, dim, std::move(start), std::move(end), std::move(step)); + } else { + return mutated_view.slice_symint( + dim, std::move(start), std::move(end), std::move(step)); + } +} + +} // namespace at::functionalization diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e581d56248c4064551a895abf19aa3f9585189f8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.cpp @@ -0,0 +1,140 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace at::functionalization { + +// Note [Functionalization: Alias Removal Part 2] +// See Note [Functionalization: Alias Removal] for more details. +// This function applies a single update from one of the views to the StorageImpl. +// We start out with and , and our goal is to end up with . +// Consider this program: +// +// base = ... +// a = base.view1() +// b = a.view2() +// c = b.view3() +// c.add_(3) +// +// Then the functionalization pass will queue an update as follows: +// +// update.new_val = c # the updated value of c +// update.view_metas = [view1_meta, view2_meta, view3_meta] +// +// Syncing any of a, b or c will eventually call apply_update() on the storage, and the following will run: +// +// tmp_values = [base, a, b] # NB: c is not necessary +// t = update.new_val +// t = view3_inverse(b, t, 0) # 0 is output index, these are all single output views so it's 0 +// t = view2_inverse(a, t, 0) +// t = view1_inverse(base, t, 0) # t now represents the updated storage. +// storage.base_ = t +static const Tensor apply_update(const FunctionalStorageImpl::Update& update, const Tensor& base) { + at::Tensor t = update.new_val; + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t)); + if (update.view_metas.empty()) { return t; } + + std::vector tmp_values({base}); + tmp_values.reserve(update.view_metas.size()); + for (size_t i = 0; i < update.view_metas.size() - 1; ++i) { + at::Tensor next_view = update.view_metas[i]->forward(tmp_values.back()); + // NB: We only actually need tmp_values for ops like select/slice/diagonal/squeeze/as_strided + // All of these ops require additional information to recover the sizes of the original tensor. + // If need to, we could probably apply this optimization and only bother computing tmp_values + // for those necessary view ops. + tmp_values.push_back(std::move(next_view)); + } + for(int64_t i = static_cast(update.view_metas.size()) - 1; i >= 0; --i) { + // Each view inverse is implemented in ViewInverses.cpp. + t = update.view_metas[i]->reverse(tmp_values[i], t); + } + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t)); + return t; +} + + +static c10::SymInt get_nbytes(const Tensor& value) { + // The functionalization story when wrapping tensors that don't have storage + // is a bit wonky, but fortunately for some models (e.g., dlrm) we never + // actually perform mutations on these tensors, so you never really get + // called out on it. For now, functionalization still creates "storages" + // for these tensors (which is wrong), but we don't give them any space. + // A more proper fix would be to have a SparseFunctionalTensorWrapper that + // models sparse correctly. + if (value.is_sparse() || at::sparse_csr::is_sparse_compressed(value)) { + return 0; + } + if (value.unsafeGetTensorImpl()->has_symbolic_sizes_strides()) { + // Today, the two implementations of SymInt are in Python (proxy tensor), + // and lazy tensor (LTC/XLA). + // LTC hasn't implemented SymInt support yet though + // Once it does, we should remove this check. + if (value.key_set().has(c10::DispatchKey::Python)) { + return value.storage().sym_nbytes(); + } + return at::detail::computeStorageNbytes(value.sym_sizes(), value.sym_strides(),static_cast(value.dtype().itemsize()), value.sym_storage_offset()); + } + // XLA storage objects also do not properly track nbytes. + return static_cast(at::detail::computeStorageNbytes(value.sizes(), value.strides(), value.dtype().itemsize(), value.storage_offset())); +} + +FunctionalStorageImpl::FunctionalStorageImpl(const Tensor& base) + : c10::StorageImpl( + c10::StorageImpl::use_byte_size_t(), + get_nbytes(base), + DataPtr{nullptr, base.device()}, + GetAllocator(kMeta), + /*resizable=*/true + ), + base_(base) +{ + // SparseTensorImpl has no storage, so we cannot query its nbytes. + // (original_storage_size is only used for storage resizing in fsdp anyway, which does not apply to sparse) + // Same for XLA + if (base.unsafeGetTensorImpl()->has_storage() && data_ptr().device().type() != c10::DeviceType::XLA) { + original_storage_size_ = base.unsafeGetTensorImpl()->unsafe_storage().unsafeGetStorageImpl()->sym_nbytes(); + } else { + original_storage_size_ = -1; + } + curr_storage_size_ = original_storage_size_; + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(base_)); +} + +void FunctionalStorageImpl::add_update(const Tensor& updated_val, const std::vector>& metas) { + TORCH_CHECK(!frozen_, "cannot mutate tensors with frozen storage"); + + if (metas.size() > 1) { + for (size_t i = 1; i < metas.size(); ++i) { + // Skipping this check for XLA. Would be good to add it back, but it is failing XLA CI + TORCH_CHECK(updated_val.device().type() == c10::DeviceType::XLA || !metas[i]->is_as_strided, +"During torch.compile, encountered a mutation on a view chain of length ", metas.size(), ", where view ", i, +" was an as_strided() call. as_strided() is non-compositional, and therefore is not possible to functionalize properly today," +"so this behavior is banned in compile. As a workaround, you can either remove the mutation from the model code, or you " +"can insert a graph break right before the mutation with torch._dynamo.graph_break(). If you would like this behavior to " +"work properly, please comment on https://github.com/pytorch/pytorch/issues/104505."); + } + } + updates_.push_back({updated_val, metas}); + generation_++; +} + +bool FunctionalStorageImpl::apply_updates() { + // N.B:none of the tensors used in this function should be FunctionalTensorWrappers at this point. + // The only reason we currently need the TLS exclude guard here is because of functorch's DynamicLayer stack. + // It adds the Functionalize key into TLS before redispatching to the functionalization kernels, + // which means that we need to explicitly exclude it here before doing any other work underneath the pass. + at::AutoDispatchSkipFunctionalize guard; + bool any_updates = !updates_.empty(); + for (auto& update_data: updates_) { + base_ = apply_update(update_data, base_); + } + updates_.clear(); + return any_updates; +} + +} // namespace at::functionalization diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.h b/western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..fd2a1bb8e3818fc4873767444b11b660e36cc814 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalStorageImpl.h @@ -0,0 +1,285 @@ +#pragma once + +#include + +#include +#include +#include + +namespace at::functionalization { + +// See Note [Functionalization Pass In Core] + +enum class InverseReturnMode { + /// Specifies that functional inverses should always return a view. + AlwaysView, + /// Specifies that functional inverses should always return a non-view / copy. + NeverView, + /// Specifies that functional inverses should return a view unless a (copying) + /// scatter + /// inverse exists, in which case that will be used instead. + /// This avoids as_strided() calls that can be difficult for subclasses to + /// handle. + ViewOrScatterInverse, +}; + +#define FUNCTIONALIZATION_VIEWMETA_NAME(TYPE) \ + static const char* name() { \ + return #TYPE; \ + } + +template +struct tuple_elements_are_owning; + +template +struct tuple_elements_are_owning> + : std::bool_constant<(std::is_same_v, Ts> && ...)> {}; + +#define FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(...) \ + using SerializableTuple = std::tuple<__VA_ARGS__>; \ + static_assert( \ + ::at::functionalization::tuple_elements_are_owning< \ + SerializableTuple>::value, \ + "FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE elements must be " \ + "owning value types (no references or cv-qualifiers); a reference " \ + "element would dangle in to_serializable_tuple() and in the data " \ + "member it initializes.") + +// ViewMeta is a class used by the functionalization pass to navigate between +// a base tensor and a view tensor. +// For example, if I call `b = a.view1(...)` +// the functionalization pass will generate and store a ViewMeta specialization +// for `view1` operation on b that looks like: +// +// struct TORCH_API view1_ViewMeta : public ViewMeta { +// FUNCTIONALIZATION_VIEWMETA_NAME(view1_ViewMeta); +// FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE( +// bool /* reapply_views */, +// std::vector); +// +// view1_ViewMeta(const SerializableTuple& tpl) +// : view1_ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {} +// +// view1_ViewMeta(bool reapply_views, const std::vector& size) +// : ViewMeta(/*has_symbolic_inputs=*/false), +// reapply_views(reapply_views), +// size(size) {} +// +// Tensor forward(const Tensor& base) override { +// return base.view1(...); +// } +// +// Tensor reverse(const Tensor& base, const Tensor& mutated_view) override { +// return at::functionalization::impl::view1_inverse(base, mutated_view, +// ...); +// } +// +// SerializableTuple to_serializable_tuple() { +// return std::make_tuple(reapply_views, size); +// } +// +// bool reapply_views; +// std::vector size; +// }; +// +// The forward function describes how to replay view1 on a tensor. +// +// The reverse function describes how, given a tensor that is already a view, +// how to get the corresponding base tensor. See Note [Functionalization Pass: +// View Inverses] for details. +// +// `SerializedTuple` is a typedef that defines an `std::tuple<...>` type +// representing the `ViewMeta` instance state. Methods that take in/return such +// a type are used for supporting pickle serialization. +struct ViewMeta { + ViewMeta( + bool has_symbolic_inputs, + bool is_multi_output = false, + bool is_as_strided = false, + int64_t out_idx = 0) + : out_index(out_idx), + is_multi_output(is_multi_output), + is_as_strided(is_as_strided), + has_symbolic_inputs(has_symbolic_inputs) {} + + virtual ~ViewMeta() = default; + + virtual Tensor forward(const Tensor& base) = 0; + virtual Tensor reverse(const Tensor& base, const Tensor& mutated_view) = 0; + + // See Note [out_idx in ViewMeta] + int64_t out_index; + + // Tells us if this is a multi-output view + bool is_multi_output; + + bool is_as_strided; + + // Tells us if this view operation has any symbolic inputs + bool has_symbolic_inputs; + + // Returns a new ViewMeta with the same forward/reverse + // functions, but a new out index. + // + // This method should be implemented by those `ViewMeta` that have more than + // one output. + virtual std::shared_ptr to_out_index(int64_t out_index) { + TORCH_CHECK_NOT_IMPLEMENTED( + false, + "ViewMeta::to_out_index not implemented. ", + "Likely because there's only one output."); + } +}; + +// FunctionalStorageImpl is a subclass of StorageImpl used by the +// functionalization pass. It has no underlying data (similar to meta storage). +// It also knows how to reflect mutations to tensors in the absence of a valid +// data pointer. +// +// A storage represents the state shared by (potentially multiple) views of the +// same tensor. For example, in the following code: +// +// b = a.view1(...) +// c = b.view2(...) +// b.add_(1) +// --> storage.add_update(b, {view1_meta}) +// +// The call to add_(1) will result in a call to alias.add_update(b, +// {view1_meta}), queueing up the mutation from b onto the alias. Later, suppose +// c is used in an expression (e.g. you try to print c, or pass it to an +// operator). Doing so will involve "syncing" c. First we apply any pending +// updates to the alias, and then we regenerate c by replaying its views off of +// the updated alias. E.g: +// +// print(str(c)) +// --> c.sync_() +// --> alias.apply_updates() // after this, the alias will be updated to +// reflect the mutation to b +struct TORCH_API FunctionalStorageImpl : public c10::StorageImpl { + public: + struct Update { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const at::Tensor new_val; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members) + const std::vector> view_metas; + }; + + explicit FunctionalStorageImpl(const Tensor& value); + + void add_update( + const Tensor& updated_val, + const std::vector>& view_metas); + bool apply_updates(); + const Tensor& base() { + return base_; + } + size_t generation() const { + return generation_; + } + void freeze() { + frozen_ = true; + } + + c10::SymInt get_storage_size(bool before) { + if (before) { + return original_storage_size_; + } else { + return curr_storage_size_; + } + } + + ~FunctionalStorageImpl() override = default; + + uint64_t mutation_counter() { + return mutation_counter_; + } + void mark_mutation() { + mutation_counter_++; + } + void mark_mutation_during_no_grad_or_inference_mode() { + mutation_counter_during_no_grad_or_inference_mode_++; + } + void mark_mutation_hidden_from_autograd() { + mutation_counter_hidden_from_autograd_++; + } + + bool are_all_mutations_under_no_grad_or_inference_mode() const { + auto non_autograd_mutations = + mutation_counter_during_no_grad_or_inference_mode_ + + mutation_counter_hidden_from_autograd_; + // The <= is because both counters will technically be incremented, if we + // perform e.g. a triton kernel mutation under no_grad + return mutation_counter_ <= non_autograd_mutations; + } + + bool are_all_mutations_hidden_from_autograd() const { + // mutations under no_grad / inference_mode are technically not hidden from + // autograd - they change the version counter + return mutation_counter_ <= mutation_counter_hidden_from_autograd_; + } + + void mark_inductor_storage_resize(c10::SymInt new_size) { + inductor_storage_resized_ = true; + curr_storage_size_ = std::move(new_size); + inductor_storage_resized_counter_++; + } + + bool was_inductor_storage_resized() { + return inductor_storage_resized_; + } + + uint64_t inductor_storage_resized_counter() { + return inductor_storage_resized_counter_; + } + + private: + // NB: base_ should always point to a tensor BELOW the current + // functionalization layer. This is mainly to avoid reference cycles. e.g. + // given `b = a.view(...)` Both a.storage_ and b.storage_ are a + // FunctionStorageImpl containing an Walualias, with contains a Tensor + // `base_`. In this case (where a and b are FunctionalTensorWrapper's), base_ + // should point not to a, but to a's unwrapped value, a.value_` See Note + // [Functionalization: Walualias Removal] for a diagram that shows this + // visually. + at::Tensor base_; + std::vector updates_; + // generation_ gets incremented every time a mutation is queued onto the + // alias. It is used to determine if a given tensor is "up to date", or if it + // needs to be regenerated from the alias. + size_t generation_ = 0; + // If frozen, no more mutations are allowed on this storage. Once frozen, a + // storage cannot be unfrozen. + bool frozen_ = false; + + // These mutation counters are bumped on the storage + // whenever a FunctionalTensorWrapper experiences a mutation. + // When the mutation is under no_grad, or comes from a triton kernel, we also + // bump the corresponding during_no_grad or hidden_from_autograd counters. Why + // do we need to detect these two situations separately from "normal" input + // mutations? (1) "normal" input mutations can mutate autograd metadata like + // .grad_fn, + // in which case they need to be replayed outside of the compiled graph + // (2) "no_grad" input mutations are generally safe to keep in the graph (and + // compile), + // but they bump the tensor's VC, so we need to mark_dirty() on the inputs + // in torch.compile + // (3) mutations that are fully hidden from autograd (e.g. from a triton + // kernel) + // do not mutate any autograd state, and be fully kept in the graph + // When we detect that an input was mutated, we need to be able to tell if: + // (1) all of the mutations were from triton kernels + // (2) all of the mutations were under no_grad + uint64_t mutation_counter_during_no_grad_or_inference_mode_ = 0; + uint64_t mutation_counter_ = 0; + uint64_t mutation_counter_hidden_from_autograd_ = 0; + + // Used to tell if: + // (1) There were any storage resizes on a graph input + // (2) The original/curr storage size tell us if these resizes result in a nop + bool inductor_storage_resized_ = false; + uint64_t inductor_storage_resized_counter_ = 0; + c10::SymInt original_storage_size_; + c10::SymInt curr_storage_size_; +}; + +} // namespace at::functionalization diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.cpp b/western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c6df6871f7e61092e96888a8c28747b637695e2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.cpp @@ -0,0 +1,940 @@ + +#include + +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at { + +void FunctionalTensorWrapper::set_constructor_metadata() { + TORCH_INTERNAL_ASSERT(value_.defined()); + // Note: "level" is a concept that we don't know how to compute in core. + // For now I'm retroactively setting this in functorch, + // but once Open Multiple Dispatch lands we should be able to calculate this in core. + level_ = -1; + // mirror all of the generic tensor metadata onto the wrapper + copy_generic_tensor_metadata(value_.getIntrusivePtr().get(), this); + refresh_numel(); + refresh_contiguous(); + storage_access_should_throw_ = false; + // In general, the sizes/stride metadata on a tensor can change as it is mutated, + // and these changes need to be reflected in the metadata of the wrapper. + set_allow_tensor_metadata_change(true); + key_set_ = c10::DispatchKeySet(c10::DispatchKey::Functionalize) | value_.key_set(); + // All of the keys corresponding to functorch transforms should not be copied over. + // Functorch transforms all have their own wrapper tensors (e.g. BatchedTensorImpl) which expect + // to participate in the functorch transforms. + key_set_ = key_set_ - c10::functorch_transforms_ks - c10::python_ks; + // We override a bunch of _custom(), so make sure they get called + // TODO: metadata copying may not actually be necessary then + set_custom_sizes_strides(SizesStridesPolicy::CustomSizes); + set_custom_device(true); + // E.g. when running torch.compile under inference mode, we need to make sure that + // for any inputs that were created outside of inference mode (so they are not inference tensors), + // then the functional wrappers that we wrap them with should also not be inference tensors. + version_counter_ = value_.unsafeGetTensorImpl()->version_counter(); +} + +FunctionalTensorWrapper::FunctionalTensorWrapper(const Tensor& value) + : c10::TensorImpl( + c10::Storage(c10::make_intrusive(value)), + c10::DispatchKeySet(DispatchKey::Functionalize) | value.key_set(), + value.dtype() + ), + value_(value) +{ + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(value_)); + TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize)); + set_constructor_metadata(); +} + +void FunctionalTensorWrapper::freeze_storage() const { + functional_storage_impl()->freeze(); +} + +// Note [Functionalization: Alias Removal] +// When someone calls a view() op during the functionalization pass, e.g. 'b = a.view(...)', +// we link `b` and `a` to a shared Alias object to preserve the aliasing relationship. +// +// How do we do that? +// +// Every FunctionalTensorWrapper contains a dummy FunctionalStorageImpl, which subclasses from c10::StorageImpl. +// It doesn't contain any data (similar to MetaTensor storage), but it contains an Alias object that knows about the base tensor. +// When a tensor is created through a view operation, both the new and old tensor point to the same FunctionalStorageImpl. +// +// As mutations are applied to any of the views, we also queue each mutation up on the Alias object, so we can replay them. +// When the user requests a tensor that's had a view taken, we check if it's up to date. +// If it's not up to date, we first replay all of the queued up mutations onto the alias, and then re-apply the current view +// on top of the newly updated alias. +// +// Why do we queue up and lazily run mutations on the alias, instead of updating the alias eagerly? +// This behavior was taken from pytorch/xla, which the alias-removal logic was inspired from. +// One benefit of the laziness is that we save work in the cases where a user has multiple views and mutates one of them, +// but never uses the other views later in the program (in which case we'll never update the alias). +// It also has downsides though: repeatedly applying mutations to the same view without syncing +// will silently use up more and more memory as more mutations are queued up. +// +// Corresponding diagram: +// +// b = a.view(...) +// +// a b +// | | If the user asks for b and it’s out of date, +// \/ \/ We regenerate b by replaying it’s views from the alias. +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - . +// | FunctionalTensorWrapper | | FunctionalTensorWrapper | +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - . +// | value | storage | | storage | Value | +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - . +// | \ / | +// | \ / | +// | . - - - - - - - - - - - - . | +// | | FunctionalStorageImpl | | +// | . - - - - - - - - - - - - . | +// | | Alias | | +// | . - - - - - - - - - - - - . | +// | / mutations to a or b | +// | / are queued onto Alias | +// | / | +// \/ / \/ +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - . +// | TensorImpl | | TensorImpl | +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - . +// | value | storage | | storage | Value | +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - . +// | | +// | | +// | | +// | In this picture the two tensor views their own storages, | +// | have their own storages, but backends like functorch | +// \/ are allowed to re-alias underneath the pass \/ +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - . +// | underlying_storage | | underlying_storage | +// . - - - - - - - - - - - - - . . - - - - - - - - - - - - - - - . +// +// This constructor is only used by view ops. +// - view_value: The output tensor that we need to wrap. +// - base: The "base" of the view that `view_value` was generated from. +// See Note [Functionalization: Alias Removal Part 2] for more details on the mutation replay logic. +FunctionalTensorWrapper::FunctionalTensorWrapper( + const Tensor& view_value, + const FunctionalTensorWrapper* base, + const std::shared_ptr& meta) + : c10::TensorImpl( + c10::DispatchKeySet(DispatchKey::Functionalize), + view_value.dtype(), + base->storage().data_ptr().device()), + value_(view_value), + is_multi_output_view_( + base->is_multi_output_view_ || meta->is_multi_output), + was_storage_changed_(base->was_storage_changed_), + is_symbolic_(base->is_symbolic_) { + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(value_)); + TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize)); + set_constructor_metadata(); + // Copy the original tensor's ViewMeta vector and push the current one. + if (!base->view_metas_.empty()) { + view_metas_ = base->view_metas_; // copy + } + view_metas_.push_back(meta); + maybe_mark_symbolic(meta.get()); + storage_ = base->storage_; // alias this tensor's storage with the base tensor's +} + +functionalization::FunctionalStorageImpl* FunctionalTensorWrapper::functional_storage_impl() const { + return static_cast(storage_.unsafeGetStorageImpl()); +} + +void FunctionalTensorWrapper::commit_update() { + auto storage_impl = functional_storage_impl(); + storage_impl->add_update(value_, view_metas_); + // As an optimization, we used to mark the tensor here as "up-to-date", + // That way, code like: + // x = torch.ones(1'000'000) + // x[0].add_(1) + // doesn't result in an unnecessary materialization of the base. + // This optimization results in the slice temporarily haven't incorrect + // stride/storage_offset though, and DCE should handle that optimization anyway. + // generation_ = storage_impl->generation(); +} + +bool FunctionalTensorWrapper::is_up_to_date() const { + auto alias_generation = functional_storage_impl()->generation(); + return generation_ == alias_generation; +} + +// See Note [Functionalization Pass - Inplace View Ops] +void FunctionalTensorWrapper::mutate_view_meta(const std::shared_ptr& meta) { + view_metas_.push_back(meta); + // Manually track the fact that this tensor received a metadata mutation! + has_metadata_mutation_ = true; + // Mark this tensor as being symbolic if there are any symbolic inputs used by the view operation. + maybe_mark_symbolic(meta.get()); + // Note [Functionalization Pass - Inplace View Ops] + // So, these ops are special - they're mutation AND view ops. They get special codegen. + // An example is transpose_, e.g. `a.transpose_()` + // Calling transpose_() should ensure that a gets an alias, and append the new ViewMeta to a's current list of ViewMetas. + at::AutoDispatchSkipFunctionalize guard; + value_ = meta->forward(value_); + TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize)); +} + +// Note [Functionalization: Mutation Removal] +// Mutation removal is used to take a program like this: +// +// a.add_(b) +// +// and replace it with a slightly different program that has the same semantics: +// +// tmp = a.add(b) +// a.replace_(tmp) +// +// Where the replace_() call is implemented directly in the functionalization pass, so it is transparent to the backend. +// This is useful for backends that aren't able to handle certain types of mutations, like functorch. +// +// Why do we need to wrap every tensor in a FunctionalTensorWrapper? Consider this program: +// +// Before: +// tensor.add_(batched_tensor) +// +// After: +// tmp = tensor.add(batched_tensor) +// tensor.replace_(tmp) +// +// In the above, tmp is a batched tensor (because adding a normal tensor to a batched tensor does broadcasting and creates a batched tensor). +// But we can't just replace the underlying memory backing `tensor` with `tmp` - a batched tensor takes up more space! +// Instead, every input, intermediate and output of the program is wrapped in a FunctionalTensorImpl, which wraps the underlying tensor. +void FunctionalTensorWrapper::replace_(const Tensor& other, bool from_lazy_regenerate) { + // TODO: going to need to change this if we want nested functionalize() transforms. + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(other)); + value_ = other; + TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize)); + // out= ops are allowed to resize the output tensors, mutating both the data and metadata of the tensor. + // We need to propagate that metadata mutation to the wrapper (new size). + auto sizes_ = value_.sym_sizes(); + auto strides_ = value_.sym_strides(); + auto storage_offset_ = value_.sym_storage_offset(); + set_sizes_and_strides(sizes_, strides_, storage_offset_); + if (dtype() != value_.unsafeGetTensorImpl()->dtype() || layout() != value_.unsafeGetTensorImpl()->layout()) { + // .to() should not re-entrantly go through functionalization. + at::AutoDispatchSkipFunctionalize guard; + // and we want _to_copy() to show up in the graph, not the composite .to() operator + // (this can happen if autograd has already run by the time we enter this code) + value_ = at::_to_copy(value_, c10::TensorOptions().dtype(dtype()).layout(layout())); + TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize)); + } + // might not be until after the no_grad region is exited. + // Therefore, replace_() is not unconditionally safe to check the current no_grad state. + // If this is a lazy regeneration, then it is guaranteed that we have already + // done the mutation for the storage alias (when we originally performed the mutation), + // so no counter update may be needed. + // Example: if a mutation happens to a view under a no_grad, + // we won't call replace_() on the other alias until the alias is later used, which + if (!from_lazy_regenerate) { + mark_mutation(); + if (!at::GradMode::is_enabled() || InferenceMode::is_enabled()) { + // This mutation happened under no_grad or inference_mode + mark_mutation_during_no_grad_or_inference_mode(); + } + } +} + +bool FunctionalTensorWrapper::has_data_mutation() { + // Current tensor's data was mutated if its storage saw any mutations. + return functional_storage_impl()->generation() > 0; +} + +void FunctionalTensorWrapper::set__impl(const FunctionalTensorWrapper* other) { + // self.set_(src) will cause self to have all of the tensor properties of self. + value_ = other->value_; + generation_ = other->generation_; + view_metas_ = other->view_metas_; + is_symbolic_ = other->is_symbolic_; + // FREEZE the old storage, preventing mutations to it. + // this is a huge pain to handle properly in all cases, so we ban it. + functional_storage_impl()->freeze(); + // Unsafely swap out the storage with other's storage, + // disconnecting `self` with its view chain + storage_ = other->storage_; + /// explicitly mark the tensor as having its storage changed from set_() + // Otherwise, we don't actually have a 100% accurate way to check this. + // (We could check if the updated value has a new storage than the original value, + // but this won't also let us uniquely determine if the tensor **also** + // experienced a data mutation). + mark_storage_changed(); + + auto sizes_ = value_.sym_sizes(); + auto strides_ = value_.sym_strides(); + auto storage_offset_ = value_.sym_storage_offset(); + set_sizes_and_strides(sizes_, strides_, storage_offset_); +} + +void FunctionalTensorWrapper::storage_resize_(const c10::SymInt& new_size) { + auto curr_storage_size = value_.unsafeGetTensorImpl()->unsafe_storage().unsafeGetStorageImpl()->sym_nbytes(); + // storage resizing is severely limited: we only support resizing either to zero, or from zero bytes. + TORCH_CHECK(new_size == 0 || curr_storage_size == 0, "new_size: ", new_size, ". curr_storage_size: ", curr_storage_size); + // The "functionalization rule" for storage resizing is a giant no-op, mainly because we don't want + // resize_() calls to actually emit any ops in the functional graph. + // How does it work? + // Resizing up (old size == 0): + // We do nothing in this case. + // The expectation is that for the user code to be valid, the next op that should run against the current tensor "x" + // will be a x.copy_(y) (or similar), that will fully overwrite the data of x. + // If there are any outstanding aliases of x, we expect them not to be used until after the copy_() call + // (otherwise the eager code would be invalid), + // and therefore functionalization will regenerate the aliases off of the result of `x.copy(y)`. + // Resizing down (new size == 0): + // We also do nothing in this case. The assumption is that after resizing a tensor down, + // it is fully unused in the program (unless it is later resized back up first, has data copied in) + // Although it might be saved for backward, which happens in FSDP. + // The expected pattern is that the param will then be resized back up from zero in the backward. + + // Mark the tensor as having its storage resized. + // This is so we can detect it for inputs in AOTAutograd and error / emit + // an input mutation resize_() appropriately + functional_storage_impl()->mark_inductor_storage_resize(new_size); +} + +void FunctionalTensorWrapper::maybe_replace_storage(const Tensor& other) { + // Note [resize_() in functionalization pass] + // resize_() is a special operator in functionalization because it can reallocate its underlying storage. + // This function is only ever called in the case that resize_() needs to reallocate its storage to a larger size. + // + // However, functionalization currently bans the following code: + // a = torch.ones(2) + // b = a.view(2) + // b.resize_(4) # b is a view tensor, that we are trying to increase the storage size of + // + // Why is this code difficult to handle? + // The functionalization pass currently keeps aliases in sync by making the following assumptions: + // - The “base” tensor always refers to “all of the data” + // - Whenever you have b = view_op(a), “b” should always refer to a subset of “a”s memory. + // + // The code above breaks that assumption b.resize_(4) actually needs to update "a" + // to tell it that it is now actually some slice of a pre-existing larger storage. + // We're also no longer re-generate "b" fully from "a" anymore, since "a" refers to a slice of "b"'s data. + // + // This is probably fixable in theory, but: + // - the fix would likely complicated the functionalization logic quite a bit. + // - the primary use case for resize_() today is resizing zero-sized tensors in out= variants of operators + // - resize_() also can give you weird results today if you try to resize_() a weirdly strided tensor. + // + // Given all of the above, for now we're just banning the above usage. + TORCH_CHECK(storage().use_count() == 1, "Attempted to resize a view tensor to a larger size. This is not allowed in the functionalization pass"); + TORCH_CHECK(view_metas_.empty(), "Attempted to resize a view tensor to a larger size. This is not allowed in the functionalization pass"); + // If this tensor is not a view (and has no outstanding views taken out on it), + // Then it's safe to throw out the old storage and replace it with the new, larger one. + storage_ = c10::Storage(c10::make_intrusive(other)); + value_ = other; + TORCH_INTERNAL_ASSERT(!value_.key_set().has(c10::DispatchKey::Functionalize)); + generation_ = 0; + // And update the metadata on the wrapper to reflect the new sizes and strides + set_sizes_and_strides(value_.sizes(), value_.strides()); + refresh_numel(); + // (Technically we should be guaranteed that the tensor was already contiguous, + // since it's guaranteed not to have been a view. Doesn't hurt to run though) + refresh_contiguous(); + // Swapping out the storage of a tensor (aka from a resize_() call) will update the sizes and strides of the tensor, + // so we need to record the fact that metadata was mutated. + has_metadata_mutation_ = true; +} + +void FunctionalTensorWrapper::_unsafe_reset_storage() { + // Reset the storage with the current value_ tensor as the base + storage_ = c10::Storage(c10::make_intrusive(value_)); + // Reset the generation so that it matches the new storage + generation_ = 0; + // Clear any pre-existing view metas so that base and value_ are semantically the same + view_metas_.clear(); +} + +void FunctionalTensorWrapper::sync_() { + if (is_up_to_date()) { + return; + } + apply_updates(); + regenerate_from_base(); +} + +const std::vector>& FunctionalTensorWrapper::view_metas() const { + return view_metas_; +} + +void FunctionalTensorWrapper::regenerate_from_base() { + at::AutoDispatchSkipFunctionalize guard; + auto storage_impl = functional_storage_impl(); + auto t = storage_impl->base(); + + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t)); + t = at::functionalization::impl::apply_view_meta_sequence(t, view_metas_); + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t)); + + replace_(t, /*from_lazy_regenerate=*/true); + generation_ = storage_impl->generation(); +} + +bool FunctionalTensorWrapper::apply_updates() { + // Apply all updates on alias_ + auto storage_impl = functional_storage_impl(); + return storage_impl->apply_updates(); +} + +const char* FunctionalTensorWrapper::tensorimpl_type_name() const { + return "FunctionalTensorWrapper"; +} + +void FunctionalTensorWrapper::copy_tensor_metadata( + const FunctionalTensorWrapper* src_impl, + FunctionalTensorWrapper* dest_impl, + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) { + TensorImpl::copy_tensor_metadata( + src_impl, + dest_impl, + version_counter, + allow_tensor_metadata_change); + + // FunctionalTensorWrapper-specific fields. + dest_impl->value_ = src_impl->value_; + dest_impl->level_ = src_impl->level_; + dest_impl->has_metadata_mutation_ = src_impl->has_metadata_mutation_; + dest_impl->is_multi_output_view_ = src_impl->is_multi_output_view_; + dest_impl->was_storage_changed_ = src_impl->was_storage_changed_; + dest_impl->is_symbolic_ = src_impl->is_symbolic_; + dest_impl->generation_ = src_impl->generation_; + dest_impl->view_metas_ = src_impl->view_metas_; +} + + +void FunctionalTensorWrapper::copy_tensor_metadata_and_refresh( + const FunctionalTensorWrapper* src_impl, + FunctionalTensorWrapper* dest_impl, + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const { + copy_tensor_metadata(src_impl, dest_impl, version_counter, allow_tensor_metadata_change); + dest_impl->refresh_numel(); + dest_impl->refresh_contiguous(); +} + +template +c10::intrusive_ptr FunctionalTensorWrapper::shallow_copy_and_detach_core( + VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const { + if (key_set_.has(DispatchKey::Python) && + !c10::impl::tls_is_dispatch_key_excluded(DispatchKey::Python)) { + auto r = (*c10::impl::getGlobalPyInterpreter())->detach(this); + if (r) { + r->set_version_counter(std::forward(version_counter)); + r->set_allow_tensor_metadata_change(allow_tensor_metadata_change); + return r; + } + } + + auto impl = c10::make_intrusive(value_); + copy_tensor_metadata_and_refresh( + /*src_impl=*/this, + /*dest_impl=*/impl.get(), + /*version_counter=*/std::forward(version_counter), + /*allow_tensor_metadata_change=*/allow_tensor_metadata_change); + return impl; +} + +c10::intrusive_ptr FunctionalTensorWrapper::shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const { + return shallow_copy_and_detach_core( + version_counter, allow_tensor_metadata_change); +} + +c10::intrusive_ptr FunctionalTensorWrapper::shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const { + return shallow_copy_and_detach_core( + std::move(version_counter), allow_tensor_metadata_change); +} + +void FunctionalTensorWrapper::shallow_copy_from(const c10::intrusive_ptr& impl) { + AT_ASSERT(has_compatible_shallow_copy_type(impl->key_set())); + auto functional_impl = + static_cast(impl.get()); + copy_tensor_metadata_and_refresh( + /*src_impl=*/functional_impl, + /*dest_impl=*/this, + /*version_counter=*/version_counter(), + /*allow_tensor_metadata_change=*/allow_tensor_metadata_change()); +} + + +c10::Device FunctionalTensorWrapper::device_custom() const { + // The storage pointer already uses the underlying tensor custom device (if + // applicable) to extract the device. So, we dont have to recurse again by + // doing value_.unsafeGetTensorImpl()->device(). + return storage().data_ptr().device(); +} +at::IntArrayRef FunctionalTensorWrapper::sizes_custom() const { + return value_.unsafeGetTensorImpl()->sizes(); +} +at::IntArrayRef FunctionalTensorWrapper::strides_custom() const { + return value_.unsafeGetTensorImpl()->strides(); +} +int64_t FunctionalTensorWrapper::dim_custom() const { + return value_.unsafeGetTensorImpl()->dim(); +} +int64_t FunctionalTensorWrapper::numel_custom() const { + return value_.unsafeGetTensorImpl()->numel(); +} +c10::SymBool FunctionalTensorWrapper::sym_is_contiguous_custom(at::MemoryFormat memory_format) const { + return value_.unsafeGetTensorImpl()->sym_is_contiguous(memory_format); +} +c10::SymIntArrayRef FunctionalTensorWrapper::sym_sizes_custom() const { + return value_.unsafeGetTensorImpl()->sym_sizes(); +} +c10::SymIntArrayRef FunctionalTensorWrapper::sym_strides_custom() const { + return value_.unsafeGetTensorImpl()->sym_strides(); +} +c10::SymInt FunctionalTensorWrapper::sym_size_custom(int64_t d) const { + return value_.unsafeGetTensorImpl()->sym_size(d); +} +c10::SymInt FunctionalTensorWrapper::sym_storage_offset_custom() const { + return value_.unsafeGetTensorImpl()->sym_storage_offset(); +} +c10::Layout FunctionalTensorWrapper::layout_impl() const { + return value_.unsafeGetTensorImpl()->layout(); +} + +namespace functionalization { +namespace impl { + +Tensor to_functional_tensor(const Tensor& tensor) { + // Note [Wrapped Numbers <> Functionalization] + if (tensor.unsafeGetTensorImpl()->is_wrapped_number()) { + return tensor; + } + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!isFunctionalTensor(tensor)); + return at::detail::make_tensor(tensor); +} +std::optional to_functional_tensor(const std::optional& tensor) { + if (tensor.has_value()) { + return to_functional_tensor(*tensor); + } + return std::nullopt; +} +c10::List<::std::optional> to_functional_tensor(const c10::List<::std::optional>& t_list) { + c10::List<::std::optional> outputs; + outputs.reserve(t_list.size()); + for (const auto i : c10::irange(t_list.size())) { + outputs.push_back(to_functional_tensor(t_list[i])); + } + return outputs; +} +std::vector to_functional_tensor(ITensorListRef t_list) { + std::vector outputs; + outputs.reserve(t_list.size()); + for (const auto& tensor : t_list) { + outputs.push_back(to_functional_tensor(tensor)); + } + return outputs; +} + +Tensor from_functional_tensor(const Tensor& tensor, bool assert_functional) { + // Note [Wrapped Numbers <> Functionalization] + if (!tensor.defined() || tensor.unsafeGetTensorImpl()->is_wrapped_number()) { + return tensor; + } + if (isFunctionalTensor(tensor)) { + auto impl = unsafeGetFunctionalWrapper(tensor); + return impl->value(); + } else { + // If the current tensor is not functional, then raise an error + // if assert_functional is true. Otherwise, return the input. + TORCH_INTERNAL_ASSERT(!assert_functional) + return tensor; + } +} +std::optional from_functional_tensor(const std::optional& t, bool assert_functional) { + if (t.has_value()) { + return from_functional_tensor(*t, assert_functional); + } + return std::nullopt; +} +std::vector from_functional_tensor(ITensorListRef t_list) { + std::vector outputs; + outputs.reserve(t_list.size()); + for (const auto& tensor : t_list) { + // from_functional_tensor(Tensor) has asserts to make sure you don't accidentally call + // it on a non-functional input, + // but from_functional_tensor(TensorList) can receive a list containing both + // functional and non-functional tensors. + // Example of when that can happen: torch.cat(function_input_tensor, global_state_tensor). + // When that happens, we're okay with only unwrapping the functional tensors. + outputs.push_back(from_functional_tensor(tensor, /*assert_functional=*/false)); + } + return outputs; +} +c10::List<::std::optional> from_functional_tensor(const c10::List<::std::optional>& t_list) { + c10::List<::std::optional> outputs; + outputs.reserve(t_list.size()); + for (const auto i : c10::irange(t_list.size())) { + outputs.push_back(from_functional_tensor(t_list[i], /*assert_functional=*/false)); + } + return outputs; +} + +void sync(const Tensor& t) { + if (t.unsafeGetTensorImpl()->is_wrapped_number()) { + // Note [Wrapped Numbers <> Functionalization] + // Unfortunately, we can't easily guarantee that wrapped numbers (scalar-tensors) + // get wrapped up in a FunctionalTensorWrapper object, since they skip the dispatcher. + // That shouldn't matter, since I don't think we're allowed to assign to wrapped numbers anyway. + return; + } + // Not every tensor that hits a functionalization kernel is necessarily a functional tensor. + // For example, xla_tensor.copy_(cpu_tensor) needs to hit the functionalization kernel + // to sync xla_tensor, but not cpu_tensor. + if (!at::functionalization::impl::isFunctionalTensor(t)) { + return; + } + auto functional_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(t); + functional_impl->sync_(); +} +void sync(const std::optional& t) { + if (t.has_value()) { + sync(*t); + } +} +void sync(ITensorListRef t_list) { + for (const auto& t : t_list) { + sync(t); + } +} +void sync(const c10::List<::std::optional>& t_list) { + for (const auto i : c10::irange(t_list.size())) { + sync(t_list[i]); + } +} + +void replace_(const Tensor& functional_tensor, const Tensor& other) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor)); + unsafeGetFunctionalWrapper(functional_tensor)->replace_(other); +} + +void replace_(const ITensorListRef functional_tensor, ITensorListRef other) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(functional_tensor.size() == other.size()); + auto functional_tensor_it = functional_tensor.begin(); + auto other_it = other.begin(); + for ([[maybe_unused]] const auto i : c10::irange(functional_tensor.size())) { + replace_(*functional_tensor_it++, *other_it++); + } +} + +void propagate_xla_data(const Tensor& functional_tensor, const Tensor& other) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor)); + if (functional_tensor.key_set().has(c10::DispatchKey::XLA)) { + at::_propagate_xla_data(at::functionalization::impl::unsafeGetFunctionalWrapper(functional_tensor) + ->value(), other); + } +} + +void propagate_xla_data(const ITensorListRef functional_tensor, ITensorListRef other) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(functional_tensor.size() == other.size()); + auto functional_tensor_it = functional_tensor.begin(); + auto other_it = other.begin(); + for ([[maybe_unused]] const auto i : c10::irange(functional_tensor.size())) { + propagate_xla_data(*functional_tensor_it++, *other_it++); + } +} + +void propagate_xla_data_direct(const Tensor& tensor, const Tensor& other) { + if (tensor.key_set().has(c10::DispatchKey::XLA)) { + at::_propagate_xla_data(tensor, other); + } + } + +void propagate_xla_data_direct(const ITensorListRef tensor, + ITensorListRef other) { + auto tensor_it = tensor.begin(); + auto other_it = other.begin(); + for ([[maybe_unused]] const auto i : c10::irange(tensor.size())) { + propagate_xla_data_direct(*tensor_it++, *other_it++); + } +} + +void commit_update(const Tensor& functional_tensor) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor)); + unsafeGetFunctionalWrapper(functional_tensor)->commit_update(); +} + +void commit_update(ITensorListRef functional_tensor) { + for (const auto& t : functional_tensor) { + commit_update(t); + } +} + +void unsafe_reset_storage(const Tensor& functional_tensor) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(functional_tensor)); + unsafeGetFunctionalWrapper(functional_tensor)->_unsafe_reset_storage(); +} + +void mark_mutation_hidden_from_autograd(const Tensor& functional_tensor) { + TORCH_CHECK(isFunctionalTensor(functional_tensor)); + unsafeGetFunctionalWrapper(functional_tensor)->mark_mutation_hidden_from_autograd(); +} + +bool are_all_mutations_hidden_from_autograd(const Tensor& functional_tensor) { + TORCH_CHECK(isFunctionalTensor(functional_tensor)); + return unsafeGetFunctionalWrapper(functional_tensor)->are_all_mutations_hidden_from_autograd(); +} + +bool are_all_mutations_under_no_grad_or_inference_mode(const Tensor& functional_tensor) { + TORCH_CHECK(isFunctionalTensor(functional_tensor)); + return unsafeGetFunctionalWrapper(functional_tensor)->are_all_mutations_under_no_grad_or_inference_mode(); +} + +bool isFunctionalTensor(const at::Tensor& tensor) { + return tensor.unsafeGetTensorImpl()->key_set().has(c10::DispatchKey::Functionalize); +} + +bool isBaseTensor(const at::Tensor& tensor) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isFunctionalTensor(tensor)); + return unsafeGetFunctionalWrapper(tensor)->isBaseTensor(); +} + +bool isFunctionalTensor(const std::optional& t) { + if (t.has_value()) { + return isFunctionalTensor(*t); + } else { + return false; + } +} + +bool isFunctionalTensor(const c10::List<::std::optional>& t_list) { + if (t_list.empty()) { return false; } + auto functional_count = 0; + for (const auto i : c10::irange(t_list.size())) { + auto const & e= t_list[i]; + if (!e.has_value() || !e->defined()) { continue; } + if (isFunctionalTensor(e)) { + ++functional_count; + } + } + return functional_count > 0; +} + +template +static bool isFunctionalTensorIListRef(c10::IListRef list) { + if (list.size() == 0) { return false; } + auto functional_count = 0; + for (const auto& tensor : list) { + if (!tensor.defined()) { continue; } + if (isFunctionalTensor(tensor)) { + ++functional_count; + } + } + return functional_count > 0; +} + +bool isFunctionalTensor(ITensorListRef list) { + return isFunctionalTensorIListRef(list); +} + +void freeze_functional_tensor(const Tensor& tensor) { + TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(tensor)); + auto functional_base_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(tensor); + functional_base_impl->freeze_storage(); +} + +Tensor create_functional_tensor_with_view_meta( + const at::Tensor& view_to_wrap, + const at::Tensor& base, + const std::shared_ptr& meta, + int64_t out_idx) { + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(view_to_wrap)); + TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(base)); + auto functional_base_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(base); + auto meta_ = meta; + if (out_idx != 0) { + // Note [out_idx in ViewMeta] + // When a view op outputs multiple tensors, each output needs its own separate ViewMeta. + // Each ViewMeta also tracks the index of the particular output tensor, which is needed in the reverse function. + meta_ = meta->to_out_index(out_idx); + } + return at::detail::make_tensor(view_to_wrap, functional_base_impl, meta_); +} + +std::vector create_functional_tensor_with_view_meta( + ITensorListRef view_to_wrap, + const at::Tensor& base, + const std::shared_ptr& meta) { + std::vector outputs(view_to_wrap.size()); + int64_t i = 0; + for (const auto& tensor : view_to_wrap) { + outputs[i] = create_functional_tensor_with_view_meta(tensor, base, meta, i); + i++; + } + return outputs; +} + +void mutate_view_meta(const at::Tensor& self, const std::shared_ptr& meta) { + TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(self)); + auto self_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(self); + self_impl->mutate_view_meta(meta); +} + +Tensor apply_view_meta_sequence( + const Tensor& base, + const std::vector>& sequence) { + Tensor r = base; + for (auto& vm : sequence) { + r = vm->forward(r); + } + return r; +} + +// Note [Propagating strides in the functionalization pass] +// In order to properly compute stride information, the functionalization pass +// calls each {view} reference implementations with meta tensors. +// The output meta tensor's stride info serves as a reference for what the correct strides should be. +void set_sizes_strides_offset(const Tensor& out, const Tensor& reference_out) { + out.unsafeGetTensorImpl()->set_sizes_and_strides(reference_out.sym_sizes(), reference_out.sym_strides(), reference_out.sym_storage_offset()); +} + +void set_sizes_strides_offset(const std::vector& outs, const std::vector& reference_outs) { + TORCH_INTERNAL_ASSERT(outs.size() == reference_outs.size()); + for (const auto i : c10::irange(reference_outs.size())) { + set_sizes_strides_offset(outs[i], reference_outs[i]); + } +} + +thread_local static bool _functionalizationReapplyViews; + +bool getFunctionalizationReapplyViewsTLS() { + return _functionalizationReapplyViews; +} +void setFunctionalizationReapplyViewsTLS(bool reapply_views) { + _functionalizationReapplyViews = reapply_views; +} + +} // namespace impl + + +// Given an **out-of-place** op that might internally call view/inplace ops, +// This function will "functionalize" it. +// That is, it will call the operator, but removing any intermediate views/mutations +// that are performed inside of it. +// This is useful for LTC/XLA, which would like to reuse some of our composite kernels +// from pytorch core but not have to worry about the view ops that they might call. +// e.g. at::block_diag +void functionalize_op_helper(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_arguments = schema.arguments().size(); + const auto arguments_begin = stack->size() - num_arguments; + auto arguments = torch::jit::last(stack, num_arguments); + + // Wrap all tensor-like inputs into FunctionalTensorWrappers. + // When we re-invoke the dispatcher, this will automatically enable the functionalization pass. + for (uint64_t idx = 0; idx < num_arguments; ++idx) { + const auto& ivalue = arguments[idx]; + if (ivalue.isTensor()) { + const auto& t = ivalue.toTensor(); + if (t.defined()) { + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(t), + "The composite op functionalization fallback expects its inputs all not to be functional tensors"); + auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(t)); + (*stack)[arguments_begin + idx] = t_new; + } + } else if (ivalue.isTensorList()) { + auto tensors = ivalue.toTensorList(); + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(tensors), + "The composite op functionalization fallback expects its inputs all not to be functional tensors"); + auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(tensors)); + (*stack)[arguments_begin + idx] = t_new; + } else if (ivalue.isOptionalTensorList()) { + auto opt_tensors = ivalue.toOptionalTensorList(); + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(opt_tensors), + "The composite op functionalization fallback expects its inputs all not to be functional tensors"); + auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(opt_tensors)); + (*stack)[arguments_begin + idx] = t_new; + } else if (ivalue.isList()) { + // Handle nested lists containing tensor lists (e.g., Tensor[][]). + auto list = ivalue.toList(); + for (const auto i : c10::irange(list.size())) { + const auto& elem = list.get(i); + if (elem.isTensorList()) { + auto tensors = elem.toTensorList(); + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(tensors), + "The composite op functionalization fallback expects its inputs all not to be functional tensors"); + list.set(i, c10::IValue(at::functionalization::impl::to_functional_tensor(tensors))); + } + } + } + } + + { + // Today when you call at::empty(device=lazy), the lazy backend decides whether or not to wrap + // the output in a functional tensor based on TLS. + // In this code, we're re-entrantly entering functionalization in the same call-stack, + // so we need to manually fix up TLS as if it hadn't already been called. + auto curr_tls = c10::impl::tls_local_dispatch_key_set(); + auto tls_reenable_functionalize = c10::impl::PODLocalDispatchKeySet(); + tls_reenable_functionalize.set_included(curr_tls.included_); + tls_reenable_functionalize.set_excluded(curr_tls.excluded_.remove(c10::DispatchKey::Functionalize)); + c10::impl::ForceDispatchKeyGuard guard_(tls_reenable_functionalize); + // So, we should probably provide a way to directly call a kernel registered to + // the `CompositeExplicitAutograd` key. + // We can't do that today, so this should be a reasonably good proxy + // (It won't work in cases where an op has both a CompositeExplicitAutograd kernel + // AND a dedicated meta kernel, but that probably shouldn't ever happen). + op.redispatchBoxed(c10::DispatchKeySet(c10::DispatchKey::Meta), stack); + } + + const auto num_returns = schema.returns().size(); + const auto returns_begin = stack->size() - num_returns; + auto returns = torch::jit::last(stack, num_returns); + + for (const auto idx : c10::irange(num_returns)) { + const auto& ivalue = returns[idx]; + if (ivalue.isTensor()) { + const auto& t = ivalue.toTensor(); + if (!t.defined()) { continue; } + at::functionalization::impl::sync(t); + auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(t)); + (*stack)[returns_begin + idx] = t_new; + } else if (ivalue.isTensorList()) { + auto tensors = ivalue.toTensorList(); + at::functionalization::impl::sync(tensors); + auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(tensors)); + (*stack)[returns_begin + idx] = t_new; + } else if (ivalue.isOptionalTensorList()) { + auto opt_tensors = ivalue.toOptionalTensorList(); + at::functionalization::impl::sync(opt_tensors); + auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(opt_tensors)); + (*stack)[returns_begin + idx] = t_new; + } else if (ivalue.isList()) { + // Handle nested lists containing tensor lists (e.g., Tensor[][]). + auto list = ivalue.toList(); + for (const auto i : c10::irange(list.size())) { + const auto& elem = list.get(i); + if (elem.isTensorList()) { + auto tensors = elem.toTensorList(); + at::functionalization::impl::sync(tensors); + list.set(i, c10::IValue(at::functionalization::impl::from_functional_tensor(tensors))); + } + } + } + } +} + + + +} // namespace functionalization +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.h b/western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..136be8d4fd171fc919fc7aaab57146fc57bb6ae5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalTensorWrapper.h @@ -0,0 +1,481 @@ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at { + +// Note [Functionalization Pass In Core] +// The Functionalization pass is used to remove aliasing from a pytorch program. +// +// This is useful for backends that don't support aliasing, like XLA and Vulkan. +// It's also necessary in order to remove mutation from a program, which is +// needed in Functorch. +// +// Consider this program: +// a = torch.ones(...) +// b = a.view(...) +// b.add_(1) +// +// In this program, b is meant to alias with a due to the use of view(). At the +// end of the program, both a and b are full of 2's. However, backends that +// don't support aliasing aren't able to correctly implement the view() +// operator. Instead, they can opt into the Functionalization pass, which will +// sit between the user and the backend, and provide the necessary aliasing +// logic. +// +// The functionalization pass will turn the above program into a slightly +// different program that has the same semantics, transparently to the user, +// that backends like XLA/Vulkan are able to implement a = torch.ones(...) b = +// a.view_copy(...) # view() replaced with view_copy(). Backends like +// XLA/Vulkan can implement this! b.add_(1) a.add_(1) # Our functionalization +// pass machinery knows that a and b are aliased - it applies b's mutation to a +// too. +// +// So, how does the functionalization pass keep track of which tensors are +// aliased? The pass works by wrapping EVERY tensor in the program inside of a +// FunctionalTensorWrapper, which knows about its alias'd tensors. +// +// See Note [Functionalization: Alias Removal] for details on the aliasing +// machinery. See Note [Functionalization: Mutation Removal] for details on +// mutation removal. +struct TORCH_API FunctionalTensorWrapper : public c10::TensorImpl { + explicit FunctionalTensorWrapper(const Tensor& value); + // Additional constructor to create a FunctionalTensorWrapper directly from an + // underlying tensor that was created from a view. For example, the code b = + // a.view1() will generate a constructor call to FunctionalTensorWrapper(b, a, + // view1_meta) + explicit FunctionalTensorWrapper( + const Tensor& view_value, + const FunctionalTensorWrapper* base, + const std::shared_ptr& meta); + + // Get the underlying, actual tensor, that doesn't know anything about + // functionalization. + const Tensor& value() const { + return value_; + } + // The concept of "level" is only ever important to functorch; it's exposed + // here as more of a hook for functorch to use. + int64_t level() const { + return level_; + } + void set_level(int64_t level) { + level_ = level; + } + bool has_metadata_mutation() const { + return has_metadata_mutation_; + } + uint64_t mutation_counter() const { + return functional_storage_impl()->mutation_counter(); + } + void mark_mutation() { + functional_storage_impl()->mark_mutation(); + } + // Denotes a mutation that's hidden from autograd, + // e.g. for the purposes of passing a tensor to a triton kernel + void mark_mutation_hidden_from_autograd() { + functional_storage_impl()->mark_mutation_hidden_from_autograd(); + } + void mark_mutation_during_no_grad_or_inference_mode() { + functional_storage_impl()->mark_mutation_during_no_grad_or_inference_mode(); + } + // Are all the mutations happening to the tensor hidden from autograd + bool are_all_mutations_hidden_from_autograd() const { + return functional_storage_impl()->are_all_mutations_hidden_from_autograd(); + } + // Did all mutations happen under no_grad or inference_mode + // (We also need to ignore mutations fully hidden from autograd here) + bool are_all_mutations_under_no_grad_or_inference_mode() const { + return functional_storage_impl() + ->are_all_mutations_under_no_grad_or_inference_mode(); + } + + void maybe_mark_symbolic(functionalization::ViewMeta* meta) { + is_symbolic_ = is_symbolic_ | meta->has_symbolic_inputs; + } + + bool is_symbolic() const { + return is_symbolic_; + } + + // Retrieves the ViewMeta sequence of this tensor. + const std::vector>& view_metas() + const; + + // Sync's the underlying tensor with its alias, if it's out of date. This + // involves two steps: 1) Apply any pending updates/mutations to the alias 2) + // Replay the views (if any) to regenerate the current tensor off of the + // updated alias. + void sync_(); + // Performs step (1) of the sync. This is its own public API because it's + // needed by view_inplace ops like transpose_. See Note [Functionalization + // Pass - Inplace View Ops] + void regenerate_from_base(); + // Performs step (2) of the sync. This is its own public API because it's + // needed by functorch. functorch wants to make sure that all input tensors to + // a functionalized program have been properly synced so it can properly + // propagate mutations to inputs. It can't just call sync_(), because the + // FunctionalTensorWrapper will look like it has no aliases and sync_ will be + // a noop. We use the reference count on storage_ to determine if the wrapper + // is aliased, and by the time functorch is ready to propagate updates to + // inputs, any intermediate views of the input created by the program will + // have been deallocated. This function also returns whether or not the base + // actually had any updates to apply. + bool apply_updates(); + // Takes the current state of value_ and snapshots it, sending it as a pending + // update to the alias. + void commit_update(); + // When any tensor is mutated, the tensor increments its alias's "generation". + // Separately, each tensor maintains its own "generation" counter, which is + // used to determine if it's up-to-date with its alias. The act of syncing a + // tensor will set a tensor's generation equal to its alias's generation. + bool is_up_to_date() const; + // Freezes the storage of this tensor, preventing subsequent mutations + void freeze_storage() const; + // Every FunctionalTensorWrapper contains a vector objects + // describing the series of view ops that ran to generate the current tensor + // from the base tensor. This method is used by inplace-view ops like + // transpose_. It appends a ViewMeta to the existing stack, and refreshes the + // tensor by replaying the views off of the alias. + void mutate_view_meta( + const std::shared_ptr& meta); + + // Custom implementation of self.set_(src) + void set__impl(const FunctionalTensorWrapper* other); + + // Custom implementation of resize_storage_bytes_(self, new_size) + void storage_resize_(const c10::SymInt& new_size); + + // Returns whether the current tensor's data was ever mutated + bool has_data_mutation(); + // + // Returns whether the current FunctionalTensorWrapper + // experienced a set_() call. + bool was_storage_changed() { + return was_storage_changed_; + } + + void mark_storage_changed() { + was_storage_changed_ = true; + storage_changed_counter_++; + } + + bool was_shallow_copy_data() { + return was_shallow_copy_data_; + } + + void mark_shallow_copy_data() { + was_shallow_copy_data_ = true; + } + + uint64_t storage_changed_counter() { + return storage_changed_counter_; + } + + // A FunctionalTensor is considered a base if its not a view of another + // tensor. + bool isBaseTensor() const { + return view_metas_.empty(); + } + + c10::SymInt get_storage_size(bool before) { + return functional_storage_impl()->get_storage_size(before); + } + + // Returns whether the FunctionalTensor experienced an + // untyped_storage().resize_() call + bool was_inductor_storage_resized() { + return functional_storage_impl()->was_inductor_storage_resized(); + } + + bool inductor_storage_resized_counter() { + return functional_storage_impl()->inductor_storage_resized_counter(); + } + // The functionalization pass can be used to remove mutations. + // It does so by replacing any mutation op with it's corresponding + // out-of-place op, followed by a call to replace_(). e.g: + // + // a.add_(1) + // + // will turn into: + // + // tmp = a.add(1) + // a.replace_(tmp) + // + // replace_() swaps out the wrapped tensor, value_, with tmp. + void replace_(const Tensor& other, bool from_lazy_regenerate = false); + + bool is_multi_output_view() { + return is_multi_output_view_; + } + + // See Note[resize_() in functionalization pass] + void maybe_replace_storage(const Tensor& other); + + // Replaces the storage with a new functional storage, + // and clears the view_metas_ stack. + // WARNING: Calling this function will sever the aliasing relationship between + // the current FunctionalTensorWrapper and any of its outstanding aliases. + // Please only call if you know what you're doing. + void _unsafe_reset_storage(); + + c10::intrusive_ptr shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const override; + + c10::intrusive_ptr shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const override; + + ~FunctionalTensorWrapper() override = default; + + // FunctionalTensorWrapper overrides all custom size/stride function, + // so that if the inner tensor has a custom implementation + // we make sure to call that implementation. + at::IntArrayRef sizes_custom() const override; + at::IntArrayRef strides_custom() const override; + int64_t dim_custom() const override; + int64_t numel_custom() const override; + c10::SymBool sym_is_contiguous_custom( + at::MemoryFormat memory_format) const override; + c10::SymIntArrayRef sym_sizes_custom() const override; + c10::SymInt sym_size_custom(int64_t d) const override; + c10::SymIntArrayRef sym_strides_custom() const override; + c10::SymInt sym_storage_offset_custom() const override; + c10::Device device_custom() const override; + c10::Layout layout_impl() const override; + + private: + const char* tensorimpl_type_name() const override; + void set_constructor_metadata(); + functionalization::FunctionalStorageImpl* functional_storage_impl() const; + + // This is used to re-implement shallow_copy_and_detach for + // FunctionalTensorWrapper. The implementation is identical, but we just need + // to return a subclass instead of a plain TensorImpl. + // TODO: maybe it's possible to arrange for that to happen automatically + // without an override here? + template + c10::intrusive_ptr shallow_copy_and_detach_core( + VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const; + + void shallow_copy_from(const c10::intrusive_ptr& impl) override; + void copy_tensor_metadata_and_refresh( + const FunctionalTensorWrapper* src_impl, + FunctionalTensorWrapper* dest_impl, + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const; + + // Note that value is not taken by reference: internally, the wrapper will + // change the value tensor that it points to over time. + Tensor value_; + int64_t level_{}; + // These two counters are used for identifying + // whether all the mutations on a given tensor are hidden from autograd or + // not. If we have an input mutation that is hidden from autograd, then once + // we convert the input mutation to a copy_() we know it will be safe to hide + // the copy_() from autograd as well. + bool has_metadata_mutation_ = false; + bool is_multi_output_view_ = false; + // Did the tensor experience a set_() call. + bool was_storage_changed_ = false; + // Did the tensor experience a shallow_copy_data_() call. + bool was_shallow_copy_data_ = false; + uint64_t storage_changed_counter_ = 0; + // Did the tensor experience any view operation with symbolic int. + bool is_symbolic_ = false; + + size_t generation_ = 0; + std::vector> view_metas_; + + protected: + static void copy_tensor_metadata( + const FunctionalTensorWrapper* src_impl, + FunctionalTensorWrapper* dest_impl, + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change); +}; + +// Utility functions for the functionalization pass. + +namespace functionalization { +namespace impl { + +inline FunctionalTensorWrapper* unsafeGetFunctionalWrapper( + const Tensor& tensor) { + auto functional_impl = + static_cast(tensor.unsafeGetTensorImpl()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(functional_impl != nullptr); + return functional_impl; +} + +TORCH_API bool isBaseTensor(const at::Tensor& tensor); + +TORCH_API bool isFunctionalTensor(const at::Tensor& tensor); +TORCH_API bool isFunctionalTensor(const std::optional& t); +TORCH_API bool isFunctionalTensor( + const c10::List>& t_list); +TORCH_API bool isFunctionalTensor(ITensorListRef list); + +TORCH_API Tensor to_functional_tensor(const Tensor& tensor); +TORCH_API std::optional to_functional_tensor( + const std::optional& tensor); +TORCH_API c10::List> to_functional_tensor( + const c10::List>& t_list); +TORCH_API std::vector to_functional_tensor(ITensorListRef t_list); + +TORCH_API void freeze_functional_tensor(const Tensor& tensor); + +TORCH_API Tensor +from_functional_tensor(const Tensor& tensor, bool assert_functional = true); +TORCH_API std::optional from_functional_tensor( + const std::optional& t, + bool assert_functional = true); +TORCH_API c10::List> from_functional_tensor( + const c10::List>& t_list); +TORCH_API std::vector from_functional_tensor(ITensorListRef t_list); + +TORCH_API void sync(const at::Tensor& t); +TORCH_API void sync(const std::optional& t); +TORCH_API void sync(const c10::List>& t_list); +TORCH_API void sync(ITensorListRef t_list); + +TORCH_API void replace_(const Tensor& functional_tensor, const Tensor& other); +TORCH_API void replace_( + const ITensorListRef functional_tensor, + ITensorListRef other); + +TORCH_API void commit_update(const Tensor& functional_tensor); +TORCH_API void commit_update(ITensorListRef functional_tensor); + +TORCH_API void unsafe_reset_storage(const Tensor& functional_tensor); + +TORCH_API void mark_mutation_hidden_from_autograd( + const Tensor& functional_tensor); + +TORCH_API bool are_all_mutations_hidden_from_autograd( + const Tensor& functional_tensor); + +TORCH_API bool are_all_mutations_under_no_grad_or_inference_mode( + const Tensor& functional_tensor); + +// These two methods are XLA-specific logic and are no-ops +// for the normal functionalization flow. +TORCH_API void propagate_xla_data( + const Tensor& functional_tensor, + const Tensor& other); +TORCH_API void propagate_xla_data( + const ITensorListRef functional_tensor, + ITensorListRef other); + +TORCH_API void propagate_xla_data_direct( + const Tensor& tensor, + const Tensor& other); +TORCH_API void propagate_xla_data_direct( + const ITensorListRef tensor, + ITensorListRef other); + +Tensor create_functional_tensor_with_view_meta( + const Tensor& view_to_wrap, + const Tensor& base, + const std::shared_ptr& meta, + int64_t out_idx = 0); +std::vector create_functional_tensor_with_view_meta( + ITensorListRef view_to_wrap, + const Tensor& base, + const std::shared_ptr& meta); + +void mutate_view_meta( + const Tensor& self, + const std::shared_ptr& meta); + +TORCH_API Tensor apply_view_meta_sequence( + const Tensor& base, + const std::vector>& sequence); + +void set_sizes_strides_offset(const Tensor& out, const Tensor& meta_out); +void set_sizes_strides_offset( + const std::vector& outs, + const std::vector& meta_outs); + +// ~~~~~ TLS used in functionalization ~~~~~ + +TORCH_API bool getFunctionalizationReapplyViewsTLS(); +TORCH_API void setFunctionalizationReapplyViewsTLS(bool reapply_views); + +class TORCH_API FunctionalizationReapplyViewsGuard { + public: + FunctionalizationReapplyViewsGuard(bool reapply_views) + : prev_(getFunctionalizationReapplyViewsTLS()) { + setFunctionalizationReapplyViewsTLS(reapply_views); + } + + ~FunctionalizationReapplyViewsGuard() { + setFunctionalizationReapplyViewsTLS(prev_); + } + + FunctionalizationReapplyViewsGuard( + const FunctionalizationReapplyViewsGuard&) = delete; + FunctionalizationReapplyViewsGuard operator=( + const FunctionalizationReapplyViewsGuard&) = delete; + FunctionalizationReapplyViewsGuard(FunctionalizationReapplyViewsGuard&&) = + delete; + FunctionalizationReapplyViewsGuard operator=( + FunctionalizationReapplyViewsGuard&&) = delete; + + private: + bool prev_; +}; + +} // namespace impl + +// Helper function to call an out-of-place composite aten kernel that may use +// mutations / views internally, and functionalize them. +TORCH_API void functionalize_op_helper( + const c10::OperatorHandle& op, + torch::jit::Stack* stack); + +template +struct _functionalize_aten_op final {}; + +template +struct _functionalize_aten_op final { + static ReturnType call( + typename c10::maybe_keep_symint::type... args) { + using FuncType = ReturnType( + typename c10::maybe_keep_symint::type...); + auto op = c10::Dispatcher::singleton() + .findSchemaOrThrow( + (const char*)Op::name, (const char*)Op::overload_name) + .typed(); + + return c10::impl::BoxedKernelWrapper::call( + c10::BoxedKernel::makeFromFunction(), + op, + // BoxedKernelWrapper knows to ignore this keyset argument, + // because functionalize_op_helper doesn't take in a DispatchKeySet + c10::DispatchKeySet(), + args...); + } +}; + +template +using functionalize_aten_op = + _functionalize_aten_op; + +template +using functionalize_aten_op_symint = + _functionalize_aten_op; + +} // namespace functionalization +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b02c1aa61336e13e8f20e189b7f5a5ee2b82388 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.cpp @@ -0,0 +1,425 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace at::functionalization { + +Tensor resize__ViewMeta::forward(const Tensor& base) { + if (!reapply_views) { + return at::as_strided_copy(base, size, c10::contiguous_strides(size)); + } + return base.as_strided(size, c10::contiguous_strides(size)); +} + +Tensor resize__ViewMeta::reverse(const Tensor& base, const Tensor& mutated_view) { + return base.as_strided_scatter( + mutated_view, size, c10::contiguous_strides(size)); +} + +Tensor _unsafe_view_ViewMeta::forward(const Tensor& base) { + return at::_unsafe_view_symint(base, size); +} + +Tensor _unsafe_view_ViewMeta::reverse(const Tensor& base, const Tensor& mutated_view) { + return at::_unsafe_view_symint(mutated_view, base.sym_sizes()); +} + +} // namespace at::functionalization + +namespace { + void functionalizeFallback(const c10::OperatorHandle& op, c10::DispatchKeySet dispatchKeySet [[maybe_unused]], torch::jit::Stack* stack) { + const auto& schema = op.schema(); + // NB: auto_functionalize handles the case where outputs do not have alias info. + // This error message therefore suggests users to modify their custom op to the + // point where auto_functionalize works instead of asking them to try the raw + // functionalization API (because that is a bit difficult to use). + // If you're here and want to try the raw functionalizaton kernel approach, + // see https://gist.github.com/bdhirsh/7dadbf6296f8f7d1abcf4c482f438aaa + TORCH_CHECK( + !schema.hasAnyAliasInfo(), + "Found a custom (non-ATen) operator whose output has alias annotations: ", + op.schema(), + ". We only support functionalizing operators whose outputs do not have alias ", + "annotations (e.g. 'Tensor(a)' is a Tensor with an alias annotation whereas ", + "'Tensor' is a Tensor without. The '(a)' is the alias annotation). " + "The alias annotation specifies that the output ", + "Tensor shares storage with an input that has the same annotation. ", + "Please check if ", + "(1) the output needs to be an output (if not, don't return it), ", + "(2) if the output doesn't share storage with any inputs, then ", + "delete the alias annotation. ", + "(3) if the output indeed shares storage with an input, then add a ", + ".clone() before returning it to prevent storage sharing and then " + "delete the alias annotation. ", + "Otherwise, please file an issue on GitHub."); + const auto num_arguments = schema.arguments().size(); + const auto arguments_begin = stack->size() - num_arguments; + auto arguments = torch::jit::last(stack, num_arguments); + + auto any_functional_inputs = false; + auto any_tensor_inputs = false; + for (uint64_t idx = 0; idx < num_arguments; ++idx) { + const auto& ivalue = arguments[idx]; + if (ivalue.isTensor()) { + any_tensor_inputs = true; + const auto& t = ivalue.toTensor(); + if (t.defined() && at::functionalization::impl::isFunctionalTensor(t)) { + any_functional_inputs = true; + at::functionalization::impl::sync(t); + auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(t)); + (*stack)[arguments_begin + idx] = t_new; + } + } else if (ivalue.isTensorList()) { + any_tensor_inputs = true; + auto tensors = ivalue.toTensorList(); + if (at::functionalization::impl::isFunctionalTensor(tensors)) { + any_functional_inputs = true; + at::functionalization::impl::sync(tensors); + auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(tensors)); + (*stack)[arguments_begin + idx] = t_new; + } + } else if (ivalue.isOptionalTensorList()) { + any_tensor_inputs = true; + auto opt_tensors = ivalue.toOptionalTensorList(); + if (at::functionalization::impl::isFunctionalTensor(opt_tensors)) { + any_functional_inputs = true; + at::functionalization::impl::sync(opt_tensors); + auto t_new = c10::IValue(at::functionalization::impl::from_functional_tensor(opt_tensors)); + (*stack)[arguments_begin + idx] = t_new; + } + } else if (ivalue.isList()) { + // Handle nested lists containing tensor lists (e.g., Tensor[][]). + auto list = ivalue.toList(); + for (const auto i : c10::irange(list.size())) { + const auto& elem = list.get(i); + if (elem.isTensorList()) { + any_tensor_inputs = true; + auto tensors = elem.toTensorList(); + if (at::functionalization::impl::isFunctionalTensor(tensors)) { + any_functional_inputs = true; + at::functionalization::impl::sync(tensors); + list.set(i, c10::IValue(at::functionalization::impl::from_functional_tensor(tensors))); + } + } + } + } + } + // we should wrap the output if any inputs were wrapped, + // OR if we're hitting a factory function (with no tensor inputs) + auto should_wrap_outputs = !any_tensor_inputs || any_functional_inputs; + { + at::AutoDispatchSkipFunctionalize guard; + op.callBoxed(stack); + } + const auto num_returns = schema.returns().size(); + const auto returns_begin = stack->size() - num_returns; + auto returns = torch::jit::last(stack, num_returns); + + for (const auto idx : c10::irange(num_returns)) { + const auto& ivalue = returns[idx]; + if (ivalue.isTensor() && should_wrap_outputs) { + const auto& t = ivalue.toTensor(); + if (!t.defined()) { + continue; + } + auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(t)); + (*stack)[returns_begin + idx] = t_new; + } else if (ivalue.isTensorList() && should_wrap_outputs) { + auto tensors = ivalue.toTensorList(); + auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(tensors)); + (*stack)[returns_begin + idx] = t_new; + } else if (ivalue.isOptionalTensorList() && should_wrap_outputs) { + auto opt_tensors = ivalue.toOptionalTensorList(); + auto t_new = c10::IValue(at::functionalization::impl::to_functional_tensor(opt_tensors)); + (*stack)[returns_begin + idx] = t_new; + } else if (ivalue.isList() && should_wrap_outputs) { + // Handle nested lists containing tensor lists (e.g., Tensor[][]). + auto list = ivalue.toList(); + for (const auto i : c10::irange(list.size())) { + const auto& elem = list.get(i); + if (elem.isTensorList()) { + auto tensors = elem.toTensorList(); + list.set(i, c10::IValue(at::functionalization::impl::to_functional_tensor(tensors))); + } + } + } + } + } +} + +// resize_() is special because: +// - when we resize to a larger size, it acts as a mutation +// - when we resize to a smaller size, it acts as a view +// See Note [resize_ in Functionalization] for more dtails +static const at::Tensor & resize__functionalization(c10::DispatchKeySet dispatchKeySet [[maybe_unused]], const at::Tensor & self, at::IntArrayRef size, std::optional memory_format) { + // First unwrap the tensor arguments + at::Tensor self_; + if (at::functionalization::impl::isFunctionalTensor(self)) { + at::functionalization::impl::sync(self); + self_ = at::functionalization::impl::from_functional_tensor(self); + } else { + self_ = self; + } + // Case 1: arguments are not functional tensors, so we no-op and redispatch. + if (!at::functionalization::impl::isFunctionalTensor(self)) { + at::AutoDispatchSkipFunctionalize guard; + self_.resize_(size, memory_format); + return self; + } + + // Case 2: actually functionalize resize_() + at::Tensor tmp_output; + { + at::AutoDispatchSkipFunctionalize guard; + tmp_output = at::resize(self_, size, memory_format); + } + + auto itemsize = self.dtype().itemsize(); + auto storage_offset = self.storage_offset(); + auto new_size_bytes = at::detail::computeStorageNbytesContiguous(size, itemsize, storage_offset); + auto needs_resize_storage = new_size_bytes > self.storage().nbytes(); + + if (needs_resize_storage) { + // If resize_() actually increases the size of the storage, then we need to tell FunctionalTensorWrapper about it. + // See Note[resize_() in functionalization pass] + auto func_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(self); + func_impl->maybe_replace_storage(tmp_output); + // See the note - we're guaranteed at this point that "self" is *not* a view (and has no outstanding views) + // So we don't need to treat the output of resize as view tensor. + return self; + } + + // Otherwise, we know that we're resizing to a smaller size. + // resize_() is effectively a view operator. + // The output of resizing is equivalent to taking a slice of a larger tensor. + // We have to emulate this "slicing" with an as_strided call. + auto reapply_views = at::functionalization::impl::getFunctionalizationReapplyViewsTLS(); + auto view_meta = std::make_shared( + reapply_views, size.vec()); + at::functionalization::impl::mutate_view_meta(self, view_meta); + return self; +} + + +static at::Tensor lift_functionalize(const at::Tensor & self) { + if (at::functionalization::impl::isFunctionalTensor(self)) { + return self.view_as(self); + } + + at::AutoDispatchSkipFunctionalize guard; + auto out = at::lift(self); + return at::functionalization::impl::to_functional_tensor(out); +} + +static at::Tensor lift_fresh_functionalize(const at::Tensor & self) { + // See Note [Exporting and compiling a graph with lift_fresh_copy] + if (at::functionalization::impl::isFunctionalTensor(self)) { + return self.view_as(self); + } + + at::AutoDispatchSkipFunctionalize guard; + auto out = at::lift_fresh(self); + return at::functionalization::impl::to_functional_tensor(out); +} + +static at::Tensor lift_fresh_functionalize_copy(const at::Tensor & self) { + // Note [Exporting and compiling a graph with lift_fresh_copy] + // If out is already a functional tensor, don't wrap it twice. + // In theory this could be useful if we want to nest functionalization with itself, + // but that isn't really a use case today. + // Needed for https://github.com/pytorch/pytorch/issues/105327 + if (at::functionalization::impl::isFunctionalTensor(self)) { + // Note [Composite Functionalization under PreDispatch mode] + // When we are tracing under PreDispatch, PreDispatch key will be + // in the local include TLS. As a result, when we redispatch here, + // we will end up hitting PreDispatch stack first. So, we should + // directly redispatch to the functionalize key manually. + static auto op = c10::Dispatcher::singleton().findSchemaOrThrow("aten::clone", "").typed)>(); + return op.redispatch(c10::DispatchKeySet({c10::DispatchKey::Functionalize}), self, std::nullopt); + } + + at::AutoDispatchSkipFunctionalize guard; + auto out = at::lift_fresh_copy(self); + return at::functionalization::impl::to_functional_tensor(out); +} + +static bool device_opted_into_functionalization(c10::Device self_device, std::optional tgt_device) { + // If the target device is empty, then the output tensor should be on the same device as the input + auto real_tgt_device = tgt_device.has_value() ? tgt_device.value() : self_device; + return real_tgt_device.type() == c10::DeviceType::XLA || real_tgt_device.type() == c10::DeviceType::Lazy; +} + +// note I only need this because the to.dtype/to.dtype_layout overload calls this, so we skip the op above. +// We should probably get rid of this though. +static at::Tensor _to_copy_functionalize( + const at::Tensor & self, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory, + bool non_blocking, + std::optional memory_format) { + at::Tensor self_; + if (at::functionalization::impl::isFunctionalTensor(self)) { + // sync any pending updates + at::functionalization::impl::sync(self); + // pass the unwrapped tensor to the backend + self_ = at::functionalization::impl::from_functional_tensor(self); + } else { + self_ = self; + } + + at::AutoDispatchSkipFunctionalize guard; + auto out = at::_to_copy(self_, dtype, layout, device, pin_memory, non_blocking, memory_format); + + // Special case: if the Functionalize key is not in TLS, we assume that we're running + // on a lazy backend (LTC). + // In that case, if we're copying to a non-functionalize-enabled device, + // then the functionalization pass should "end". We need to sync any updates on the input + // tensor, but we shouldn't wrap the output. + if (!c10::impl::tls_local_dispatch_key_set().included_.has(c10::DispatchKey::Functionalize)) { + if (!device_opted_into_functionalization(self.device(), device)) { + return out; + } + } + return at::functionalization::impl::to_functional_tensor(out); +} + + +// Why is _unsafe_view special-cased here? +// Basically just to satisfy autograd's debug asserts. +// The situation: +// - _unsafe_view's autograd kernel has debug asserts to confirm +// that the input and output alias storage. +// - _unsafe_view's schema in native_functions.yaml +// does not contain alias annotations, so it advertises as non-aliasing. +// - functionalization will then treat _unsafe_view like a non-aliasing op. +// Specifically, autograd will redispatch to functionalization's +// boxed fallback kernel, which creates a new FunctionalTensorWrapper output +// that does **not** alias storage with the input, tripping the assert. +// The kernel written here just manually re-ifies the aliasing relationship. +// +// Another way to handle this would be to fix unsafe_view's alias annotations +// in native_functions.yaml, but I think this would be a pessimization. +// The idea with _unsafe_view is that you're guaranteed that the input +// is a temporary, and don't actually have to worry about propagating +// mutations between the input and output. +static at::Tensor _unsafe_view_functionalize(const at::Tensor & self, at::SymIntArrayRef size) { + if (!at::functionalization::impl::isFunctionalTensor(self)) { + at::AutoDispatchSkipFunctionalize guard; + return at::_unsafe_view_symint(self, size); + } + + auto self_ = at::functionalization::impl::from_functional_tensor(self); + at::Tensor tmp_output; + { + at::AutoDispatchSkipFunctionalize guard; + tmp_output = at::_unsafe_view_symint(self_, size); + } + + bool has_symbolic_inputs = std::any_of( + size.begin(), size.end(), [=](auto& s) { return s.is_symbolic(); }); + auto view_meta = + std::make_shared( + has_symbolic_inputs, size.vec()); + + auto out = at::functionalization::impl::create_functional_tensor_with_view_meta(tmp_output, self, std::move(view_meta)); + // See Note [Propagating strides in the functionalization pass] + // (for _unsafe_view, I'm just manually doing the shape inference rule here instead of calling the meta function for unsafe_view) + auto inferred_size = at::infer_size_dv(size, self.sym_numel()); + + auto stride = at::detail::computeStride(self.sym_sizes(), self.sym_strides(), inferred_size); + + if (!stride.has_value()) { + + TORCH_SYM_CHECK( + self.sym_is_contiguous(), + "View is not valid from size:", + self.sym_sizes(), + " stride: ", + self.sym_strides(), + " to shape: ", + inferred_size, + " in case of unbacked symbols consider adding torch.check to guide computing strides."); + + // With unbacked symints, computeStride could fail even on contiguous + // tensors. In this case, we can use the strides of an empty tensor of + // inferred_size. + stride = at::detail::empty_symint_meta( + inferred_size, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt) + .sym_strides(); + } + + out.unsafeGetTensorImpl()->set_sizes_and_strides(inferred_size, stride.value()); + return out; +} + +static at::Tensor& set__functionalize(at::Tensor& self, const at::Tensor& src) { + // error case + TORCH_CHECK(at::functionalization::impl::isFunctionalTensor(self) || !at::functionalization::impl::isFunctionalTensor(src), + "set__functionalize: Tried to mutate a non-functional tensor with a functional tensor, which is not allowed"); + + // nop case + if (!at::functionalization::impl::isFunctionalTensor(self) && !at::functionalization::impl::isFunctionalTensor(src)) { + at::AutoDispatchSkipFunctionalize guard; + return self.set_(src); + } + + TORCH_CHECK(at::functionalization::impl::isFunctionalTensor(src), + "set__functionalize: We do not currently support x.set_(y) where y is not a FunctionalTensor. Please file an issue"); + + TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(self)); + TORCH_INTERNAL_ASSERT(at::functionalization::impl::isFunctionalTensor(src)); + auto self_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(self); + auto src_impl = at::functionalization::impl::unsafeGetFunctionalWrapper(src); + // See Note [Ordering of resize_() and set_()] + TORCH_CHECK(!self_impl->was_inductor_storage_resized(), + "storage_resize_() followed by set_() in torch.compile is not supported today"); + self_impl->set__impl(src_impl); + return self; +} + +TORCH_LIBRARY_IMPL(_, Functionalize, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&functionalizeFallback>()); +} + +TORCH_LIBRARY_IMPL(aten, Functionalize, m) { + m.impl("resize_", TORCH_FN(resize__functionalization)); + m.impl("lift", TORCH_FN(lift_functionalize)); + m.impl("lift_fresh", TORCH_FN(lift_fresh_functionalize)); + m.impl("lift_fresh_copy", TORCH_FN(lift_fresh_functionalize_copy)); + m.impl("_to_copy", TORCH_FN(_to_copy_functionalize)); + m.impl("_unsafe_view", TORCH_FN(_unsafe_view_functionalize)); + // The overloads of set_() that take in a storage should never + // appear with torch.compile, because dynamo graph breaks + m.impl("set_.source_Tensor", TORCH_FN(set__functionalize)); +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.h b/western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..eb145b0ccb74d6879f365c37e7e94f61f383adbe --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/FunctionalizeFallbackKernel.h @@ -0,0 +1,58 @@ +#pragma once + +#include + +namespace at::functionalization { + +// `ViewMeta` implementation for `resize_` operation. +struct TORCH_API resize__ViewMeta : public ViewMeta { + FUNCTIONALIZATION_VIEWMETA_NAME(resize__ViewMeta) + FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE( + bool /* reapply_views */, + std::vector); + + resize__ViewMeta(const SerializableTuple& tpl) + : resize__ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {} + + resize__ViewMeta(bool reapply_views, const std::vector& size) + : ViewMeta(/*has_symbolic_inputs=*/false), + reapply_views(reapply_views), + size(size) {} + + Tensor forward(const Tensor& base) override; + Tensor reverse(const Tensor& base, const Tensor& mutated_view) override; + + SerializableTuple to_serializable_tuple() { + return std::make_tuple(reapply_views, size); + } + + bool reapply_views; + std::vector size; +}; + +// `ViewMeta` implementation for `_unsafe_view` operation. +struct TORCH_API _unsafe_view_ViewMeta : public ViewMeta { + FUNCTIONALIZATION_VIEWMETA_NAME(_unsafe_view_ViewMeta) + FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE( + bool /* has_symbolic_inputs */, + std::vector); + + _unsafe_view_ViewMeta(const SerializableTuple& tpl) + : _unsafe_view_ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {} + + _unsafe_view_ViewMeta( + bool has_symbolic_inputs, + const std::vector& size) + : ViewMeta(has_symbolic_inputs), size(size) {} + + Tensor forward(const Tensor& base) override; + Tensor reverse(const Tensor& base, const Tensor& mutated_view) override; + + SerializableTuple to_serializable_tuple() { + return std::make_tuple(has_symbolic_inputs, size); + } + + std::vector size; +}; + +} // namespace at::functionalization diff --git a/western_ai/usa/pytorch/aten/src/ATen/Generator.h b/western_ai/usa/pytorch/aten/src/ATen/Generator.h new file mode 100644 index 0000000000000000000000000000000000000000..741e39f29dae4cca6cb39f8b1d385bb14ed1b6c5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Generator.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/InferSize.h b/western_ai/usa/pytorch/aten/src/ATen/InferSize.h new file mode 100644 index 0000000000000000000000000000000000000000..c5bf1c9628ca31df890dc10bbf981a24fa961695 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/InferSize.h @@ -0,0 +1,128 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { + +// Infers the size of a dim with size -1, if it exists. Also checks that new +// shape is compatible with the number of elements. +// +// templated to handle std::vector and DimVector use cases, see +// below +// +template +inline void infer_size_impl( + InputArrayRef shape, + NumelType numel, + ResultVec& res) { + NumelType newsize = 1; + // N.B. this is an index, not a sym dim! + std::optional infer_dim; + for (int64_t dim = 0, ndim = shape.size(); dim != ndim; dim++) { + if (TORCH_GUARD_OR_FALSE(sym_eq(shape[dim], -1))) { + TORCH_CHECK(!infer_dim, "only one dimension can be inferred"); + infer_dim = dim; + } else { + // in case of unbacked shape[dim] we assume it's not -1 and add a runtime + // assertion. + TORCH_MAYBE_SYM_CHECK( + sym_gt(shape[dim], -1), + "invalid shape dimension ", + shape[dim], + " at index ", + dim, + " of shape ", + shape); + newsize *= shape[dim]; + } + } + + if (infer_dim) { + // numel is the product of known sizes, it has to be divisible by newsize. + // and newsize should be positive unless newsize == numel (we throw + // different) error message in that case. + if constexpr (std::is_same_v) { + auto v = newsize.maybe_as_int(); + if (v and *v == 0) { + // Avoid div by 0 when sym_eq(numel % newsize, 0) is constructed! + // which may happen when newsize is not a symbol! if its a symbol + // division won't happen anyway during compile. + TORCH_MAYBE_SYM_CHECK( + numel == newsize, + "shape '", + shape, + "' is invalid for input of size ", + numel); + } else { + auto cond = sym_gt(newsize, 0) + .sym_and(sym_eq(numel % newsize, 0)) + .sym_or(sym_eq(numel, newsize)); + TORCH_MAYBE_SYM_CHECK( + cond, "shape '", shape, "' is invalid for input of size ", numel); + } + + } else { + TORCH_CHECK( + (newsize > 0 && (numel % newsize == 0)) || numel == newsize, + "shape '", + shape, + "' is invalid for input of size ", + numel); + } + + // We have a degree of freedom here to select the dimension size; follow + // NumPy semantics and just bail. However, a nice error message is needed + // because users often use `view` as a way to flatten & unflatten + // dimensions and will otherwise be confused why + // empty_tensor.view( 0, 0) + // works yet + // empty_tensor.view(-1, 0) + // doesn't. + TORCH_MAYBE_SYM_CHECK( + newsize != 0, + "cannot reshape tensor of 0 elements into shape ", + shape, + " because the unspecified dimension size -1 can be any " + "value and is ambiguous"); + + res[*infer_dim] = numel / newsize; + return; + } + + TORCH_MAYBE_SYM_CHECK( + sym_eq(numel, newsize), + "shape '", + shape, + "' is invalid for input of size ", + numel); +} + +inline std::vector infer_size(IntArrayRef shape, int64_t numel) { + auto res = shape.vec(); + infer_size_impl(shape, numel, res); + return res; +} + +inline at::DimVector infer_size_dv(IntArrayRef shape, int64_t numel) { + auto res = at::DimVector(shape); + infer_size_impl(shape, numel, res); + return res; +} + +inline at::SymDimVector infer_size_dv( + c10::SymIntArrayRef shape, + c10::SymInt numel) { + auto res = at::SymDimVector(shape); + infer_size_impl( + shape, std::move(numel), res); + return res; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/InitialTensorOptions.h b/western_ai/usa/pytorch/aten/src/ATen/InitialTensorOptions.h new file mode 100644 index 0000000000000000000000000000000000000000..58289fb41c6f66b85ca17297864e1639f0a78441 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/InitialTensorOptions.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace at { + +// Represents the initial TensorOptions, before the "defaults" are ever changed. +// This is designed to be used in library code, where the explicit devices, +// dtypes, etc. are known. NOTE: this is not a stable API. +inline TensorOptions initialTensorOptions() { + return TensorOptions(kCPU).dtype(kFloat).layout(kStrided).requires_grad( + false); +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/Layout.h b/western_ai/usa/pytorch/aten/src/ATen/Layout.h new file mode 100644 index 0000000000000000000000000000000000000000..11bda768d2fc435e5aa32c764097ef158fe4a315 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/Layout.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.cpp b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69e8c4019792bd27be1bf5d2f145f19f1122d8c0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.cpp @@ -0,0 +1,378 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { + +// Given a linear index, return the actual index. +// Example: Given linear_idx = 3, sizes = [5, 2], we would return [1, 0] +static SmallVector +computeIndex(int64_t linear_idx, IntArrayRef sizes) { + SmallVector result; + result.reserve(sizes.size()); + for (auto it = sizes.rbegin(); it != sizes.rend(); it++) { + auto remainder = linear_idx % *it; + result.push_back(remainder); + linear_idx -= remainder; + linear_idx /= *it; + } + std::reverse(std::begin(result), std::end(result)); + return result; +} + +static bool areAllReturnsTensors(const FunctionSchema& schema) { + return std::all_of( + schema.returns().begin(), + schema.returns().end(), + [] (const Argument& arg) { return arg.type() == TensorType::get(); }); +} + +static bool areAnyArgumentsTensorList(const FunctionSchema& schema) { + return std::any_of( + schema.arguments().begin(), + schema.arguments().end(), + [] (const Argument& arg) { return arg.type()->isSubtypeOf(*ListType::ofTensors()); }); +} + +// Returns if an operator is in-place. An operator is inplace if: +// 1. The first argument is a Tensor and it is being written to +// 2. The first argument is being returned +// 3. No other arguments are aliased +// Here is an example of an in-place operator: +// add_(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) +static bool isInplaceOp(const c10::FunctionSchema& schema) { + if (!schema.is_mutable() || schema.returns().size() != 1) { + return false; + } + // Check that the first argument is being written to + const AliasInfo* first_arg_alias_info = schema.arguments().begin()->alias_info(); + if (!first_arg_alias_info || !first_arg_alias_info->isWrite()) { + return false; + } + // Check that none of the other args are being aliased + for (auto it = schema.arguments().begin() + 1; it != schema.arguments().end(); ++it) { + const AliasInfo* alias_info = it->alias_info(); + if (alias_info) { + return false; + } + } + // Check that the first tensor is being returned (i.e., output has a (a!)) + const AliasInfo* return_alias_info = schema.returns()[0].alias_info(); + return return_alias_info && return_alias_info->isWrite(); +} + +static void warnFallback(const c10::FunctionSchema& schema) { + if (!globalContext().areVmapFallbackWarningsEnabled()) { + return; + } + TORCH_WARN("There is a performance drop because we have not yet implemented ", + "the batching rule for ", schema.operator_name(), ". ", + "You are using the legacy vmap prototype (torch._vmap_internals.vmap). ", + "If you are using torch.autograd.functional.{jacobian, hessian} ", + "or torch._vmap_internals.vmap: please switch to using ", + "torch.func.{jacrev, jacfwd, hessian} and/or torch.vmap instead ", + "for better operator coverage and performance improvements ."); +} + +// The general flow of the algorithm is as follows. +// - First, we figure out which arguments are BatchedTensors and save them +// to a vector. We also store a vector of which index of the arguments list +// each BatchedTensor appears in. This will be useful for bookkeeping later. +// - Next, we apply the MultiBatchVmapTransform to all of the BatchedTensors. +// This returns a vector of VmapPhysicalView that hold tensors that contain +// all of the collective batch dimensions at the front of the tensors. +// - Then, we attempt to call `op` once per slice of the inputs. To do this, +// we repeatedly we slice the input arguments (if they are BatchedTensors), +// put the sliced (or a not-sliced) version of the input onto the stack, invoke +// the operator, and then pop the results off the stack. +static void batchedTensorInplaceForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + warnFallback(schema); + + const auto num_arguments = static_cast(schema.arguments().size()); + const auto arguments = torch::jit::last(stack, num_arguments); + const auto arguments_begin = stack->size() - num_arguments; + + // `self` is the Tensor being modified in-place + Tensor self = arguments[0].toTensor(); + const auto* self_impl = maybeGetBatchedImpl(self); + std::bitset self_vmap_levels; + if (self_impl) { + self_vmap_levels = createVmapLevelsBitset(self_impl->bdims()); + } + + // Figure out which arguments are BatchedTensor. Save them to a vector. + // For each BatchedTensor, also record what position of `arguments` they came from. + SmallVector batched_tensor_inputs; + VmapDimVector batched_tensor_inputs_position; + for (const auto idx : c10::irange(arguments.size())) { + const auto& ivalue = arguments[idx]; + if (!ivalue.isTensor()) { + continue; + } + const auto& tensor = ivalue.toTensor(); + if (!tensor.defined()) { + continue; + } + const auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + continue; + } + + // NOTE: [vmap-incompatible in-place operations] + // In-place operations on `self` are not possible if there exists some vmap + // level `l` such that `self` is not being vmapped on that level but another + // argument is. For example, let B0 be a batch dim inside vmap and consider + // vmap(Tensor.add_, in_dims=(None, 0))(torch.ones(3), torch.ones(B0, 3)) + // - self is torch.ones(3) and does not participate in this vmap + // - other is BatchedTensor(torch.ones(B0, 3)) + // There's no way to do self.add_(other) because `other` has more elements + // elements than `self` due to being vmapped over. + // + // In the vmap fallback, we should error out when we detect this. + auto other_vmap_levels = createVmapLevelsBitset(batched->bdims()); + if (self_vmap_levels != (self_vmap_levels | other_vmap_levels)) { + // Find one vmap level to complain about + auto additional_bdims = (self_vmap_levels | other_vmap_levels) ^ self_vmap_levels; + [[maybe_unused]] auto offending_level = llvm::findLastSet(additional_bdims.to_ulong()); + // The following prints out "vmap: aten::add_(tensor, ...) is not possible", + // but it would be better to print out "tensor.add_(...) is not possible". + // Afaict there's no official way to get the add_ and there is no way to + // tell if an operator has method or function variants. + TORCH_CHECK(false, + "vmap: ", schema.name(), "(self, *extra_args) is not possible because ", + "there exists a Tensor `other` in extra_args that has more elements ", + "than `self`. This happened due to `other` being vmapped over but ", + "`self` not being vmapped over at level ", offending_level, ". ", + "Please try to use out-of-place operators instead of ", schema.name(), ". ", + "If said operator is being called inside the PyTorch framework, ", + "please file a bug report instead."); + } + batched_tensor_inputs.push_back(tensor); + batched_tensor_inputs_position.push_back(static_cast(idx)); + } + TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty()); + + // MultiBatchVmapTransform the BatchedTensor arguments. This returns + // VmapPhysicalViews that contain all of the batch dimensions. + const auto input_physical_views = MultiBatchVmapTransform::logicalToPhysical( + batched_tensor_inputs); + + // Compute the total number of batches + auto num_batch_dims = input_physical_views.front().numBatchDims(); + auto first_physical_view_sizes = input_physical_views.front().tensor().sizes(); + auto batch_sizes = ArrayRef( + first_physical_view_sizes.begin(), first_physical_view_sizes.begin() + num_batch_dims); + const auto num_batches = c10::multiply_integers(batch_sizes); + // Without a shape-checking API, we're unable to compute the correct shape of + // the output so we just error out. + TORCH_CHECK(num_batches > 0, + "Batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support vmap over dims of size 0."); + + // Strategy: For each batch, we are going to push slices (where applicable) + // of the arguments onto `stack`, and call `op`. + for (const auto linear_idx : c10::irange(num_batches)) { + auto index = computeIndex(linear_idx, batch_sizes); + auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin(); + auto input_physical_views_iter = input_physical_views.begin(); + for (const auto arg_idx : c10::irange(num_arguments)) { + // We assume that torch::jit::Stack is backed by vector for + // simplicity. When that is not the case, this code should be updated. + const auto& argument = (*stack)[arguments_begin + arg_idx]; + if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end() + || arg_idx != *batched_tensor_inputs_pos_iter) { + // argument isn't a BatchedTensor + torch::jit::push(stack, argument); + continue; + } + // argument is a BatchedTensor + TORCH_INTERNAL_ASSERT(input_physical_views_iter != input_physical_views.end()); + const auto& physical_view_for_argument = *input_physical_views_iter; + torch::jit::push(stack, physical_view_for_argument.tensor().index(index)); + batched_tensor_inputs_pos_iter++; + input_physical_views_iter++; + } + + op.callBoxed(stack); + torch::jit::drop(stack, 1); + } + + // Return the tensor that was written to in-place + torch::jit::drop(stack, num_arguments); + torch::jit::push(stack, self); +} + +static Tensor safeStack(TensorList tensors) { + auto is_defined = [](const Tensor& t) { return t.defined(); }; + if (std::all_of(tensors.begin(), tensors.end(), is_defined)) { + return at::stack(tensors); + } + // NOTE [vmap through backward and undefined grad] + // While vmapping through backward functions (to compute batched grad), it + // is possible for the backward function to return an undefined grad for some + // grad_input for each example. In that case, we return an undefined grad. + // + // It is theoretically possible for *some* of the examples to produce an + // undefined grad (a kernel could peek at the gradient values and return an + // undefined tensor if it determines the gradient is full of zeros). We + // could handle this by treating the undefined grad as a zero-filled tensor + // of the correct shape while stacking the tensors together. However I expect + // this to happen very rarely (I have not been able to find an example in our + // codebase) so we just error out in this case. + if (std::none_of(tensors.begin(), tensors.end(), is_defined)) { + return Tensor(); + } + TORCH_CHECK(false, + "vmap: slow fallback received a mix of undefined and defined tensors ", + "as the result of an operation. This is not supported, please file us ", + "an issue on github."); +} + +// The general flow of the algorithm is as follows. +// - First, we figure out which arguments are BatchedTensors and save them +// to a vector. We also store a vector of which index of the arguments list +// each BatchedTensor appears in. This will be useful for bookkeeping later. +// - Next, we apply the MultiBatchVmapTransform to all of the BatchedTensors. +// This returns a vector of VmapPhysicalView that hold tensors that contain +// all of the collective batch dimensions at the front of the tensors. +// - Then, we attempt to call `op` once per slice of the inputs. To do this, +// we repeatedly we slice the input arguments (if they are BatchedTensors), +// put the sliced (or a not-sliced) version of the input onto the stack, invoke +// the operator, and then pop the results off the stack. +// - Each result obtained from the previous step is a slice of the total result, +// so we stack those tensors together to form the final result. +void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + + if (isInplaceOp(schema)) { + batchedTensorInplaceForLoopFallback(op, stack); + return; + } + TORCH_CHECK(!schema.is_mutable() && !schema.hasAnyAliasInfo(), + "Batching rule not implemented for ", schema.operator_name(), "; ", + "the fallback path doesn't work on out= or view ops."); + TORCH_CHECK(areAllReturnsTensors(schema) && !areAnyArgumentsTensorList(schema), + "Batching rule not implemented for ", schema.operator_name(), ". ", + "We could not generate a fallback."); + TORCH_CHECK(num_returns >= 1, + "Batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support operations with no returns."); + warnFallback(schema); + + const auto num_arguments = static_cast(schema.arguments().size()); + const auto arguments = torch::jit::last(stack, num_arguments); + const auto arguments_begin = stack->size() - num_arguments; + + // Figure out which arguments are BatchedTensor. Save them to a vector. + // For each BatchedTensor, also record what position of `arguments` they came from. + SmallVector batched_tensor_inputs; + VmapDimVector batched_tensor_inputs_position; + for (const auto idx : c10::irange(arguments.size())) { + const auto& ivalue = arguments[idx]; + if (!ivalue.isTensor()) { + continue; + } + const auto& tensor = ivalue.toTensor(); + if (!tensor.defined()) { + continue; + } + const auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + continue; + } + batched_tensor_inputs.push_back(tensor); + batched_tensor_inputs_position.push_back(static_cast(idx)); + } + TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty()); + + // MultiBatchVmapTransform the BatchedTensor arguments. This returns + // VmapPhysicalViews that contain all of the batch dimensions. + const auto input_physical_views = MultiBatchVmapTransform::logicalToPhysical( + batched_tensor_inputs); + + // Compute the total number of batches + auto num_batch_dims = input_physical_views.front().numBatchDims(); + auto some_sizes = input_physical_views.front().tensor().sizes(); + auto batch_sizes = ArrayRef(some_sizes.begin(), some_sizes.begin() + num_batch_dims); + const auto num_batches = c10::multiply_integers(batch_sizes); + // Without a shape-checking API, we're unable to compute the correct shape of + // the output so we just error out. + TORCH_CHECK(num_batches > 0, + "Batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support vmap over dims of size 0."); + + // Strategy: For each batch, we are going to push slices (where applicable) + // of the arguments onto `stack`, call `op`, and store the result in + // `output_shards`. + // + // NOTE: [Output shards layout] + // Assume that the operator has three outputs: a, b, c. + // The layout of output_shards is as follows: + // [ a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3] + // This is so that we can call at::stack([a0...a3]), at::stack([b0...b3]) + // more easily in the next step. + std::vector output_shards(num_batches * num_returns); + + for (const auto linear_idx : c10::irange(num_batches)) { + auto index = computeIndex(linear_idx, batch_sizes); + auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin(); + auto input_physical_views_iter = input_physical_views.begin(); + for (const auto arg_idx : c10::irange(num_arguments)) { + // We assume that torch::jit::Stack is backed by vector for + // simplicity. When that is not the case, this code should be updated. + const auto& argument = (*stack)[arguments_begin + arg_idx]; + if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end() + || arg_idx != *batched_tensor_inputs_pos_iter) { + // argument isn't a BatchedTensor + torch::jit::push(stack, argument); + continue; + } + // argument is a BatchedTensor + TORCH_INTERNAL_ASSERT(input_physical_views_iter != input_physical_views.end()); + const auto& physical_view_for_argument = *input_physical_views_iter; + torch::jit::push(stack, physical_view_for_argument.tensor().index(index)); + batched_tensor_inputs_pos_iter++; + input_physical_views_iter++; + } + + op.callBoxed(stack); + + // Store the result into `output_shards`. See NOTE: [Output shards layout] + // to learn about the details of how we store the shards. + const auto returns = torch::jit::last(stack, num_returns); + for (const auto return_idx : c10::irange(returns.size())) { + output_shards[num_batches * return_idx + linear_idx] = returns[return_idx].toTensor(); + } + torch::jit::drop(stack, num_returns); + } + + // For each output Tensor, stack the shards of the tensor together to form a return + torch::jit::drop(stack, num_arguments); + auto output_shards_chunks = MatrixRef(output_shards, num_batches); + for (const auto return_idx : c10::irange(num_returns)) { + auto shards = output_shards_chunks[return_idx]; + auto flat_output = safeStack(shards); + // See NOTE [vmap through backward and undefined grad] + if (!flat_output.defined()) { + torch::jit::push(stack, flat_output); + continue; + } + VmapDimVector output_sizes(batch_sizes); + output_sizes.insert( + output_sizes.end(), + flat_output.sizes().begin() + 1, + flat_output.sizes().end()); + torch::jit::push( + stack, + input_physical_views.front().getPhysicalToLogicalMap().apply(flat_output.view(output_sizes))); + } +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.h b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.h new file mode 100644 index 0000000000000000000000000000000000000000..7a4a1961a5f57d0aed6a4bd9b07ae2ff7e094d8a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedFallback.h @@ -0,0 +1,25 @@ +#pragma once +#include +#include +#include + +namespace at { + +// If an operator doesn't have a batching rule implemented then we fallback +// to this implementation. The fallback only works on out-of-place operators +// that return only tensors with new memory. (e.g., no in-place operators, no +// view operations). +// +// The fallback effectively takes all of the BatchedTensors in `stack`, slices +// them, and runs `op` on all of the corresponding slices to produce slices +// of the outputs. The output slices then get `torch.stack`ed to create the +// final returns. +// +// The performance of the fallback is not very good because it introduces an +// extra copy from stacking the sliced outputs. Because of this, we prefer to +// write batching rules for operators whenever possible. +void batchedTensorForLoopFallback( + const c10::OperatorHandle& op, + torch::jit::Stack* stack); + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35bb4bf3441b16939e2374be301748ccf961b97b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.cpp @@ -0,0 +1,158 @@ +#include + +#include +#include +#include + +namespace at { + +BatchedTensorImpl::BatchedTensorImpl(Tensor value, BatchDims bdims) + : TensorImpl( + c10::DispatchKeySet(DispatchKey::Batched), + value.dtype(), + value.device() + ) + , value_(std::move(value)) + , bdims_(std::move(bdims)) +{ + TORCH_INTERNAL_ASSERT(value_.defined()); + set_storage_access_should_throw(); + set_custom_sizes_strides(SizesStridesPolicy::CustomStrides); + checkInvariants(); + + const auto public_dims = value_.dim() - bdims_.size(); + const auto value_sizes = value_.sizes(); + const auto value_strides = value_.strides(); + sizes_and_strides_.resize(public_dims); + for (const auto dim : c10::irange(public_dims)) { + auto actual_dim = actualDim(static_cast(dim), /*wrap_dim=*/false); + sizes_and_strides_.size_at_unchecked(dim) = value_sizes.at(actual_dim); + sizes_and_strides_.stride_at_unchecked(dim) = value_strides.at(actual_dim); + } + storage_offset_ = value_.storage_offset(); + refresh_numel(); + refresh_contiguous(); +} + +int64_t BatchedTensorImpl::actualDim(int64_t dim, bool wrap_dim) const { + if (wrap_dim) { + const auto ndim = sizes_and_strides_.size(); + dim = maybe_wrap_dim(dim, static_cast(ndim)); + } + auto is_bdim = createBatchDimBitset(bdims_); + + // Example: assume dim = 3, and is_bdim = 10010011000... + // The 1's are batch dims and 0's are normal dims of the underlying value_ Tensor. + // actualDim gives us the index of `dim` in the `value_` Tensor, which is equivalent + // to asking "where does the 3rd (0-indexed) zero occur in the bitset?". + // The answer to that is index 5. + // + // TODO(rzou): the PDEP instruction does exactly this + // (https://stackoverflow.com/questions/7669057/find-nth-set-bit-in-an-int) + // but it might require newer (>= ~2015) CPUs. We should clean this up + // if/when we have dropped support for older CPUs. + int64_t non_bdim_count = 0; + for (const auto actual_dim : c10::irange(kVmapMaxTensorDims)) { + if (is_bdim[actual_dim]) { + continue; + } + if (non_bdim_count == dim) { + return actual_dim; + } + non_bdim_count++; + } + // If we hit this assert, then that means + // `non_bdim_count` + #num_bdims > kVmapMaxTensorDims. We restrict the number + // of dims a BatchedTensorImpl can have to kVmapMaxTensorDims so this should + // never be hit. + TORCH_INTERNAL_ASSERT(false); +} + +void BatchedTensorImpl::checkInvariants() const { + int64_t prev_level = -1; + for (const auto& bdim : bdims_) { + TORCH_INTERNAL_ASSERT(bdim.level() > prev_level); + prev_level = bdim.level(); + } +} + +// The following are publicly exposed as methods of Tensor + +IntArrayRef BatchedTensorImpl::strides_custom() const { + return strides_default(); +} + +// TODO: implement proper contiguity on batched tensor, then put +// sizes_strides_policy back to Default +c10::SymBool BatchedTensorImpl::sym_is_contiguous_custom(at::MemoryFormat memory_format) const { + TORCH_CHECK(memory_format == MemoryFormat::Contiguous, + "NYI: querying is_contiguous inside of vmap for memory_format ", + "other than torch.contiguous_format"); + return is_contiguous_; +} + +// The following are some internal inherited methods that we do not support. +// They should never get called. +void BatchedTensorImpl::set_size(int64_t dim, int64_t new_size) { + TORCH_INTERNAL_ASSERT(false, "Can't set_size for BatchedTensorImpl"); +} +void BatchedTensorImpl::set_stride(int64_t dim, int64_t new_stride) { + TORCH_INTERNAL_ASSERT(false, "Can't set_stride for BatchedTensorImpl"); +} +void BatchedTensorImpl::set_storage_offset(int64_t storage_offset) { + TORCH_INTERNAL_ASSERT(false, "Can't set_storage_offset for BatchedTensorImpl"); +} +#ifdef DEBUG +bool BatchedTensorImpl::has_storage() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!storage_, "BatchedTensorImpl assumes that storage_ is never set"); + return false; +} +#endif + +const char* BatchedTensorImpl::tensorimpl_type_name() const { + return "BatchedTensorImpl"; +} + +Tensor makeBatched(Tensor tensor, BatchDims bdims) { + TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor)); + auto tensor_dim = tensor.dim(); + TORCH_CHECK( + tensor_dim <= kVmapMaxTensorDims, + "vmap only supports tensors of dimensionality up to ", kVmapMaxTensorDims, + "; got a tensor with dim ", tensor_dim); + TORCH_INTERNAL_ASSERT( + std::all_of(bdims.begin(), bdims.end(), + [](const BatchDim& bdim) { return bdim.level() < kVmapNumLevels; }), + "We only support up to ", kVmapNumLevels, " nested vmaps"); + return at::detail::make_tensor(std::move(tensor), std::move(bdims)); +} + +Tensor addBatchDim(Tensor tensor, int64_t level, int64_t dim) { + const auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + BatchDims bdims; + bdims.emplace_back(level, dim); + return at::detail::make_tensor(std::move(tensor), std::move(bdims)); + } + BatchDims new_bdims(batched->bdims().begin(), batched->bdims().end()); + auto actual_bdim = batched->actualDim(dim, /*wrap_dim=*/true); + new_bdims.emplace_back(level, actual_bdim); + return makeBatched(batched->value(), std::move(new_bdims)); +} + +bool inplaceIsVmapCompatible(const Tensor& self, const Tensor& other) { + const auto* other_batched = maybeGetBatchedImpl(other); + if (!other_batched) { + return true; + } + const auto* self_batched = maybeGetBatchedImpl(self); + if (!self_batched) { + // self is not batched but other is batched + return false; + } + auto self_levels = createVmapLevelsBitset(self_batched->bdims()); + auto other_levels = createVmapLevelsBitset(other_batched->bdims()); + return self_levels == (self_levels | other_levels); +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.h b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..f57e52981dfd33a7da5e295895a7cf3cc6b8ec85 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchedTensorImpl.h @@ -0,0 +1,161 @@ +#pragma once + +#include + +#include +#include +#include + +namespace at { + +// We assume this in a few other places in the codebase, +// but there isn't a centralized definition. +constexpr int64_t kVmapMaxTensorDims = 64; + +// The valid vmap levels range from [0, 64). This effectively means that we +// support a maximum of 64 nested vmaps. +constexpr int64_t kVmapNumLevels = 64; + +// Store this number of elements of BatchDims on the stack. Most people will +// probably use <= 5 nested vmaps, but adjust this number as necessary. +constexpr int64_t kBatchDimsStackSize = 5; + +// a BatchDim represents a "private" dimension on a Tensor created inside of +// vmap. It is a (level, dim) tuple, with the `dim` indicating which dimension +// is being vmap'ed over and the `level` being an identifier for which vmap +// said dimension was created inside. The `dim` corresponds to a "physical +// dim" - it is a dimension index on the underlying physical tensor that is +// being vmapped over. +struct BatchDim { + BatchDim(int64_t level, int64_t dim) : dim_(dim), level_(level) {} + int64_t dim() const { + return dim_; + } + int64_t level() const { + return level_; + } + + private: + int64_t dim_; + int64_t level_; +}; + +using BatchDims = SmallVector; +using BatchDimsRef = ArrayRef; + +// A BatchedTensorImpl holds an underlying Tensor and a list of BatchDim +// NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a +// BatchedTensorImpl. +// +// The batch dimensions are treated as being "private"; they are not +// user-visible. For example, in the following Tensor, +// bt = BatchedTensorImpl(ones(2, 3, 5, 7), [(lvl=1, dim=0), (lvl=2, dim=1)]) +// dimensions 0 and 1 are batch dimensions. +// +// bt.sizes() returns (5, 7); bt.sum(0) performs a reduction over the (public) +// dim 0, which is equivalent to dim 3 in the underlying ones(2, 3, 5, 7) +// tensor. +struct TORCH_API BatchedTensorImpl : public c10::TensorImpl { + explicit BatchedTensorImpl(Tensor value, BatchDims bdims); + + // Returns a reference to BatchDims that represent which dimensions of this + // tensor are private. + BatchDimsRef bdims() const { + return bdims_; + } + + // BatchedTensorImpl wraps a Tensor + const Tensor& value() const { + return value_; + } + + // Given a public dimension index, return the dimension index in the + // underlying value() tensor. For example, if we have + // bt = BatchedTensorImpl(ones(2, 3, 5, 7), [(lvl=1, dim=0), (lvl=2, + // dim=2)]) + // bt.actualDim(0) -> 1 + // bt.actualDim(1) -> 3 + // bt.actualDim(2) -> Error + int64_t actualDim(int64_t dim, bool wrap_dim = true) const; + + // We have to override this because we opted into CustomStrides + IntArrayRef strides_custom() const override; + // Override a bunch of methods inherited from TensorImpl to return error + // messages. + c10::SymBool sym_is_contiguous_custom( + at::MemoryFormat memory_format) const override; + void set_size(int64_t dim, int64_t new_size) override; + void set_stride(int64_t dim, int64_t new_stride) override; + void set_storage_offset(int64_t storage_offset) override; +#ifdef DEBUG + bool has_storage() const override; +#endif + + private: + // see NOTE: [BatchedTensorImpl levels invariant] + void checkInvariants() const; + const char* tensorimpl_type_name() const override; + + Tensor value_; + + // Note: [BatchedTensorImpl levels invariant] + // There is an invariant that the BatchDims must be stored in increasing + // `level` order. That is, for i < j, bdims_[i].level must be less than + // bdims_[j].level. + BatchDims bdims_; +}; + +// NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a +// BatchedTensorImpl. +inline bool isBatchedTensor(const Tensor& tensor) { + return tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::Batched); +} + +// It is unsafe to call this on a Tensor that is not backed by a +// BatchedTensorImpl. Please use `maybeGetBatchedImpl` whenever possible. +inline BatchedTensorImpl* unsafeGetBatchedImpl(const Tensor& tensor) { + return static_cast(tensor.unsafeGetTensorImpl()); +} + +inline BatchedTensorImpl* maybeGetBatchedImpl(const Tensor& tensor) { + if (!isBatchedTensor(tensor)) { + return nullptr; + } + return unsafeGetBatchedImpl(tensor); +} + +// Returns a bitset. If bit i is set, then that means dim i is a batchdim. +inline std::bitset createBatchDimBitset( + BatchDimsRef bdims) { + std::bitset is_bdim; + for (const auto& bdim : bdims) { + is_bdim.set(bdim.dim()); + } + return is_bdim; +} + +// Creates a bitset for all of the levels present in `bdims` +inline std::bitset createVmapLevelsBitset(BatchDimsRef bdims) { + std::bitset result; + for (const auto& bdim : bdims) { + result.set(bdim.level()); + } + return result; +} + +inline std::ostream& operator<<(std::ostream& out, const BatchDim& bdim) { + out << "(lvl=" << bdim.level() << ", dim=" << bdim.dim() << ')'; + return out; +} + +// Use this to construct a BatchedTensor from a regular Tensor +TORCH_API Tensor makeBatched(Tensor tensor, BatchDims bdims); + +// Adds a batch dim to `tensor`, returning a BatchedTensor +TORCH_API Tensor addBatchDim(Tensor tensor, int64_t level, int64_t dim); + +// Checks if an inplace operation on self and other is "vmap compatible". +// See NOTE: [vmap-incompatible in-place operations] for the definition of this. +TORCH_API bool inplaceIsVmapCompatible(const Tensor& self, const Tensor& other); + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchingRegistrations.cpp b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchingRegistrations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7660b1f39f1f0b1163a1a430f66ffc4ce5174db3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyBatchingRegistrations.cpp @@ -0,0 +1,1291 @@ +#include +#include +#include +#include +#include +#include + +#include + +namespace at { + +// NOTE: [What is a batching rule?] +// +// A *batching rule* implements the logic of how to call an operator on inputs +// that have zero or more additional batch dimensions. When one does a vmap, the +// dimension(s) being vmap'ed over get recorded as batch dimensions. +// +// For example, vmap(torch.add)(x, y) +// 1. wraps `x` into batched_x = BatchedTensor(x, bdims=[(lvl=1, dim=0)]; +// 2. wraps `y` into batched_y = BatchedTensor(y, bdims=[(lvl=1, dim=0)]; +// 3. and then runs `torch.add(batched_x, batched_y)`. + +// NOTE: [When should I add a batching rule?] +// When you are adding a new operator, you'll need to add a batching rule so +// that vmap can work efficiently with said operator. If you do not, we'll attempt +// to generate a slow fallback for the batching rule. + +// NOTE: [How to write batching rules?] +// The signature of a batching rule should look like exactly like the C++ signature +// of its operator. +// +// First, see NOTE: [Logical vs physical args] in VmapTransforms.h for terminology. +// +// At a high level, what a batching rule does is the following: +// 1. Converts (logical) BatchedTensors to views on physical tensors. +// 2. Converts logical arguments (e.g. dimension indexes, shapes) to physical +// arguments that correspond to the physical tensors. +// 3. Calls at:: operations on the physical tensors and arguments to produce +// some physical results. +// 4. Converts physical results back to BatchedTensors. +// +// Steps 1, 2, and 4 differ for operators with different batching behaviors. When +// writing a new batching rule, please select a VmapTransform that matches the +// batching behavior of your operation. The VmapTransform provides helper functions +// to do steps (1), (2), and (4). +// (see NOTE: [What is an VmapTransform?] in VmapTransforms.h) + +// Note: [Future plans] +// The API for writing a batching rule isn't stable. In the future, we'd like +// to think about the problem of translating these batching rules to TorchScript. +// Ideally batching rules in eager mode vs TorchScript would look pretty similar, +// if not use the same mechanism. In order to accomplish that we might have to +// do some refactoring. + +namespace{ + +// PyTorch allows operations to specify dim 0 and dim -1 on a scalar tensor. +bool is_allowed_dim_on_scalar_tensor(int64_t dim) { + return dim == 0 || dim == -1; +} + +Tensor sum_batching_rule(const Tensor& self, OptionalIntArrayRef opt_dims, bool keepdim, std::optional dtype) { + if (opt_dims.has_value()) { + auto dims = opt_dims.value(); + // PyTorch has a special case where sum(scalar_tensor, dim=0) does not fail + // and instead returns a new scalar tensor (this also happens for dim=-1) + // If the following happens: + // >>> x = torch.randn(B0) # the per-examples are all scalars + // >>> vmap(partial(torch.sum, dim=0), x) + // then we replicate the behavior of sum(scalar_tensor, dim=0). + if (/*logical*/self.dim() == 0 && (dims.empty() || (dims.size() == 1 && is_allowed_dim_on_scalar_tensor(dims[0])))) { + return self.clone(); + } + } + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dims_physical = self_physical.getPhysicalDims(opt_dims); + auto result = at::sum(self_physical.tensor(), dims_physical, keepdim, dtype); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +bool isPhysicalScalarTensor(const Tensor& logical_tensor) { + if (logical_tensor.dim() > 0) { + return false; + } + auto* batched = maybeGetBatchedImpl(logical_tensor); + if (batched) { + return false; + } + return true; +} + +template +Tensor binary_pointwise_batching_rule( + const Tensor& self, const Tensor& other, ExtraArgs... args) { + if (self.dim() > 0 && other.dim() > 0) { + auto physical_args = BroadcastingVmapTransform::logicalToPhysical({self, other}); + auto result = Func(physical_args[0].tensor(), physical_args[1].tensor(), args...); + return physical_args[0].getPhysicalToLogicalMap().apply(result); + } + if (isPhysicalScalarTensor(self)) { + auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other); + auto result = Func(self, other_physical.tensor(), args...); + return other_physical.getPhysicalToLogicalMap().apply(result); + } + if (isPhysicalScalarTensor(other)) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = Func(self_physical.tensor(), other, args...); + return self_physical.getPhysicalToLogicalMap().apply(result); + } + + // At this point, we know at least one of the operands is a logical Scalar tensor. + // Here we must emulate TensorIterator's special behavior on Scalars. + // + // As a motivating example, consider the following: + // x = torch.randn(3, 10) + // y = torch.randn(3, dtype=torch.double) + // vmap(torch.mul)(torch.randn(3, 10), torch.randn(3, dtype=torch.double)) + // + // At a per-example level, we are adding FloatTensor[10] and DoubleTensor[]; + // Type Promotion dictates that the result should be FloatTensor[10]. + // This means we cannot directly pass the physical tensors (x and y) to + // TensorIterator (if we did, it would promote them to DoubleTensor). + // + // FIXME(rzou): I didn't want to go down the slippery slope of emulating + // everything TensorIterator does (it would be better to refactor out the + // TensorIterator logic). The one thing that this code doesn't handle + // is cross-device logical scalar tensors. + // cpu_tensor = torch.randn(3) + // cuda_tensor = torch.randn(3, 10, device='cuda') + // vmap(torch.mul)(cpu_tensor, cuda_tensor) + // + // At a per-example level, we are adding CPUTensor[] and CUDATensor[10]. + // TensorIterator allows for this cross-device operation because one of the + // tensors is a Scalar CPU tensor. However, the following code will throw an + // error in that case. I don't expect to see many use cases for this, so + // this is probably fine as-is. + auto logical_self = self; + auto logical_other = other; + auto result_type = at::native::result_type(logical_self, logical_other); + if (logical_self.scalar_type() != result_type) { + logical_self = logical_self.to(result_type); + } + if (logical_other.scalar_type() != result_type) { + logical_other = logical_other.to(result_type); + } + auto physical_args = BroadcastingVmapTransform::logicalToPhysical( + {std::move(logical_self), std::move(logical_other)}); + auto result = Func(physical_args[0].tensor(), physical_args[1].tensor(), args...); + return physical_args[0].getPhysicalToLogicalMap().apply(result); +} + +Tensor expand_batching_rule(const Tensor& self, IntArrayRef size, bool implicit) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto size_physical = self_physical.getPhysicalShape(size); + auto self_physical_dim = self_physical.tensor().dim(); + + TORCH_CHECK(self_physical_dim <= static_cast(size_physical.size()), + "expand: the number of sizes provided (", /*logical*/size.size(), ") ", + "must be greater or equal to the number of dimensions in the tensor (", + /*logical dim*/self.dim(), ")"); + + if (self_physical_dim == static_cast(size_physical.size())) { + auto result = self_physical.tensor().expand(size_physical, implicit); + return self_physical.getPhysicalToLogicalMap().apply(result); + } + + TORCH_INTERNAL_ASSERT(self_physical_dim < static_cast(size_physical.size())); + // Here, we know we are expanding a (logical) tensor to a larger number + // of dimensions. We have to be careful because we can't call expand directly + // due to the presence of batch dimensions. + // + // As an example, let B0 be a batch dimension and consider expand(Tensor[B0, 3], [2, 3]). + // The result should be a tensor of size [B0, 2, 3]. + // A physical view of size [B0, 3] can't directly be expanded to size [B0, 2, 3] + // so the strategy here is to view it first as a tensor of size [B0, 1, 3] and + // then expand. + auto self_physical_size = self_physical.tensor().sizes(); + auto extra_dims = size_physical.size() - self_physical_dim; + VmapDimVector view_shape(size_physical.size(), 1); + std::copy(self_physical_size.begin(), + self_physical_size.begin() + self_physical.numBatchDims(), + view_shape.begin()); + std::copy(self_physical_size.begin() + self_physical.numBatchDims(), + self_physical_size.end(), + view_shape.begin() + self_physical.numBatchDims() + extra_dims); + auto result = self_physical.tensor().view(view_shape).expand(size_physical, implicit); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +std::vector chunk_batching_rule(const Tensor& self, int64_t chunks, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::chunk(self_physical.tensor(), chunks, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +Tensor clamp_batching_rule(const Tensor& self, const std::optional& min, const std::optional& max) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::clamp(self_physical.tensor(), min, max); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor clamp_min_batching_rule(const Tensor& self, const Scalar& min) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::clamp_min(self_physical.tensor(), min); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor clamp_max_batching_rule(const Tensor& self, const Scalar& max) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::clamp_max(self_physical.tensor(), max); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +std::vector tensor_split_sections_batching_rule(const Tensor& self, int64_t sections, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::tensor_split(self_physical.tensor(), sections, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +std::vector tensor_split_indices_batching_rule(const Tensor& self, IntArrayRef indices, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::tensor_split(self_physical.tensor(), indices, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +Tensor unsqueeze_batching_rule(const Tensor& self, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + // NB: unsqueeze has some special handling of its `dim` argument so we can't call + // self_physical.getPhysicalDim directly. In particular, native::unsqueeze + // wraps the dim to (the logical dimension) + 1, so we need to do that here too. + // https://github.com/pytorch/pytorch/blob/b623bdeabb0aa8da44285d303246e7f8ac06c2a9/aten/src/ATen/native/TensorShape.cpp#L1413 + auto dim_physical = + self_physical.numBatchDims() + maybe_wrap_dim(dim, /*logical_dim*/self.dim() + 1); + auto result = self_physical.tensor().unsqueeze(dim_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor& fill_inplace_scalar_batching_rule(Tensor& self, const Scalar& value) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + self_physical.tensor().fill_(value); + return self; +} + +Tensor& fill_inplace_tensor_batching_rule(Tensor& self, const Tensor& value) { + auto value_batched = isBatchedTensor(value); + + if (value_batched) { + auto physical_args = + BroadcastingVmapTransform::logicalToPhysical({self, value}); + physical_args[0].tensor().copy_(physical_args[1].tensor()); + } else { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + self_physical.tensor().fill_(value); + } + return self; +} + +Tensor& zero_inplace_batching_rule(Tensor &self) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + self_physical.tensor().zero_(); + return self; +} + +Tensor squeeze_batching_rule(const Tensor& self) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto physical_sizes = self_physical.tensor().sizes(); + + // Don't squeeze the batch dims! + VmapDimVector squeezed_sizes; + int64_t num_batch_dims = self_physical.numBatchDims(); + squeezed_sizes.insert( + squeezed_sizes.end(), + physical_sizes.begin(), + physical_sizes.begin() + num_batch_dims); + for (auto it = physical_sizes.begin() + num_batch_dims; it != physical_sizes.end(); ++it) { + if (*it != 1) { + squeezed_sizes.push_back(*it); + } + } + + auto result = self_physical.tensor().view(squeezed_sizes); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor squeeze_dim_batching_rule(const Tensor& self, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = self_physical.tensor().squeeze(dim_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor squeeze_dims_batching_rule(const Tensor& self, IntArrayRef dims) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dims_physical = self_physical.getPhysicalDims(dims); + auto result = self_physical.tensor().squeeze(dims_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor trace_batching_rule(const Tensor& self) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + // Batched Diagonal View + auto self_diag = at::diagonal(self_physical.tensor(), /*offset*/0, /*dim1*/-2, /*dim2*/-1); + auto result = at::sum(self_diag, -1); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor trace_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes) { + auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad); + auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options()); + // Batched Diagonal View + auto grad_input_diag = at::diagonal(grad_input, /*offset*/0, /*dim1*/-2, /*dim2*/-1); + // Append a dimension of size one to the grad output + auto grad_physical_tensor = grad_physical.tensor().unsqueeze(-1); + grad_input_diag.copy_(grad_physical_tensor); + return grad_physical.getPhysicalToLogicalMap().apply(grad_input); +} + +Tensor transpose_int_batching_rule(const Tensor& self, int64_t dim0, int64_t dim1) { + // PyTorch has a special case where scalar_tensor.transpose(dim0, dim1) works + // for dim0, dim1 in {0, -1} and returns the scalar tensor. If the following happens: + // >>> x = torch.randn(B0) # the per-examples are all scalars + // >>> vmap(lambda x: x.transpose(0, -1), x) + // then we replicate this behavior. + if (/*logical*/self.dim() == 0 && is_allowed_dim_on_scalar_tensor(dim0) && + is_allowed_dim_on_scalar_tensor(dim1)) { + return self; + } + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim0_physical = self_physical.getPhysicalDim(dim0); + auto dim1_physical = self_physical.getPhysicalDim(dim1); + auto result = self_physical.tensor().transpose(dim0_physical, dim1_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor permute_batching_rule(const Tensor& self, IntArrayRef dims) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dims_physical = self_physical.getPhysicalDims(dims); + + VmapDimVector all_dims_physical; + all_dims_physical.reserve(self_physical.tensor().dim()); + for (const auto bdim : c10::irange(self_physical.numBatchDims())) { + all_dims_physical.push_back(bdim); + } + all_dims_physical.insert( + all_dims_physical.end(), + dims_physical.begin(), + dims_physical.end()); + auto result = self_physical.tensor().permute(all_dims_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor select_batching_rule(const Tensor& self, int64_t dim, int64_t index) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = self_physical.tensor().select(dim_physical, index); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +int64_t getGradInputPhysicalDim(int64_t dim, IntArrayRef input_sizes, int64_t num_batch_dims) { + return maybe_wrap_dim(dim, static_cast(input_sizes.size())) + num_batch_dims; +} + +Tensor select_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes, int64_t dim, int64_t index) { + auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad); + auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options()); + auto physical_dim = getGradInputPhysicalDim(dim, input_sizes, grad_physical.numBatchDims()); + grad_input.select(physical_dim, index).copy_(grad_physical.tensor()); + return grad_physical.getPhysicalToLogicalMap().apply(grad_input); +} + +Tensor slice_batching_rule( + const Tensor& self, + int64_t dim, + std::optional start, + std::optional end, + int64_t step) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = self_physical.tensor().slice(dim_physical, start, end, step); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor slice_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes, int64_t dim, int64_t start, int64_t end, int64_t step) { + auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad); + auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options()); + auto physical_dim = getGradInputPhysicalDim(dim, input_sizes, grad_physical.numBatchDims()); + grad_input.slice(physical_dim, start, end, step).copy_(grad_physical.tensor()); + return grad_physical.getPhysicalToLogicalMap().apply(grad_input); +} + +Tensor diagonal_batching_rule(const Tensor& self, int64_t offset, int64_t dim1, int64_t dim2) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim1_physical = self_physical.getPhysicalDim(dim1); + auto dim2_physical = self_physical.getPhysicalDim(dim2); + auto result = at::diagonal(self_physical.tensor(), offset, dim1_physical, dim2_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor diagonal_backward_batching_rule(const Tensor& grad, IntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2) { + auto grad_physical = MultiBatchVmapTransform::logicalToPhysical(grad); + auto grad_input = at::zeros(grad_physical.getPhysicalShape(input_sizes), grad.options()); + auto dim1_physical = getGradInputPhysicalDim(dim1, input_sizes, grad_physical.numBatchDims()); + auto dim2_physical = getGradInputPhysicalDim(dim2, input_sizes, grad_physical.numBatchDims()); + grad_input.diagonal(offset, dim1_physical, dim2_physical).copy_(grad_physical.tensor()); + return grad_physical.getPhysicalToLogicalMap().apply(grad_input); +} + +Tensor movedim_batching_rule(const Tensor& self, IntArrayRef source, IntArrayRef destination) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto source_physical = self_physical.getPhysicalDims(source); + auto destination_physical = self_physical.getPhysicalDims(destination); + auto result = at::movedim(self_physical.tensor(), source_physical, destination_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor reshape_batching_rule(const Tensor& self, IntArrayRef shape) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto shape_physical = self_physical.getPhysicalShape(shape); + auto result = self_physical.tensor().reshape(shape_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +std::vector split_batching_rule(const Tensor& self, int64_t split_size, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::split(self_physical.tensor(), split_size, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +std::vector split_with_sizes_batching_rule(const Tensor& self, IntArrayRef split_sizes, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::split_with_sizes(self_physical.tensor(), split_sizes, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +std::vector unbind_batching_rule(const Tensor& self, int64_t dim) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::unbind(self_physical.tensor(), dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +Tensor unfold_batching_rule(const Tensor& self, int64_t dim, int64_t size, int64_t step) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = self_physical.tensor().unfold(dim_physical, size, step); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor contiguous_batching_rule(const Tensor& self, MemoryFormat memory_format) { + TORCH_CHECK(memory_format == MemoryFormat::Contiguous, + "NYI: Tensor.contiguous(...) inside of vmap for memory_format other ", + "than torch.contiguous_format"); + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = physical_view.tensor().contiguous(memory_format); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +Tensor view_batching_rule(const Tensor& self, IntArrayRef size) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto size_physical = self_physical.getPhysicalShape(size); + auto result = self_physical.tensor().view(size_physical); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +Tensor view_as_complex_batching_rule(const Tensor& self) { + // guard against the user passing in a batch of scalar tensors with batch + // size equal to 2. + TORCH_CHECK(!self.sizes().empty(), "Input tensor must have one or more dimensions"); + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::view_as_complex(self_physical.tensor()); + return self_physical.getPhysicalToLogicalMap().apply(result); +} + +// Checks that the smallest batch stride is greater than the largest example +// stride. This is something we can support but we choose not to because it's +// potentially error prone. +void checkBatchDimsAtFrontInLayout(IntArrayRef physical_strides, int64_t num_batch_dims) { + auto smallest_batch_stride = std::min_element( + physical_strides.begin(), physical_strides.begin() + num_batch_dims); + auto largest_example_stride = std::max_element( + physical_strides.begin() + num_batch_dims, physical_strides.end()); + if (largest_example_stride == physical_strides.end()) { + // No example dimensions + return; + } + TORCH_CHECK(*smallest_batch_stride >= *largest_example_stride, + "vmap: Calling Tensor.as_strided is not supported unless the batch dims being ", + "vmapped over are at the front of the tensor (in memory layout). When they are ", + "not at the front of the tensor this operation can be error prone so we " + "actively discourage it; please file us a bug report and/or try to ", + "express the as_strided operation in terms of PyTorch view operations"); +} + +// given (sizes, strides, storage_offset) returns the maximum location that +// can be indexed (or nullopt if such a location doesn't exist, e.g., tensors +// with zero-size dims). +std::optional maximum_indexable_location( + IntArrayRef sizes, IntArrayRef strides, int64_t storage_offset) { + auto result = native::storage_size_for(sizes, strides); + if (result == 0) { + return std::nullopt; + } + return result + storage_offset; +} + +// Let x be the "first slice" of physical_tensor. +// This checks that the range of possible memory locations accessible by +// x.as_strided(sizes, strides, maybe_storage_offset) +// are within the bounds of possible memory locations accessible by x. +void checkBasicAsStridedValidForSlice( + const Tensor& physical_tensor, + int64_t num_batch_dims, + IntArrayRef sizes, + IntArrayRef strides, + std::optional maybe_storage_offset) { + auto slice_sizes = physical_tensor.sizes().slice(num_batch_dims); + auto slice_strides = physical_tensor.strides().slice(num_batch_dims); + auto base_offset = physical_tensor.storage_offset(); + + auto storage_offset = maybe_storage_offset.value_or(base_offset); + + auto max_as_strided_loc = maximum_indexable_location(sizes, strides, storage_offset); + auto max_slice_loc = maximum_indexable_location(slice_sizes, slice_strides, base_offset); + + if (!max_as_strided_loc.has_value()) { + return; + } + if (!max_slice_loc.has_value()) { + TORCH_CHECK(false, + "result = tensor.as_strided(", sizes, ",", strides, ",", storage_offset, ")", + "can access memory outside of `tensor`. `tensor` has no storage but the ", + "passed-in (size, stride, storage_offset) imply a result with some storage. ", + "This is not supported inside of vmap, please try to rewrite the ", + "`as_strided` call as a sequence of PyTorch view operations"); + } + + TORCH_CHECK( + *max_as_strided_loc <= *max_slice_loc && base_offset <= storage_offset, + "result = tensor.as_strided(", sizes, ",", strides, ",", storage_offset, ")", + "can access memory outside of `tensor`. `result` can access some", + "memory in range [", storage_offset, ", ", *max_as_strided_loc, "], but ", + "`tensor` can only access some memory in range [", base_offset, ", ", + *max_slice_loc, "]. This is not supported inside of vmap, please try to", + "rewrite the `as_strided` call as a sequence of PyTorch view operations"); +} + +Tensor _reshape_alias_batching_rule(const Tensor& self, IntArrayRef sizes, IntArrayRef strides [[maybe_unused]]) { + return reshape_batching_rule(self, sizes); +} + +Tensor _new_zeros_with_same_feature_meta_batching_rule( + const Tensor& self, + const Tensor& other, + int64_t unused_num_batch_dims) { + TORCH_CHECK(isBatchedTensor(self) && !isBatchedTensor(other), + "Only the 'batched grad' use case is supported in PyTorch core."); + + TORCH_INTERNAL_ASSERT(unused_num_batch_dims == 0, + "num_batch_dims should not be explicitly passed in because it will be overridden"); + auto self_physical_view = at::MultiBatchVmapTransform::logicalToPhysical(self); + const auto& self_physical_tensor = self_physical_view.tensor(); + int64_t num_batch_dims = self_physical_view.numBatchDims(); + checkBatchDimsAtFrontInLayout(self_physical_tensor.strides(), num_batch_dims); + auto result = at::_new_zeros_with_same_feature_meta(self_physical_tensor, other, num_batch_dims); + return self_physical_view.getPhysicalToLogicalMap().apply(result); +} + +bool _has_same_storage_numel_batching_rule(const Tensor& self, const Tensor& other) { + TORCH_CHECK(isBatchedTensor(self) && !isBatchedTensor(other), + "Only the 'batched grad' use case is supported in PyTorch core."); + // The _has_same_storage_numel check is skipped if the tangent is a batched + // tensor because using as_strided to access storage locations not indexable + // by the input tensor is not supported in vmap + return true; +} + +// What are the semantics of as_strided inside of vmap? +// y = vmap(lambda x: x.as_strided(sizes, strides, offset))(xs) +// This returns a view on `x`, `y`, such that each y[i] has: +// - sizes: `sizes` +// - strides: `strides` +// - storage_offset: offset + i * x.stride(batch_dim) +// +// In other words, it is as if we had treated each x[i] as having storage +// offset equal to xs.offset() and called as_strided(sizes, sizes, offset). +// (that is equivalent to x[i].as_strided( +// sizes, sizes, offset + x[i].storage_offset() - xs.offset()) for all i) +// +// Note that this *may* be different from actually running as_strided +// in a for-loop. This is due to how as_strided takes in `offset` to be +// an *absolute* offset. As an example, consider: +// >>> x = torch.tensor([0., 1., 2., 3., 4.]).as_strided([4], [1], 1) +// >>> z = [x[i].as_strided([1], [1], 1) for i in range(4)] +// Each z[i] is actually the same view on x (z[i] == torch.tensor([1.]))! +// However, we consider the above for-loop comprehension to be a user error: +// a user should have written the following if they wanted to use as_strided +// in a per-sample way: +// >>> z = [x[i].as_strided([1], [1], 1 + x[i].storage_offset() - 1) for i in range(4)] +Tensor as_strided_batching_rule( + const Tensor& tensor, + IntArrayRef sizes, + IntArrayRef strides, + std::optional storage_offset) { + auto physical_view = at::MultiBatchVmapTransform::logicalToPhysical(tensor); + auto num_batch_dims = physical_view.numBatchDims(); + auto physical_sizes = physical_view.getPhysicalShape(sizes); + const auto& physical_tensor = physical_view.tensor(); + + // We can't rely on the physical as_strided call to do this for us because + // we do some sanity checks on the size/strides before calling into as_strided. + TORCH_CHECK(sizes.size() == strides.size(), + "Tensor.as_strided(size, stride, ...): size and stride must have the ", + "same length! Got size ", sizes, " and stride ", strides); + + // Sanity checks: + // 1. All batch dims are at the front in memory layout (not necessary for + // correctness, but we are worried the user might be doing crazy things) + // 2. as_strided(sizes, strides, storage_offset + tensor[i].offset() - tensor.offset()) + // is valid for a slice of the input tensor. + // See Note: [When will the as_strided batching rule fail?] for details. + checkBatchDimsAtFrontInLayout(physical_tensor.strides(), num_batch_dims); + checkBasicAsStridedValidForSlice( + physical_tensor, num_batch_dims, sizes, strides, storage_offset); + + // physical_strides = physical tensor's batch strides + (logical) strides + auto batch_strides = physical_tensor.strides().slice(0, num_batch_dims); + at::VmapDimVector physical_strides; + physical_strides.reserve(num_batch_dims + strides.size()); + physical_strides.insert( + physical_strides.end(), batch_strides.begin(), batch_strides.end()); + physical_strides.insert( + physical_strides.end(), strides.begin(), strides.end()); + + // If zi = xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) + // is valid for all i, then it turns out that + // xs.as_strided(physical_sizes, physical_strides, offset) always succeeds + // and creates a tensor y such that each y[i] references the same memory + // locations as zi. See NOTE: [When will the as_strided batching rule fail?] + auto result = physical_view.tensor().as_strided( + physical_sizes, physical_strides, storage_offset); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +// NOTE: [When will the as_strided batching rule fail?] +// If zi = xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) +// is valid for all i, then it turns out that +// xs.as_strided(physical_sizes, physical_strides, offset) always succeeds and +// creates a tensor y such that each y[i] refers to the same memory as zi. +// +// Let's say we have xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()). +// Furthermore, let's say that as a part of being "valid" this as_strided call +// does not return a result that can index memory not indexable by xs[i]. +// +// WLOG, assume that there's only one batch dim and it is at the front of the +// `xs` tensor. Let B be the batch size and S be the stride of the batch dim. +// - If the batch dim isn't at the front of the tensor, then we can just move it +// to the front with movedim/permute. This is always valid because it just swaps +// some strides around. +// - This proof also works for tensors with multiple batch dims. We just have to +// do a little accounting: +// - instead of [B], we'd have [B0, B1, ..., Bk]. +// - instead of [S], we'd have [S0, S1, ..., Sk]. +// - instead of i, we'd have a list of indices [I0, I1, ..., Ik] +// - instead of S * I, we'd have \sum_{i=0}^k S_i * I_i +// +// [Equation 1] +// xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) has: +// - sizes: sizes +// - strides: strides +// - offset: offset + S * i +// +// x.as_strided itself checks that: +// - (sizes, strides, offset) are in bounds for `x`'s storage. +// - strides are positive +// - offset is positive +// +// Claim 1: if xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) +// is valid, then +// ([B] + sizes, [S] + strides, offset + xs.offset()) are in bounds for `xs`'s storage. +// +// If we have the claim, then xs.as_strided([B] + sizes, [S] + strides, offset) +// won't error out. So all we need to check is that the memory locations are +// what we expected. See [Hand-wavy proof of Claim 1] for proof (it's not very important) +// +// xs.as_strided(physical_sizes, physical_strides, offset) is equivalent to +// xs.as_strided([B] + sizes, [S] + strides, offset) +// +// xs.as_strided([B] + sizes, [S] + strides, offset) has: +// - sizes: [B] + sizes +// - strides: [S] + strides +// - offset: offset +// +// xs.as_strided([B] + sizes, [S] + strides, offset)[i] has: +// - sizes: sizes +// - strides: strides +// - offset: offset + S * i +// These memory locations are exactly the same as what we got for [Equation 1], +// so the xs.as_strided([B] + sizes, [S] + strides, offset) is valid. +// +// [Hand-wavy proof of Claim 1] +// Part of our definition of being valid is that xs[i].as_strided(...) +// must return a tensor that only uses memory indexable by xs[i]. +// This means that (sizes, strides, offset + xs[i].offset() - xs.offset()) satisfies: +// offset + xs[i].offset() - xs.offset() + 1 + \sum_j (sizes[j] - 1) * strides[j] +// <= xs[i].offset() + 1 + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j) +// (the largest-index memory location of xs[i].as_strided(...) must be \leq +// the largest-index memory location of xs[i]) +// +// Fiddling that inequality gives us: +// offset - xs.offset() + 1 + \sum_j (sizes[j] - 1) * strides[j] +// <= 1 + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j) +// +// offset - xs.offset() + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j] +// <= 1 + (B-1)*S + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j) +// +// offset - xs.offset() + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j] +// <= 1 + \sum_j (xs.size(j) - 1) * xs.stride(j) +// +// offset + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j] +// <= xs.offset() + 1 + \sum_j (xs.size(j) - 1) * xs.stride(j) +// (the largest-index memory location of xs.as_strided(size, stride, offset) +// is \leq than the largest-index memory location of xs) +// Under the assumptions we've made, the lower bound (lowest indexed memory) +// is trivially within the storage. +// +// Therefore ([B] + sizes, [S] + strides, offset) are in bounds for +// `xs`'s storage. + +template +Tensor unwrap_and_call(const Tensor& input, ExtraArgs... args) { + auto* input_batched = unsafeGetBatchedImpl(input); + auto output_physical = Func(input_batched->value(), args...); + auto old_bdims = input_batched->bdims(); + return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end())); +} + +template +Tensor unwrap_and_call_method(const Tensor& input, ExtraArgs... extra_args) { + auto* input_batched = unsafeGetBatchedImpl(input); + auto output_physical = (input_batched->value().*Func)(extra_args...); + auto old_bdims = input_batched->bdims(); + return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end())); +} + +Tensor pow_scalar_Tensor_batching_rule(const Scalar& other, const Tensor& self) { + auto* self_batched = unsafeGetBatchedImpl(self); + auto output_physical = at::pow(other, self_batched->value()); + auto old_bdims = self_batched->bdims(); + return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end())); +} + +Tensor clone_batching_rule(const Tensor& self, std::optional memory_format) { + // Memory format support is a little tricky because vmap is allowed to move + // around batch dimensions and some memory formats are rank-dependent. + // Another weird case is: + // - a tensor with MemoryFormat::ChannelsLast MUST have 4 dimensions. Do we + // allow the user to clone a Tensor with 3 logical dimensions and 1 batch + // dim into a ChannelsLast Tensor? What about a Tensor with 3 logical dims + // and N>1 batch dims? + TORCH_CHECK(!memory_format.has_value() || memory_format == MemoryFormat::Preserve + || memory_format == MemoryFormat::Contiguous, + "NYI: Tensor.clone(memory_format) inside vmap is only supported with ", + "memory_format torch.preserve_format or torch.contiguous_format (got ", + *memory_format, ")"); + + if (memory_format == MemoryFormat::Contiguous) { + // There is an ambiguity here when the batch dims are not at the front of + // the tensor. + // >>> x = torch.randn(3, B0, 5) + // >>> y = vmap(lambda x: x.clone(torch.contiguous_format), in_dims=1, out_dims=0)(x) + // >>> y[0].is_contiguous() + // ??? + // Should we make the whole tensor contiguous, or should we + // make the non-batch dims contiguous? We've chosen the latter because + // philosophically vmap hides the batch dims and operates on a per-sample level. + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self); + auto output_physical = at::clone(physical_view.tensor(), memory_format); + return physical_view.getPhysicalToLogicalMap().apply(output_physical); + } + + TORCH_INTERNAL_ASSERT(!memory_format.has_value() || memory_format == MemoryFormat::Preserve); + auto* self_batched = unsafeGetBatchedImpl(self); + auto output_physical = at::clone(self_batched->value(), memory_format); + auto old_bdims = self_batched->bdims(); + return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end())); +} + +// Note [Batching rules for matmul-like operators] +// at::matmul doesn't "de-expand" arguments to get better performance (maybe +// it should). In the batching rules for matmul-like operators (dot, mv, mm), +// we should be careful not to expand any unnecessary dimensions. e.g., if +// only one of the two arguments is a BatchedTensor, then we should try +// not to expand batch dimensions onto the other arg. +Tensor mv_batching_rule(const Tensor& self, const Tensor& other) { + auto self_batched = isBatchedTensor(self); + auto other_batched = isBatchedTensor(other); + + // A shape checking API would be nice... + TORCH_CHECK(self.dim() == 2 && other.dim() == 1, + "mv(self, other): Shape mismatch: expected matrix " + "(got `self` of size ", self.sizes(), ") ", + "and vector (got `other` of size ", other.sizes(), ")"); + + // See Note [Batching rules for matmul-like operators] for why we have cases + if (self_batched && !other_batched) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::matmul(self_physical.tensor(), other); + return self_physical.getPhysicalToLogicalMap().apply(result); + } + if (!self_batched && other_batched) { + // self_physical: [L, K], other_physical: [..., K] + // We view the tensors as [L, K], [..., K, 1], perform matmul to get + // a tensor of size [..., L, 1], and unsqueeze the last dim. + auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other); + auto result = at::matmul(self, other_physical.tensor().unsqueeze(-1)); + return other_physical.getPhysicalToLogicalMap().apply(result.squeeze(-1)); + } + if (self_batched && other_batched) { + // self_physical: [..., L, K], other_physical: [..., K] + // We view the tensors as [..., L, K], [..., K, 1], perform matmul to get + // a tensor of size [..., L, 1], and unsqueeze the last dim. + auto physical_args = MultiBatchVmapTransform::logicalToPhysical({self, other}); + auto result = at::matmul( + physical_args[0].tensor(), + physical_args[1].tensor().unsqueeze(-1)); + return physical_args[0].getPhysicalToLogicalMap().apply(result.squeeze(-1)); + } + TORCH_INTERNAL_ASSERT(false, "either self or other must be a BatchedTensor"); +} + +Tensor _make_dual_batching_rule( + c10::DispatchKeySet ks, + const Tensor& primal, + const Tensor& tangent, + int64_t level +) { + DispatchKeySet after_batched_keyset = + DispatchKeySet(DispatchKeySet::FULL_AFTER, c10::DispatchKey::Batched); + return at::redispatch::_make_dual(ks & after_batched_keyset, primal, tangent, level); +} + +Tensor dot_batching_rule(const Tensor& self, const Tensor& other) { + auto self_batched = isBatchedTensor(self); + auto other_batched = isBatchedTensor(other); + + TORCH_CHECK(/*logical*/self.dim() == 1 && /*logical*/other.dim() == 1, + "dot(self, other): Shape mismatch: vector " + "(got `self` of size ", self.sizes(), ") ", + "and vector (got `other` of size ", other.sizes(), ")"); + + // See Note [Batching rules for matmul-like operators] for why we have cases + if (self_batched && !other_batched) { + // self_physical: [..., K], other_physical: [K] + // View the tensors as [..., 1, K] and [K], perform matmul, and unsqueeze. + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::matmul(self_physical.tensor().unsqueeze(-2), other); + return self_physical.getPhysicalToLogicalMap().apply(result.squeeze(-1)); + } + if (!self_batched && other_batched) { + // self_physical: [K], other_physical: [..., K] + // View the tensors as [K] and [..., K, 1], perform matmul, and unsqueeze. + auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other); + auto result = at::matmul(self, other_physical.tensor().unsqueeze(-1)); + return other_physical.getPhysicalToLogicalMap().apply(result.squeeze(-1)); + } + if (self_batched && other_batched) { + // self_physical: [..., K], other_physical: [..., K] + // View the tensors as [..., 1, K] and [..., K, 1], perform matmul, and unsqueeze. + auto physical_args = MultiBatchVmapTransform::logicalToPhysical({self, other}); + auto result = at::matmul( + physical_args[0].tensor().unsqueeze(-2), + physical_args[1].tensor().unsqueeze(-1)); + return physical_args[0].getPhysicalToLogicalMap().apply(result.squeeze(-1).squeeze(-1)); + } + TORCH_INTERNAL_ASSERT(false, "either self or other must be a BatchedTensor"); +} + +Tensor bmm_batching_rule(const Tensor& self, const Tensor& other) { + TORCH_CHECK(/*logical*/self.dim() == 3 && /*logical*/other.dim() == 3, + "bmm(self, other): Shape mismatch: expected 3D `self` " + "(got `self` of size ", self.sizes(), ") ", + "and 3D `other` (got `other` of size ", other.sizes(), ")"); + + auto physical_args = BroadcastingVmapTransform::logicalToPhysical({self, other}); + auto result = at::matmul(physical_args[0].tensor(), physical_args[1].tensor()); + return physical_args[0].getPhysicalToLogicalMap().apply(result); +} + +Tensor mm_batching_rule(const Tensor& self, const Tensor& other) { + auto self_batched = isBatchedTensor(self); + auto other_batched = isBatchedTensor(other); + + TORCH_CHECK(/*logical*/self.dim() == 2 && /*logical*/other.dim() == 2, + "mm(self, other): Shape mismatch: expected matrix " + "(got `self` of size ", self.sizes(), ") ", + "and matrix (got `other` of size ", other.sizes(), ")"); + + // See Note [Batching rules for matmul-like operators] for why we have cases + if (self_batched && !other_batched) { + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto result = at::matmul(self_physical.tensor(), other); + return self_physical.getPhysicalToLogicalMap().apply(result); + } + if (!self_batched && other_batched) { + auto other_physical = MultiBatchVmapTransform::logicalToPhysical(other); + auto result = at::matmul(self, other_physical.tensor()); + return other_physical.getPhysicalToLogicalMap().apply(result); + } + if (self_batched && other_batched) { + auto physical_args = MultiBatchVmapTransform::logicalToPhysical({self, other}); + auto result = at::matmul(physical_args[0].tensor(), physical_args[1].tensor()); + return physical_args[0].getPhysicalToLogicalMap().apply(result.squeeze(-1).squeeze(-1)); + } + TORCH_INTERNAL_ASSERT(false, "either self or other must be a BatchedTensor"); +} + +Tensor cat_batching_rule(const ITensorListRef& tensors, int64_t dim) { + auto physical_views = MultiBatchVmapTransform::logicalToPhysical(tensors); + auto physical_tensors = fmap( + physical_views, [](const VmapPhysicalView& view) -> Tensor { return view.tensor(); }); + TORCH_INTERNAL_ASSERT( + !tensors.empty(), "The dispatcher should not have dispatched here otherwise."); + auto result = at::cat(physical_tensors, physical_views[0].getPhysicalDim(dim)); + return physical_views[0].getPhysicalToLogicalMap().apply(result); +} + +Tensor stack_batching_rule(TensorList tensors, int64_t dim) { + auto physical_views = MultiBatchVmapTransform::logicalToPhysical(tensors); + auto physical_tensors = fmap( + physical_views, [](const VmapPhysicalView& view) -> Tensor { return view.tensor(); }); + TORCH_INTERNAL_ASSERT( + !tensors.empty(), "The dispatcher should not have dispatched here otherwise."); + // NB: stack wraps the dimensionality to (logical dim + 1), so we have to + // manually handle that here. + auto dim_physical = + physical_views[0].numBatchDims() + maybe_wrap_dim(dim, /*logical*/tensors[0].dim() + 1); + auto result = at::stack(physical_tensors, dim_physical); + return physical_views[0].getPhysicalToLogicalMap().apply(result); +} + +// I am quite sad that we need to register operators with exploded TensorOptions, +// even though the native:: implementations can use TensorOptions&. +// This also makes it hard to metaprogram: i.e., we can't use +// unwrap_and_call<..., at::to> because at::to takes TensorOptions& (!!) +Tensor to_dtype_layout_batching_rule( + const Tensor& self, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory, + bool non_blocking, bool copy, + std::optional memory_format) { + auto options = TensorOptions() + .dtype(dtype) + .layout(layout) + .device(device) + .pinned_memory(pin_memory); + auto* input_batched = unsafeGetBatchedImpl(self); + auto output_physical = input_batched->value().to(options, non_blocking, copy, memory_format); + auto old_bdims = input_batched->bdims(); + return makeBatched(output_physical, BatchDims(old_bdims.begin(), old_bdims.end())); +} + +Tensor new_zeros_batching_rule( + const Tensor& self, + IntArrayRef size, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory) { + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self); + auto physical_size = physical_view.getPhysicalShape(size); + auto options = TensorOptions() + .dtype(dtype) + .layout(layout) + .device(device) + .pinned_memory(pin_memory); + auto result = physical_view.tensor().new_zeros(physical_size, options); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +Tensor new_empty_batching_rule( + const Tensor& self, + IntArrayRef size, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory) { + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self); + auto physical_size = physical_view.getPhysicalShape(size); + auto result = physical_view.tensor().new_empty(physical_size, TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory)); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +Tensor new_empty_strided_batching_rule( + const Tensor& self, + IntArrayRef size, + IntArrayRef stride, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory) { + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self); + auto physical_size = physical_view.getPhysicalShape(size); + + // Let [B0, B1, B2] be the shape of the batch dims. We're going to create + // the batch dimensions at the front of the tensor (in memory layout), + // irrespective of whether or not they are actually at the front (in memory layout) + // in the original `self` tensor. This is because when a user calls + // `new_empty_strided` in general, the `strides` they provide are for a new + // tensor and have no relation to the strides of the original tensor. + // + // So, the physical shape of the result should be ([B0, B1, B2] + size), + // but what about the physical strides? + // + // We're actually free to pick whatever stride we want: + // e.g., for size=[5, 3], stride=[0, 1], we could decide to + // use + // - physical size: [B0, B1, B2, 5, 3] + // - physical stride: [9999*B1*B2, 9999*B2, 9999, 0, 1] + // + // Let's select some reasonable strides such that: + // - The batch dims are "contiguous" with respect to each other + // - if empty_strided(size, stride) would have created a contiguous Tensor, + // then this new physical Tensor (with batch dims) is also contiguous + // + // Let S be the size of the storage if one were to construct a tensor + // with `size` and `stride` via empty_strided(size, stride). + // Then the physical sizes/strides should be: + // - physical size: [B0, B1, B2, 5, 3] + // - physical stride: [B1 * B2 * S, B2 * S, S, 0, 1] + auto batch_shape = IntArrayRef( + physical_view.tensor().sizes().begin(), physical_view.numBatchDims()); + + // physical_strides = [B1 * B2 * S, B2 * S, S] + auto physical_strides = at::detail::defaultStrides(batch_shape); + TORCH_CHECK(size.size() == stride.size(), + "new_empty_strided(sizes, strides): dimensionality of sizes (", + size.size(), ") must match dimensionality of strides (", + stride.size(), ")"); + auto storage_size = native::storage_size_for(size, stride); + for (auto& physical_stride : physical_strides) { + physical_stride *= storage_size; + } + + // physical_strides = [B1 * B2 * S, B2 * S, S] + strides + physical_strides.insert(physical_strides.end(), stride.begin(), stride.end()); + + auto result = physical_view.tensor().new_empty_strided( + physical_size, physical_strides, dtype, layout, device, pin_memory); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +template +Tensor comparison_pointwise_batching_rule(const Tensor& self, const Tensor& other) { + auto physical_args = BroadcastingVmapTransform::logicalToPhysical({self, other}); + auto result = Func(physical_args[0].tensor(), physical_args[1].tensor()); + return physical_args[0].getPhysicalToLogicalMap().apply(result); +} +} +TORCH_LIBRARY_IMPL(_, Batched, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&batchedTensorForLoopFallback>()); +} + +TORCH_LIBRARY_IMPL(aten, Batched, m) { + // NB: Ideally we would like some operators, like size.int, to "fallthrough" + // to the underlying implementation. However, because a BatchedTensor is a + // Tensor wrapper, it only has one dispatch key (Batched) on it. The resolution + // here is to just directly call the underlying implementation. + m.impl("size.int", static_cast(native::size)); + m.impl("_add_batch_dim", native::_add_batch_dim); + m.impl("_remove_batch_dim", native::_remove_batch_dim); + m.impl("_make_dual", _make_dual_batching_rule); + m.impl("_has_same_storage_numel", _has_same_storage_numel_batching_rule); + m.impl("is_same_size", native::is_same_size); + m.impl("_new_zeros_with_same_feature_meta", _new_zeros_with_same_feature_meta_batching_rule); + + m.impl("sum.dim_IntList", sum_batching_rule); + m.impl("is_complex", native::is_complex); + + // inplace operations + m.impl("fill_.Scalar", fill_inplace_scalar_batching_rule); + m.impl("fill_.Tensor", fill_inplace_tensor_batching_rule); + m.impl("zero_", zero_inplace_batching_rule); + + // view operations + m.impl("as_strided", as_strided_batching_rule); + m.impl("chunk", chunk_batching_rule); + m.impl("tensor_split.sections", tensor_split_sections_batching_rule); + m.impl("tensor_split.indices", tensor_split_indices_batching_rule); + m.impl("diagonal", diagonal_batching_rule); + m.impl("expand", expand_batching_rule); + m.impl("expand_as", native::expand_as); // composite wrt autograd + m.impl("movedim.intlist", movedim_batching_rule); + m.impl("movedim.int", static_cast(native::movedim)); // composite wrt autograd + // There is another variant of narrow. However, we don't + // want to support the other variant yet bc it isn't documented... + m.impl("narrow", native::narrow_symint); // composite wrt autograd + m.impl("numpy_T", native::numpy_T); // composite wrt autograd + m.impl("matrix_H", native::matrix_H); // composite wrt autograd + m.impl("mT", native::mT); // composite wrt autograd + m.impl("mH", native::mH); // composite wrt autograd + m.impl("permute", permute_batching_rule); + m.impl("reshape", reshape_batching_rule); + m.impl("_reshape_alias", _reshape_alias_batching_rule); + m.impl("reshape_as", native::reshape_as); // composite wrt autograd + m.impl("select.int", select_batching_rule); + m.impl("slice.Tensor", slice_batching_rule); + m.impl("split.Tensor", split_batching_rule); + m.impl("split.sizes", split_with_sizes_batching_rule); + m.impl("split_with_sizes", split_with_sizes_batching_rule); + m.impl("squeeze", squeeze_batching_rule); + m.impl("squeeze.dim", squeeze_dim_batching_rule); + m.impl("squeeze.dims", squeeze_dims_batching_rule); + m.impl("t", native::t); // composite wrt autograd + m.impl("trace", trace_batching_rule); + m.impl("transpose.int", transpose_int_batching_rule); + m.impl("unbind.int", unbind_batching_rule); + m.impl("unfold", unfold_batching_rule); + m.impl("unsqueeze", unsqueeze_batching_rule); + m.impl("view", view_batching_rule); + m.impl("view_as", native::view_as); // composite wrt autograd + + // clamp operations + m.impl("clamp", clamp_batching_rule); + m.impl("clamp_min", clamp_min_batching_rule); + m.impl("clamp_max", clamp_max_batching_rule); + + // unary pointwise, out-of-place, no additional arguments. +#define UNARY_POINTWISE(op) m.impl(#op, \ + unwrap_and_call); + UNARY_POINTWISE(abs); + UNARY_POINTWISE(acos); + UNARY_POINTWISE(asin); + UNARY_POINTWISE(atan); + UNARY_POINTWISE(ceil); + UNARY_POINTWISE(cos); + UNARY_POINTWISE(cosh); + UNARY_POINTWISE(conj_physical); + UNARY_POINTWISE(digamma); + UNARY_POINTWISE(exp); + UNARY_POINTWISE(expm1); + UNARY_POINTWISE(floor); + UNARY_POINTWISE(frac); + UNARY_POINTWISE(lgamma); + UNARY_POINTWISE(log); + UNARY_POINTWISE(log10); + UNARY_POINTWISE(log1p); + UNARY_POINTWISE(log2); + UNARY_POINTWISE(neg); + UNARY_POINTWISE(reciprocal); + UNARY_POINTWISE(relu); + UNARY_POINTWISE(round); + UNARY_POINTWISE(rsqrt); + UNARY_POINTWISE(sigmoid); + UNARY_POINTWISE(sign); + UNARY_POINTWISE(sin); + UNARY_POINTWISE(sinh); + UNARY_POINTWISE(sqrt); + UNARY_POINTWISE(tan); + UNARY_POINTWISE(tanh); + UNARY_POINTWISE(trunc); +#undef UNARY_POINTWISE +#define TO_BATCHING_RULE(name, ...) \ + { \ + using to_type = Tensor(Tensor::*)(__VA_ARGS__) const; \ + m.impl(name, unwrap_and_call_method< \ + to_type, &Tensor::to, __VA_ARGS__>);\ + } + TO_BATCHING_RULE("to.device", Device, ScalarType, bool, bool, std::optional) + TO_BATCHING_RULE("to.dtype", ScalarType, bool, bool, std::optional) + TO_BATCHING_RULE("to.other", const Tensor&, bool, bool, std::optional) + m.impl("to.dtype_layout", to_dtype_layout_batching_rule); +#undef TO_BATCHING_RULE + m.impl("clone", clone_batching_rule); + + using TensorTensorScalarType = Tensor (*)(const Tensor&, const Tensor&, const Scalar&); + using TensorTensorType = Tensor (*)(const Tensor&, const Tensor&); + using TensorScalarType = Tensor (*)(const Tensor&, const Scalar&); + +#define BINARY_POINTWISE(op) \ + m.impl(#op".Tensor", binary_pointwise_batching_rule); \ + m.impl(#op".Scalar", unwrap_and_call); +#define BINARY_POINTWISE_VA(op, ...) \ + { \ + using Binop = Tensor (*)(const Tensor&, const Tensor&, __VA_ARGS__); \ + using Unop = Tensor (*)(const Tensor&, const Scalar&, __VA_ARGS__); \ + m.impl(#op".Tensor", binary_pointwise_batching_rule); \ + m.impl(#op".Scalar", unwrap_and_call); \ + } + + BINARY_POINTWISE_VA(add, const Scalar&); + BINARY_POINTWISE_VA(sub, const Scalar&); + BINARY_POINTWISE_VA(rsub, const Scalar&); + BINARY_POINTWISE(mul); + BINARY_POINTWISE(div); + { + using Binop = Tensor (*)(const Tensor&, const Tensor&, std::optional); + using Unop = Tensor (*)(const Tensor&, const Scalar&, std::optional); + m.impl("div.Tensor_mode", binary_pointwise_batching_rule>); + m.impl("div.Scalar_mode", unwrap_and_call>); + } + + // at::pow has three out-of-place overloads + m.impl("pow.Tensor_Tensor", binary_pointwise_batching_rule); + m.impl("pow.Tensor_Scalar", unwrap_and_call); + m.impl("pow.Scalar", pow_scalar_Tensor_batching_rule); + + m.impl("sigmoid_backward", binary_pointwise_batching_rule); + m.impl( + "threshold_backward", + binary_pointwise_batching_rule< + TensorTensorScalarType, + at::threshold_backward, + const Scalar&>); + + // for at::result_type, call the native::result_type implementation. + // We don't have to do anything special because native::result_type operates + // on the logical shape of the tensors. + m.impl("result_type.Tensor", static_cast(native::result_type)); + m.impl("result_type.Scalar", static_cast(native::result_type)); + m.impl("result_type.Scalar_Tensor", static_cast(native::result_type)); + m.impl("result_type.Scalar_Scalar", static_cast(native::result_type)); + +#undef BINARY_POINTWISE_VA +#undef BINARY_POINTWISE + + +#define TRIVIAL_OP(op) m.impl(#op, \ + unwrap_and_call); + // complex number view operators + TRIVIAL_OP(imag) + TRIVIAL_OP(real); + TRIVIAL_OP(view_as_real); + TRIVIAL_OP(conj); + TRIVIAL_OP(_conj); + TRIVIAL_OP(resolve_conj); + TRIVIAL_OP(resolve_neg); + m.impl("view_as_complex", view_as_complex_batching_rule); +#undef TRIVIAL + + // matmul-like operators + m.impl("mv", mv_batching_rule); + m.impl("dot", dot_batching_rule); + m.impl("bmm", bmm_batching_rule); + m.impl("mm", mm_batching_rule); + + // cat/stack + m.impl("cat", cat_batching_rule); + m.impl("stack", stack_batching_rule); + + // backward operators + m.impl("select_backward", select_backward_batching_rule); + m.impl("slice_backward", slice_backward_batching_rule); + m.impl("trace_backward", trace_backward_batching_rule); + m.impl("diagonal_backward", diagonal_backward_batching_rule); + + // Tensor.new_* operators + m.impl("new_empty", new_empty_batching_rule); + m.impl("new_empty_strided", new_empty_strided_batching_rule); + m.impl("new_zeros", new_zeros_batching_rule); + + m.impl("contiguous", contiguous_batching_rule); + + // Comparison ops +#define COMPARISON_POINTWISE(op) \ + m.impl(#op".Tensor", comparison_pointwise_batching_rule); \ + m.impl(#op".Scalar", unwrap_and_call); + + COMPARISON_POINTWISE(eq); + COMPARISON_POINTWISE(gt); + COMPARISON_POINTWISE(ge); + COMPARISON_POINTWISE(le); + COMPARISON_POINTWISE(lt); + COMPARISON_POINTWISE(ne); + +#undef COMPARISON_POINTWISE +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.cpp b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..315416a1638c84bd33494d1fef37e480dbc9f0a8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.cpp @@ -0,0 +1,26 @@ +#include + +namespace at::impl { + +thread_local static int64_t VmapMode_current_vmap_level = 0; + +int64_t VmapMode::current_vmap_level() { + return VmapMode_current_vmap_level; +} + +int64_t VmapMode::increment_nesting() { + VmapMode_current_vmap_level++; + if (VmapMode_current_vmap_level == 1) { + c10::impl::tls_set_dispatch_key_included(DispatchKey::VmapMode, true); + } + return VmapMode_current_vmap_level; +} + +int64_t VmapMode::decrement_nesting() { + VmapMode_current_vmap_level--; + if (VmapMode_current_vmap_level == 0) { + c10::impl::tls_set_dispatch_key_included(DispatchKey::VmapMode, false); + } + return VmapMode_current_vmap_level; +} +} // namespace at::impl diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.h b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.h new file mode 100644 index 0000000000000000000000000000000000000000..dfb093566ccbe05a23e1d474cad84166496eb402 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapMode.h @@ -0,0 +1,26 @@ +#pragma once + +#include + +namespace at::impl { + +// VmapMode contains a thread local count of how many nested vmaps +// we are currently inside. That number is known as the `vmap level`. +// VmapMode is used in the implementation of the Python `torch.vmap` API. +// +// NOTE: this is NOT the c++ api for torch.vmap. That doesn't exist yet. + +struct TORCH_API VmapMode { + // Returns the vmap level, aka the count of how many nested vmaps we're in. + static int64_t current_vmap_level(); + + // Increment the count of nested vmaps. If this causes the vmap level to be + // greater than 0, then it enables DispatchKey::VmapMode on all tensors. + static int64_t increment_nesting(); + + // Decrements the count of nested vmaps. If this causes the vmap level to be + // equal to 0, then it disables DispatchKey::VmapMode on all tensors. + static int64_t decrement_nesting(); +}; + +} // namespace at::impl diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.cpp b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe7cfad69ffc57d3ebd4dfb7a8247d0aa78ebc0a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.cpp @@ -0,0 +1,294 @@ +#include +#include + +namespace at { + +// Checks if the batch dims in `bdims` appear at the front of the tensor. +static bool areBdimsAtFrontInOrder(BatchDimsRef bdims) { + for (const auto idx : c10::irange(static_cast(bdims.size()))) { + if (bdims[idx].dim() != idx) { + return false; + } + } + return true; +} + +// Takes a BatchedTensorImpl, permutes all of the batch dims to the front, +// and then returns a physical version of the Tensor. +static Tensor permuteBatchDimsToFront(BatchedTensorImpl* batched) { + auto bdims = batched->bdims(); + const Tensor& physical_tensor = batched->value(); + if (areBdimsAtFrontInOrder(bdims)) { + return physical_tensor; + } + const auto sizes = physical_tensor.sizes(); + VmapDimVector permutation(sizes.size(), 0); + permutation.reserve(sizes.size()); + const auto is_bdim = createBatchDimBitset(bdims); + int64_t idx = 0; + for (const auto& bdim : bdims) { + permutation[idx++] = bdim.dim(); + } + for (const auto ptr : c10::irange(sizes.size())) { + if (is_bdim[ptr]) { + continue; + } + permutation[idx++] = static_cast(ptr); + } + return physical_tensor.permute(permutation); +} + +VmapPhysicalView MultiBatchVmapTransform::logicalToPhysical(const Tensor& logical_tensor) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + TORCH_INTERNAL_ASSERT( + batched, + "logicalToPhysical(tensor) should only be passed a BatchedTensor"); + return { permuteBatchDimsToFront(batched), createVmapLevelsBitset(batched->bdims()) }; +} + +int64_t VmapPhysicalView::numBatchDims() const { + return static_cast(levels_.count()); +} + +int64_t VmapPhysicalView::numLogicalDims() const { + return /*physical*/tensor_.dim() - numBatchDims(); +} + +VmapDimVector VmapPhysicalView::getPhysicalDims(OptionalIntArrayRef opt_logical_dims) const { + auto logical_ndim = numLogicalDims(); + // NB: fmap doesn't have a SmallVector variant, so we don't use it here. + VmapDimVector result; + result.reserve(logical_ndim); + if (opt_logical_dims.has_value() && !opt_logical_dims.value().empty()) { + auto logical_dims = opt_logical_dims.value(); + for (auto dim : logical_dims) { + result.push_back(maybe_wrap_dim(dim, logical_ndim) + numBatchDims()); + } + } else { + for (int64_t dim = 0; dim < logical_ndim; dim++) { + result.push_back(dim + numBatchDims()); + } + } + return result; +} + +int64_t VmapPhysicalView::getPhysicalDim(int64_t logical_dim) const { + auto logical_ndim = numLogicalDims(); + return maybe_wrap_dim(logical_dim, logical_ndim) + numBatchDims(); +} + +VmapDimVector VmapPhysicalView::getPhysicalShape(IntArrayRef logical_shape) const { + VmapDimVector result; + result.reserve(logical_shape.size() + numBatchDims()); + auto tensor_sizes = tensor_.sizes(); + result.insert(result.end(), tensor_sizes.begin(), tensor_sizes.begin() + numBatchDims()); + result.insert(result.end(), logical_shape.begin(), logical_shape.end()); + return result; +} + +static BatchDims computeFrontBatchDimsFromLevels(std::bitset levels_bitset) { + BatchDims bdims; + int64_t dim = 0; + for (const auto level : c10::irange(kVmapNumLevels)) { + if (!levels_bitset[level]) { + continue; + } + bdims.emplace_back(level, dim++); + } + return bdims; +} + +// Given a Tensor or a BatchedTensor, returns the underlying physical tensor +// with all vmapped dimensions permuted to the front, if they exist, and a +// bitset of vmap levels that were present in the tensor. +static std::pair> +getPhysicalTensorAndLevels(const Tensor& self) { + auto* batched = maybeGetBatchedImpl(self); + if (batched) { + return {permuteBatchDimsToFront(batched), createVmapLevelsBitset(batched->bdims())}; + } + return {self, 0}; +} + +// Given a Tensor or a BatchedTensor, creates a physical view of the tensor +// such that it has a batch dimension for each level in `requested_levels` +// and `requested_example_dim` number of non-batch-dimensions. +// +// This function is useful in preparing physical views on tensors that can +// then be passed into broadcasting operations. For example, when adding +// two BatchedTensors of sizes [B0, 3] and [B0, B1, 2, 3], where the Bi are the +// batch dimensions, we must align the batch dimensions and non-batch-dimensions +// (henceforth referred to as the "example" dimensions) separately to produce +// tensors of size [B0, 1, 1, 3] and [B0, B1, 2, 3] so that they can be added. +// +// Here's a direct example of using alignBatchDimsAtFront on the above two tensors. +// +// 1) alignBatchDimsAtFront([B0, 3], requested_levels={0, 1}, requested_example_dim=2) +// returns a physical view of size [B0, 1, 1, 3] by adding an extra dimension for +// level 1 and another extra dimension to pad the example dimensions to 2. +// +// 2) alignBatchDimsAtFront([B0, B1, 2, 3], requested_levels={0, 1}, requested_example_dim=2) +// returns a physical view of size [B0, B1, 2, 3] +static Tensor alignBatchDimsAtFront( + const Tensor& self, + std::bitset requested_levels, + int64_t requested_example_dim) { + auto [physical_tensor, tensor_levels] = getPhysicalTensorAndLevels(self); + + TORCH_INTERNAL_ASSERT( + (tensor_levels | requested_levels) == requested_levels, + "`requested_levels` must be a superset of `self`'s levels"); + + auto physical_sizes = physical_tensor.sizes(); + + const auto tensor_example_dim = ( + static_cast(physical_sizes.size()) + - /*num_batch_dims*/static_cast(tensor_levels.count()) + ); + TORCH_INTERNAL_ASSERT(tensor_example_dim <= requested_example_dim); + + if (tensor_levels == requested_levels && tensor_example_dim == requested_example_dim) { + // Optimization: no need to do another view if the physical tensor is + // already the correct shape + return physical_tensor; + } + + VmapDimVector aligned_sizes(requested_levels.count() + requested_example_dim, 1); + + // align the example dims (non-bdims dims) first + // aligned_sizes[-tensor_example_dim:] = tensor_sizes[-tensor_example_dim:] + std::copy( + physical_sizes.rbegin(), + physical_sizes.rbegin() + tensor_example_dim, + aligned_sizes.rbegin()); + + // align the bdims + int64_t level = 0; + int64_t tensor_dim = 0; + for (const auto bdim : c10::irange(requested_levels.count())) { + // Determine the level of the bdim + while (!requested_levels[level]) level++; + if (tensor_levels[level]) { + aligned_sizes[bdim] = physical_sizes[tensor_dim++]; + } + level++; + } + return physical_tensor.view(aligned_sizes); +} + +// The algorithm is as follows: +// 1. Figure out what all of the collective levels in `logical_tensors` is. +// 2. Move all batch dims to the front of the tensors and add extra dims +// of size 1. At this point, every tensor will have a dimension for +// each of the collective levels. +// 3. Compute the batch_sizes. +// 4. Expand each physical tensor so that they have output batch size equal +// to `batch_sizes` +VmapPhysicalViewVec +MultiBatchVmapTransform::logicalToPhysical(ITensorListRef logical_tensors) { + // Figure out all of the collective vmap levels in `logical_tensors`. + std::bitset collective_levels; + for (const auto& logical_tensor : logical_tensors) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + if (batched) { + collective_levels |= createVmapLevelsBitset(batched->bdims()); + } + } + + // Populate physical_tensors. + // This contains a list of regular (non-Batched) Tensors where all of the + // batch dims have been moved to the front of the tensor. Any previously + // non-existing batch dims get added to the tensors as new dimensions of size 1. + std::vector physical_tensors; + auto num_batch_dims = collective_levels.count(); + for (const auto& logical_tensor : logical_tensors) { + auto requested_example_dim = /*logical_dim*/logical_tensor.dim(); + auto physical_tensor = alignBatchDimsAtFront( + logical_tensor, collective_levels, requested_example_dim); + physical_tensors.push_back(std::move(physical_tensor)); + } + + // Compute batch_sizes + VmapDimVector batch_sizes(num_batch_dims, 1); + for (const auto& physical_tensor : physical_tensors) { + auto physical_sizes = physical_tensor.sizes(); + for (const auto dim : c10::irange(num_batch_dims)) { + if (physical_sizes[dim] != 1) { + batch_sizes[dim] = physical_sizes[dim]; + } + } + } + + // Expand each physical_tensor so that it has batch sizes `batch_sizes` + VmapPhysicalViewVec result; + for (const auto& physical_tensor : physical_tensors) { + VmapDimVector expanded_size(batch_sizes.begin(), batch_sizes.end()); + auto physical_sizes = physical_tensor.sizes(); + expanded_size.insert( + expanded_size.end(), + physical_sizes.begin() + num_batch_dims, + physical_sizes.end()); + result.emplace_back(physical_tensor.expand(expanded_size), collective_levels); + } + return result; +} + +static std::pair,int64_t> +getLevelsAndLargestLogicalDim(TensorList logical_tensors) { + TORCH_INTERNAL_ASSERT(!logical_tensors.empty()); + std::bitset levels; + int64_t largest_logical_dim = -1; + for (const auto& tensor : logical_tensors) { + auto* batched = maybeGetBatchedImpl(tensor); + if (batched) { + levels = levels | createVmapLevelsBitset(batched->bdims()); + } + auto tensor_logical_dim = /*logical dim*/tensor.dim(); + if (tensor_logical_dim > largest_logical_dim) { + largest_logical_dim = tensor_logical_dim; + } + } + return { levels, largest_logical_dim }; +} + +VmapPhysicalViewVec BroadcastingVmapTransform::logicalToPhysical(TensorList logical_tensors) { + TORCH_INTERNAL_ASSERT( + logical_tensors.size() == 2, + "This function has only been tested for two tensors. Please add more tests ", + "before removing this check "); + + VmapPhysicalViewVec result; + + auto [levels, largest_logical_dim] = getLevelsAndLargestLogicalDim(logical_tensors); + + for (const auto& tensor : logical_tensors) { + // NB: It's possible that we didn't actually need to align `tensor`. + // For example, when adding two tensors of size (B, 2), and (3, 2), where + // the first Tensor is a BatchedTensor with batch dim B and the second is + // a regular Tensor, we will return views of size (B, 1, 2) and (1, 3, 2). + // However, the view on the second tensor is unnecessary: broadcasting + // semantics allow for the addition of two tensors of size (B, 1, 2) and (3, 2)! + // + // If this unnecessary view is a problem, consider optimizing it away in + // the future. This may involve creating a new type of VmapPhysicalView + auto aligned = alignBatchDimsAtFront(tensor, levels, largest_logical_dim) ; + result.emplace_back(std::move(aligned), levels); + } + return result; +} + +VmapPhysicalToLogicalMap VmapPhysicalView::getPhysicalToLogicalMap() const { + return VmapPhysicalToLogicalMap(levels_); +} + +Tensor VmapPhysicalToLogicalMap::apply(const Tensor& physical_tensor) const { + return makeBatched(physical_tensor, computeFrontBatchDimsFromLevels(levels_)); +} + +void VmapPhysicalToLogicalMap::applyInplace(std::vector& physical_tensors) const { + for (auto & physical_tensor : physical_tensors) { + physical_tensor = apply(physical_tensor); + } +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.h b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.h new file mode 100644 index 0000000000000000000000000000000000000000..4ddb6cadee872824ae18f9c5b92ea70160834372 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LegacyVmapTransforms.h @@ -0,0 +1,183 @@ +#pragma once + +#include +#include + +namespace at { + +// This file contains abstractions used for transforming *logical* vmap +// arguments into *physical* arguments. (Keep reading for definitions of these +// terms). + +// NOTE: [Logical vs physical args] +// Consider the following vmap. +// vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4)) +// This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4], +// with batch dims 0 and 2: +// BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)]) +// +// We say the *logical* view of the tensor has size [3] -- tensors inside +// `func` appear to have size [3]. +// However, the *physical* underlying tensor (the one passed to vmap) has size +// [2, 3, 4]. +// +// This notion of logical vs physical also extends to non-tensor arguments. +// Consider the previous tensor; let's assume the user called +// `torch.sum(tensor, dim=0)` inside of `func`. Then the logical +// dimension they are reducing over is dim 0 but the physical dim is dim 1 +// (the first non-batch dimension) + +// Forward declared; see NOTE: [What is a VmapPhysicalView?] +struct VmapPhysicalView; + +// Most PyTorch operators take 4 or fewer inputs. +constexpr int64_t kVmapTransformStaticInputSize = 4; +using VmapPhysicalViewVec = + SmallVector; + +// Pytorch generally advertises good performance for <= 5 dims. +// (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap +// dimensions to get 8. Adjust this number as necessary +constexpr int64_t kVmapStaticDimVecSize = 8; +using VmapDimVector = SmallVector; +using VmapSymDimVector = SmallVector; + +// NOTE: [What is an VmapTransform?] +// An *VmapTransform* converts logical views of tensors to physical views. +// +// Batching rules use VmapTransforms to convert logical arguments to +// physical arguments, then call one or more at:: operator that handles the +// physical arguments, and then converts the physical result back to a logical +// argument. + +// VmapTransform for operators that take tensors with multiple batch dims. +// Given one or more logical views on Tensors, `logicalToPhysical` +// permutes all of the batch dims to the front of the tensor, aligns +// and expands the batch dims to match each other (according to their `level`), +// and returns a VmapPhysicalView on the tensor(s). +struct TORCH_API MultiBatchVmapTransform { + static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor); + static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors); +}; + +// VmapTransform for operators that broadcast all inputs. +// Given some logical views on Tensors, `logicalToPhysical`: +// - permutes all of the batch dims to the front of the tensors +// - aligns all the batch dims to the collective levels of all of the tensors. +// If a tensor does not have a batch dim for a vmap level, then it receives +// a size-one dimension for said level. +// - aligns the non-batch dims to have the same dimensionality, adding extra +// size-1 dimensions in between the batch dimensions and the non-batch +// dimensions so that the batch dimensions are lined up from the right. +// +// For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch +// dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap +// tensors of size (B, 1, 2) and (B, 3, 2). +// +// Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns +// VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't +// actually *need* to return a tensor of size (1, 2) for the second tensor +// because the broadcasting operation takes care of that for us, but we do +// it anyways to keep things simple. +struct TORCH_API BroadcastingVmapTransform { + static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors); +}; + +// Forward declared, if you're reading this file head to toe, don't worry about +// it yet. +struct VmapPhysicalToLogicalMap; + +// NOTE: [What is a VmapPhysicalView?] +// VmapPhysicalView represents a physical view on a Tensor. +// +// One can use it to further convert logical dimension indices, logical shapes, +// and more to their physical variants, or convert a new (physical) tensor into +// a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented). +// +// VmapPhysicalView stores a physical tensor with all of its batch dimensions at +// the front and some levels that correspond to said batch dimensions. +// +// The levels bitset specifies which vmap levels correspond to the batch +// dimensions at the front of the tensor. In particular, the number of set bits +// corresponds to the number of batch dimensions on `tensor` and the rightmost +// bit of `levels` specifies the maximum number of nested vmaps we are in at +// this point in time. +// For example, given: +// physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3}) +// +// Rightmost bit of `levels` is 3 indicating the number of nested vmaps less +// than or equal to 3. +// bitset: 010100 +// ^ +// | +// levels: 012345 +struct TORCH_API VmapPhysicalView { + VmapPhysicalView(Tensor&& tensor, std::bitset levels) + : levels_(levels), tensor_(std::move(tensor)) { + TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor_)); + } + + Tensor& tensor() { + return tensor_; + } + const Tensor& tensor() const { + return tensor_; + } + + // Maps logical dim indices to physical dim indices. Also does dim wrapping. + // + // For example, given: + // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3}) + // + // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}. + // This is because the size of levels tell us that the first two dimensions + // of `tensor_` are batch dimensions, so a logical dim of `n` is actually + // a physical dim of `n + 2`. + VmapDimVector getPhysicalDims(OptionalIntArrayRef logical_dims) const; + int64_t getPhysicalDim(int64_t logical_dim) const; + + // Returns a VmapPhysicalToLogicalMap object. This can be used for + // mapping a physical tensor to a new logical tensor (BatchedTensor) + VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const; + + // Maps a logical shape to a physical shape by prepending the batch + // sizes to the logical shape. + VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const; + + int64_t numBatchDims() const; + + private: + int64_t numLogicalDims() const; + + std::bitset levels_; + Tensor tensor_; +}; + +// Convenience struct used for mapping a physical tensor (a non-BatchedTensor) +// to a logical one (BatchedTensor). It holds some levels that are used to do +// the mapping and assumes that the batch dimensions in the physical tensor all +// occur at the front of the tensor. +struct TORCH_API VmapPhysicalToLogicalMap { + VmapPhysicalToLogicalMap(std::bitset levels) + : levels_(levels) {} + + // Maps a physical tensor to a new logical tensor (BatchedTensor). + // Assumes that all of the "batch dimensions" are at the front + // of the physical tensor. For example, given: + // - x = rank-4 Tensor with size 2, 3, 5, 7 + // - levels = (2, 4) + // Returns: + // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)]) + Tensor apply(const Tensor& physical_tensor) const; + + // Given a vector of physical tensors, + // 1. maps each tensor to a new logical tensor. Assumes that all of the + // "batch dimensions" are at the front of the physical tensors. + // 2. stores the new logical tensors back into the passed-in vector. This is + // to avoid additional dynamic allocations. + void applyInplace(std::vector& physical_tensors) const; + + std::bitset levels_; +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/LinalgBackend.h b/western_ai/usa/pytorch/aten/src/ATen/LinalgBackend.h new file mode 100644 index 0000000000000000000000000000000000000000..3b084d189d7fb61cc0f67ccc0be15614be7e490c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/LinalgBackend.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +#include +#include + +namespace at { + +enum class LinalgBackend : int8_t { Default, Cusolver, Magma }; + +inline std::string LinalgBackendToString(at::LinalgBackend backend) { + switch (backend) { + case LinalgBackend::Default: + return "at::LinalgBackend::Default"; + case LinalgBackend::Cusolver: + return "at::LinalgBackend::Cusolver"; + case LinalgBackend::Magma: + return "at::LinalgBackend::Magma"; + default: + TORCH_CHECK(false, "Unknown linalg backend"); + } +} + +inline std::ostream& operator<<( + std::ostream& stream, + at::LinalgBackend backend) { + return stream << LinalgBackendToString(backend); +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/MapAllocator.cpp b/western_ai/usa/pytorch/aten/src/ATen/MapAllocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a31a2d61b24044896bd4515af14f55673f6d740 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/MapAllocator.cpp @@ -0,0 +1,644 @@ +#include + +#include +#include +#include +#if ATOMIC_INT_LOCK_FREE == 2 +#define AT_ATOMIC_IPC_REFCOUNT 1 +#endif + + +#include +#ifdef _WIN32 +#include +#endif + +#if defined(HAVE_MMAP) +#include +#include +#include +#endif + +#if !defined(_MSC_VER) || defined(HAVE_MMAP) +#include +#include +#elif defined(_MSC_VER) +#include +#endif +#include + +namespace at { + +static constexpr int64_t map_alloc_alignment = 64; + +std::string NewProcessWideShmHandle() { + static std::atomic counter{0}; + static std::random_device rd; +#ifdef _MSC_VER + return fmt::format( + "/torch_{}_{}_{}", + GetCurrentProcessId(), + rd(), + counter.fetch_add(1, std::memory_order_relaxed)); +#else + return fmt::format( + "/torch_{}_{}_{}", + getpid(), + rd(), + counter.fetch_add(1, std::memory_order_relaxed)); +#endif +} +#if defined(_WIN32) || defined(HAVE_MMAP) + +namespace { +struct MapInfo { + std::atomic refcount; +}; + +constexpr const char* unknown_filename = "filename not specified"; +#ifdef _WIN32 +constexpr const char* unknown_eventname = "eventname not specified"; +#endif +} // namespace (anonymous) + +MapAllocator::MapAllocator(WithFd /*unused*/, std::string_view filename, int fd, int flags, size_t size) + : filename_(filename.empty() ? unknown_filename : filename) + , size_(0) // to be filled later +#ifdef _WIN32 + , handle_(INVALID_HANDLE_VALUE) // to be filled later + , event_(INVALID_HANDLE_VALUE) // to be filled later + , eventname_(filename.empty() ? unknown_eventname : (std::string(filename) + "_event")) +#else + , fd_(fd) +#endif +{ + + if (!(flags & ALLOCATOR_MAPPED_SHARED) && !(flags & ALLOCATOR_MAPPED_SHAREDMEM)) { + flags &= ~ALLOCATOR_MAPPED_NOCREATE; + } + if ((flags ^ ALLOCATOR_MAPPED_EXCLUSIVE) == 0) { + TORCH_CHECK(false, "ALLOCATOR_MAPPED_EXCLUSIVE flag requires opening the file in shared mode"); + } +#ifdef _WIN32 + if (fd != -1) { + TORCH_CHECK(false, "MapAllocator_newWithFd is unsupported on Windows"); + } +#endif + flags_ = flags; + + // OK, now do the allocation + + if (size == 0) { + return; + } + +#ifdef _WIN32 + if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) { + // Shadowing + const wchar_t *filename; + const wchar_t *eventname; + const std::wstring wFilename = c10::u8u16(filename_); + const std::wstring wEventname = c10::u8u16(eventname_); + LARGE_INTEGER hfilesz; + + if (filename_[0] == '/') { + filename = wFilename.c_str() + 1; + eventname = wEventname.c_str() + 1; + } else { + filename = wFilename.c_str(); + eventname = wEventname.c_str(); + } + + hfilesz.QuadPart = size; + + if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) { + event_ = CreateEventW(nullptr, FALSE, FALSE, eventname); + } else if (flags_ & ALLOCATOR_MAPPED_NOCREATE) { + event_ = OpenEventW(EVENT_ALL_ACCESS, FALSE, eventname); + } else { + TORCH_CHECK(false, "Expected either ALLOCATOR_MAPPED_EXCLUSIVE or ALLOCATOR_MAPPED_NOCREATE"); + } + + if (event_ == nullptr) { + TORCH_CHECK(false, "Couldn't open shared event: <", eventname, ">, error code: <", GetLastError(), ">"); + } + + if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) { + handle_ = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, hfilesz.HighPart, hfilesz.LowPart, filename); + } else if (flags_ & ALLOCATOR_MAPPED_NOCREATE) { + handle_ = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, filename); + } else { + TORCH_CHECK(false, "Expected either ALLOCATOR_MAPPED_EXCLUSIVE or ALLOCATOR_MAPPED_NOCREATE"); + } + + if (handle_ == nullptr) { + TORCH_CHECK(false, "Couldn't open shared file mapping: <", filename, ">, error code: <", GetLastError(), ">"); + } + + size_ = size; + base_ptr_ = MapViewOfFile(handle_, FILE_MAP_ALL_ACCESS, 0, 0, size); + if (!base_ptr_) { + TORCH_CHECK(false, "Couldn't map view of shared file <", filename, ">, error code: <", GetLastError(), ">"); + } + } else { + + HANDLE hfile; + HANDLE hmfile; + LARGE_INTEGER hfilesz; + + if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) { + TORCH_CHECK(false, "exclusive file mapping is not supported on Windows"); + } + if (flags_ & ALLOCATOR_MAPPED_NOCREATE) { + TORCH_CHECK(false, "file mapping without creation is not supported on Windows"); + } + if (flags_ & ALLOCATOR_MAPPED_KEEPFD) { + TORCH_CHECK(false, "ALLOCATOR_MAPPED_KEEPFD not supported on Windows"); + } + if (flags_ & ALLOCATOR_MAPPED_FROMFD) { + TORCH_CHECK(false, "ALLOCATOR_MAPPED_FROMFD not supported on Windows"); + } + + // Shadowing + const wchar_t *filename; + const std::wstring wFilename = c10::u8u16(filename_); + + filename = wFilename.c_str(); + + /* open file */ + /* FILE_FLAG_RANDOM_ACCESS ? */ + if (flags_) { + hfile = CreateFileW(filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) { + TORCH_CHECK(false, "could not open file <", filename_, "> in read-write mode; error code: <", GetLastError(), ">"); + } + } else { + hfile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + if (hfile == INVALID_HANDLE_VALUE) { + TORCH_CHECK(false, "could not open file <", filename_, "> in read-only mode; error code: <", GetLastError(), ">"); + } + } + + if (GetFileSizeEx(hfile, &hfilesz) == 0) { + TORCH_CHECK(false, "could not get file size: <", filename_, ">; error code: <", GetLastError(), ">"); + } + + if (size > 0) { + if (size > hfilesz.QuadPart) { + if (flags_) { + hfilesz.QuadPart = size; + if (SetFilePointerEx(hfile, hfilesz, NULL, FILE_BEGIN) == 0) { + CloseHandle(hfile); + TORCH_CHECK(false, "unable to stretch file <", filename_, "> to the right size; error code: <", GetLastError(), ">", filename_); + } + if (SetEndOfFile(hfile) == 0) { + CloseHandle(hfile); + TORCH_CHECK(false, "unable to write to file <", filename_, ">; error code: <", GetLastError(), ">"); + } + } else { + CloseHandle(hfile); + TORCH_CHECK(false, "file <", filename_, "> size <", hfilesz.QuadPart, "> is smaller than the required mapping size <", size, ">; error code: <", GetLastError(), ">"); + } + } + } else { + size = hfilesz.QuadPart; + } + + size_ = size; /* if we are here, it must be the right size */ + + hfilesz.QuadPart = size_; + + /* get map handle */ + if (flags_) { + if ( (hmfile = CreateFileMappingW(hfile, NULL, PAGE_READWRITE, hfilesz.HighPart, hfilesz.LowPart, NULL)) == NULL ) { + TORCH_CHECK(false, "could not create a map on file <", filename_, ">; error code: <", GetLastError(), ">"); + } + } else { + if ( (hmfile = CreateFileMappingW(hfile, NULL, PAGE_WRITECOPY, hfilesz.HighPart, hfilesz.LowPart, NULL)) == NULL ) { + TORCH_CHECK(false, "could not create a map on file <", filename_, ">; error code: <", GetLastError(), ">"); + } + } + + /* map the stuff */ + if(flags_) { + base_ptr_ = MapViewOfFile(hmfile, FILE_MAP_ALL_ACCESS, 0, 0, 0); + } else { + base_ptr_ = MapViewOfFile(hmfile, FILE_MAP_COPY, 0, 0, 0); + } + + CloseHandle(hfile); + CloseHandle(hmfile); + } +#else /* _WIN32 */ + { + /* open file */ + int fd{-1}; + int flags{}; // shadow + + if (flags_ & (ALLOCATOR_MAPPED_SHARED | ALLOCATOR_MAPPED_SHAREDMEM)) { + flags = O_RDWR | O_CREAT; + } else { + flags = O_RDONLY; + } + + if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) { + flags |= O_EXCL; + } + if (flags_ & ALLOCATOR_MAPPED_NOCREATE) { + flags &= ~O_CREAT; + } + + if (!(flags_ & ALLOCATOR_MAPPED_FROMFD)) { + if (flags_ & ALLOCATOR_MAPPED_SHARED) { + // NOLINTNEXTLINE(bugprone-assignment-in-if-condition) + if ((fd = open(filename_.c_str(), flags, static_cast(0600))) == -1) { + TORCH_CHECK(false, "unable to open file <", filename_, "> in read-write mode: ", c10::utils::str_error(errno), " (", errno, ")"); + } + } else if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) { +#ifdef HAVE_SHM_OPEN + // NOLINTNEXTLINE(bugprone-assignment-in-if-condition) + if((fd = shm_open(filename_.c_str(), flags, static_cast(0600))) == -1) { + TORCH_CHECK(false, "unable to open shared memory object <", filename_, "> in read-write mode: ", c10::utils::str_error(errno), " (", errno, ")"); + } +#else + TORCH_CHECK(false, "unable to open file <", filename_, "> in sharedmem mode, shm_open unavailable on this platform"); +#endif + } else { + // NOLINTNEXTLINE(bugprone-assignment-in-if-condition) + if ((fd = open(filename_.c_str(), O_RDONLY)) == -1) { + TORCH_CHECK(false, "unable to open file <", filename_, "> in read-only mode: ", c10::utils::str_error(errno), " (", errno, ")"); + } + } + } else { + fd = fd_; + TORCH_INTERNAL_ASSERT(fd >= 0); + } + + struct stat file_stat{}; + if (fstat(fd, &file_stat) == -1) { +#ifndef STRIP_ERROR_MESSAGES + int last_err = errno; +#endif + if (!(flags_ & ALLOCATOR_MAPPED_FROMFD)) { + ::close(fd); + } + TORCH_CHECK(false, "unable to stat the file <", filename_, ">: ", c10::utils::str_error(last_err), " (", last_err, ")"); + } + + if (size > 0) { + if (static_cast(size) > file_stat.st_size) { + if (flags_) { + if (ftruncate(fd, static_cast(size)) == -1) { + TORCH_CHECK(false, "unable to resize file <", filename_, "> to the right size: ", c10::utils::str_error(errno), " (", errno, ")"); + } + +#ifdef HAVE_POSIX_FALLOCATE + if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) { + for (;;) { + int err = posix_fallocate(fd, 0, static_cast(size)); + if (err == 0) { + break; + } + + if (err == EINTR) { + continue; + } + + if (err == EINVAL || err == EOPNOTSUPP) { + // the underlying filesystem does not support the operation + break; + } + + TORCH_CHECK(false, "unable to allocate shared memory(shm) for file <", filename_, ">: ", c10::utils::str_error(err), " (", err, ")"); + } + } +#endif + + if (fstat(fd, &file_stat) == -1 || file_stat.st_size < static_cast(size)) { +#ifndef STRIP_ERROR_MESSAGES + int last_err = errno; +#endif + ::close(fd); + TORCH_CHECK(false, "unable to stretch file <", filename_, "> to the right size: ", c10::utils::str_error(last_err), " (", last_err, ")"); + } +/* on macOS write returns with errno 45 (Operation not supported) when used + * with a file descriptor obtained via shm_open + */ +#ifndef __APPLE__ + if ((write(fd, "", 1)) != 1) /* note that the string "" contains the '\0' byte ... */ { +#ifndef STRIP_ERROR_MESSAGES + int last_err = errno; +#endif + ::close(fd); + TORCH_CHECK(false, "unable to write to file <", filename_, ">: ", c10::utils::str_error(last_err), " (", last_err, ")"); + } +#endif + } else { + ::close(fd); + TORCH_CHECK(false, "file <", filename_, "> size <", file_stat.st_size, "> is smaller than the required mapping size <", size, ">"); + } + } + } else { + size = file_stat.st_size; + } + + size_ = static_cast(size); /* if we are here, it must be the right size */ + + /* map it */ + if (flags_ & (ALLOCATOR_MAPPED_SHARED | ALLOCATOR_MAPPED_SHAREDMEM)) { + base_ptr_ = mmap(nullptr, size_, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + } else { + base_ptr_ = mmap(nullptr, size_, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); + } + + if (base_ptr_ == MAP_FAILED) { + base_ptr_ = nullptr; /* let's be sure it is NULL */ + TORCH_CHECK(false, "unable to mmap ", size_, " bytes from file <", filename_, ">: ", c10::utils::str_error(errno), " (", errno, ")"); + } + +#if !defined(__APPLE__) && !defined(__ANDROID__) + /* attempt to use larger block size on Linux, which is important for getting better CUDA upload speed */ + posix_fadvise(fd, 0, static_cast(size), POSIX_FADV_SEQUENTIAL); +#endif + + if (flags_ & ALLOCATOR_MAPPED_KEEPFD) { + fd_ = fd; + } else { + if (::close(fd) == -1) { + TORCH_CHECK(false, "Error closing file <", filename_, ">: ", c10::utils::str_error(errno), " (", errno, ")"); + } + fd_ = -1; + } + + if (flags_ & ALLOCATOR_MAPPED_UNLINK) { + if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) { +#ifdef HAVE_SHM_UNLINK + if (shm_unlink(filename_.c_str()) == -1) { + TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, " : ", c10::utils::str_error(errno), " (", errno, ")"); + } +#else + TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, ", shm_unlink not available on platform"); +#endif + } else { + if (unlink(filename_.c_str()) == -1) + TORCH_CHECK(false, "could not unlink file ", filename_, " : ", c10::utils::str_error(errno), " (", errno, ")"); + } + } + + if (base_ptr_ == MAP_FAILED) { + TORCH_CHECK(false, "$ Torch: unable to mmap memory: you tried to mmap ", size_/1073741824, " GB."); + } + } +#endif + c10::reportMemoryUsageToProfiler(base_ptr_, size_, 0, size_, c10::Device(c10::DeviceType::CPU)); +} + +MapAllocator::MapAllocator(std::string_view filename, int flags, size_t size) + : MapAllocator(WITH_FD, filename, -1, flags, size) +{} + +#ifdef _WIN32 +struct ReleaseContext { + HANDLE event; + HANDLE handle; + HANDLE wait; +}; +static void CALLBACK WaitForReleaseHandle(PVOID lpParam, BOOLEAN TimerOrWaitFired) +{ + if (lpParam) { + ReleaseContext *ctx = (ReleaseContext *)lpParam; + + SetEvent(ctx->event); + CloseHandle(ctx->event); + CloseHandle(ctx->handle); + + UnregisterWait(ctx->wait); + + delete ctx; + } +} +#endif + +void MapAllocator::close() { + if (closed_) { + return; + } + closed_ = true; + if (base_ptr_ == nullptr) { + return; + } +#ifdef _WIN32 + if ((flags_ & ALLOCATOR_MAPPED_KEEPFD) || (flags_ & ALLOCATOR_MAPPED_SHAREDMEM)) + CloseHandle(handle_); + if(UnmapViewOfFile(base_ptr_) == 0) + TORCH_CHECK(false, "could not unmap the shared memory file"); +#else /* _WIN32 */ + if (flags_ & ALLOCATOR_MAPPED_KEEPFD) { + if (::close(fd_) == -1) { + TORCH_CHECK(false, "could not close file descriptor ", fd_, " :", c10::utils::str_error(errno), " (", errno, ")" ); + } + } + + if (munmap(base_ptr_, size_)) { + TORCH_CHECK(false, "could not unmap the shared memory file: ", c10::utils::str_error(errno), " (", errno, ")"); + } + + if (!(flags_ & (ALLOCATOR_MAPPED_FROMFD | ALLOCATOR_MAPPED_UNLINK))) { + if (flags_ & ALLOCATOR_MAPPED_SHAREDMEM) { +#ifdef HAVE_SHM_UNLINK + if (shm_unlink(filename_.c_str()) == -1) { + TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, " : ", c10::utils::str_error(errno), " (", errno, ")"); + } +#else + TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, ", shm_unlink not available on platform"); +#endif + } + } +#endif /* _WIN32 */ +} + +#else /* defined(_WIN32) || defined(HAVE_MMAP) */ + +MapAllocator::MapAllocator(std::string_view filename, int flags, size_t size) { + TORCH_CHECK(false, "file mapping not supported on your system"); +} + +MapAllocator::MapAllocator(WithFd, std::string_view filename, int fd, int flags, size_t size) { + TORCH_CHECK(false, "file mapping not supported on your system"); +} + +void MapAllocator::close() { } + +#endif + +#if (defined(_WIN32) || defined(HAVE_MMAP)) && defined(AT_ATOMIC_IPC_REFCOUNT) + +RefcountedMapAllocatorArgCheck::RefcountedMapAllocatorArgCheck(int flags) { + if (flags & ALLOCATOR_MAPPED_FROMFD) { + TORCH_CHECK(false, "RefcountedMapAllocator doesn't support ALLOCATOR_MAPPED_FROMFD flag"); + } + if (flags & ALLOCATOR_MAPPED_KEEPFD) { + TORCH_CHECK(false, "RefcountedMapAllocator doesn't support ALLOCATOR_MAPPED_KEEPFD flag"); + } + if (flags & ALLOCATOR_MAPPED_UNLINK) { + TORCH_CHECK(false, "RefcountedMapAllocator doesn't support ALLOCATOR_MAPPED_UNLINK flag"); + } + if (!(flags & ALLOCATOR_MAPPED_SHAREDMEM)) { + TORCH_CHECK(false, "RefcountedMapAllocator requires ALLOCATOR_MAPPED_SHAREDMEM flag"); + } +} + +RefcountedMapAllocator::RefcountedMapAllocator(const char *filename, int flags, size_t size) + : RefcountedMapAllocatorArgCheck(flags) + , MapAllocator(filename, flags, size + map_alloc_alignment) { + + initializeAlloc(); +} +RefcountedMapAllocator::RefcountedMapAllocator(WithFd /*unused*/, const char *filename, int fd, int flags, size_t size) + : RefcountedMapAllocatorArgCheck(flags) + , MapAllocator(WITH_FD, filename, flags, fd, size + map_alloc_alignment) { + + initializeAlloc(); +} + +void RefcountedMapAllocator::initializeAlloc() { + TORCH_CHECK(base_ptr_, "base_ptr_ is null"); + MapInfo *map_info = static_cast(base_ptr_); + +#ifdef _WIN32 + ReleaseContext* r_ctx = new ReleaseContext; + r_ctx->handle = handle_; + r_ctx->event = event_; + r_ctx->wait = NULL; + BOOL can_wait = RegisterWaitForSingleObject(&r_ctx->wait, event_, WaitForReleaseHandle, (PVOID)r_ctx, INFINITE, WT_EXECUTEONLYONCE); + TORCH_CHECK(can_wait, "Couldn't register wait on event, error code: <", GetLastError(), ">"); +#endif + + if (flags_ & ALLOCATOR_MAPPED_EXCLUSIVE) { + new (&map_info->refcount) std::atomic(1); + } else { + map_info->refcount++; + } +} + +void RefcountedMapAllocator::close() { + if (closed_) { + return; + } + closed_ = true; + + void* data = base_ptr_; + +#ifdef _WIN32 + MapInfo *info = (MapInfo*)data; + if (--info->refcount == 0) { + SetEvent(event_); + } + if(UnmapViewOfFile(data) == 0) { + TORCH_CHECK(false, "could not unmap the shared memory file"); + } +#else /* _WIN32 */ + + MapInfo *info = static_cast(data); + if (--info->refcount == 0) { +#ifdef HAVE_SHM_UNLINK + if (shm_unlink(filename_.c_str()) == -1) { + TORCH_CHECK(false, "could not unlink the shared memory file ", filename_); + } +#else + TORCH_CHECK(false, "could not unlink the shared memory file ", filename_, ", shm_unlink not available on platform"); +#endif /* HAVE_SHM_UNLINK */ + } + if (munmap(info, size_)) { + TORCH_CHECK(false, "could not unmap the shared memory file ", filename_); + } +#endif /* _WIN32 */ +} + +void RefcountedMapAllocator::incref() +{ + MapInfo *map_info = static_cast(base_ptr_); + ++map_info->refcount; +} + +int RefcountedMapAllocator::decref() +{ + MapInfo *map_info = static_cast(base_ptr_); + return --map_info->refcount == 0; +} + +#else + + +RefcountedMapAllocatorArgCheck::RefcountedMapAllocatorArgCheck(int flags) {} + +RefcountedMapAllocator::RefcountedMapAllocator(const char *filename, int flags, size_t size) + : RefcountedMapAllocatorArgCheck(flags), + MapAllocator(filename, flags, size + map_alloc_alignment) +{ + TORCH_CHECK(false, "refcounted file mapping not supported on your system"); +} + +RefcountedMapAllocator::RefcountedMapAllocator(WithFd, const char *filename, int fd, int flags, size_t size) + : RefcountedMapAllocatorArgCheck(flags), + MapAllocator(WITH_FD, filename, flags, fd, size + map_alloc_alignment) +{ + TORCH_CHECK(false, "refcounted file mapping not supported on your system"); +} + +void RefcountedMapAllocator::initializeAlloc() {} + +void RefcountedMapAllocator::close() {} + +#endif + +static void deleteMapAllocator(void* ptr) { + delete static_cast(ptr); +} + +static void deleteRefcountedMapAllocator(void* ptr) { + delete static_cast(ptr); +} + +MapAllocator* MapAllocator::fromDataPtr(const at::DataPtr& dptr) { + return dptr.cast_context(&deleteMapAllocator); +} + +RefcountedMapAllocator* RefcountedMapAllocator::fromDataPtr(const at::DataPtr& dptr) { + return dptr.cast_context(&deleteRefcountedMapAllocator); +} + +at::DataPtr MapAllocator::makeDataPtr(std::string_view filename, int flags, size_t size, size_t* actual_size_out) { + auto* context = new MapAllocator(filename, flags, size); + if (actual_size_out) *actual_size_out = context->size(); + return {context->data(), context, &deleteMapAllocator, at::DeviceType::CPU}; +} + +at::DataPtr MapAllocator::makeDataPtr(WithFd /*unused*/, const char *filename, int fd, int flags, size_t size, size_t* actual_size_out) { + auto* context = new MapAllocator(WITH_FD, filename, fd, flags, size); + if (actual_size_out) *actual_size_out = context->size(); + return {context->data(), context, &deleteMapAllocator, at::DeviceType::CPU}; +} + +at::DataPtr RefcountedMapAllocator::makeDataPtr(const char *filename, int flags, size_t size, size_t* actual_size_out) { + auto* context = new RefcountedMapAllocator(filename, flags, size); + if (actual_size_out) *actual_size_out = context->size() - map_alloc_alignment; + return {context->data(), context, &deleteRefcountedMapAllocator, at::DeviceType::CPU}; +} + +at::DataPtr RefcountedMapAllocator::makeDataPtr(WithFd /*unused*/, const char *filename, int fd, int flags, size_t size, size_t* actual_size_out) { + auto* context = new RefcountedMapAllocator(WITH_FD, filename, fd, flags, size); + if (actual_size_out) *actual_size_out = context->size() - map_alloc_alignment; + return {context->data(), context, &deleteRefcountedMapAllocator, at::DeviceType::CPU}; +} + +void* RefcountedMapAllocator::data() const { + return static_cast(static_cast(base_ptr_) + map_alloc_alignment); +} + +MapAllocator::~MapAllocator() { + MapAllocator::close(); + c10::reportMemoryUsageToProfiler(base_ptr_, -size_, 0, 0, c10::Device(c10::DeviceType::CPU)); +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/MapAllocator.h b/western_ai/usa/pytorch/aten/src/ATen/MapAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..4dd45e9c9dd4b88228e9bd67c5fb1bb8de753ae8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/MapAllocator.h @@ -0,0 +1,147 @@ +#pragma once + +#include +#include + +namespace at { + +enum MappedAllocatorModes { + ALLOCATOR_MAPPED_SHARED = 1, + ALLOCATOR_MAPPED_SHAREDMEM = 2, + ALLOCATOR_MAPPED_EXCLUSIVE = 4, + ALLOCATOR_MAPPED_NOCREATE = 8, + ALLOCATOR_MAPPED_KEEPFD = 16, + ALLOCATOR_MAPPED_FROMFD = 32, + ALLOCATOR_MAPPED_UNLINK = 64 +}; + +// Sentinel value/type to help distinguish the file descriptor constructor from +// the non-file descriptor constructor +enum WithFd { WITH_FD }; + +TORCH_API std::string NewProcessWideShmHandle(); + +class TORCH_API MapAllocator { + public: + MapAllocator(std::string_view filename, int flags, size_t size); + MapAllocator( + WithFd /*unused*/, + std::string_view filename, + int fd, + int flags, + size_t size); + MapAllocator(const MapAllocator&) = delete; + MapAllocator& operator=(const MapAllocator&) = delete; + MapAllocator(MapAllocator&&) = delete; + MapAllocator& operator=(MapAllocator&&) = delete; + + const char* filename() const { + return filename_.c_str(); + } + int fd() const { +#ifdef _WIN32 + TORCH_CHECK(false, "MapAllocator::fd() is unsupported on Windows"); +#else + return fd_; +#endif + } + ptrdiff_t size() const { + return size_; + } + // Return a pointer to the actual data for this allocator + // (in the case of the refcounted allocator, this is offset + // from the base pointer.) + virtual void* data() const { + return base_ptr_; + } + + int flags() const { + return flags_; + } + + static MapAllocator* fromDataPtr(const at::DataPtr& /*dptr*/); + static at::DataPtr makeDataPtr( + std::string_view filename, + int flags, + size_t size, + size_t* actual_size_out); + static at::DataPtr makeDataPtr( + WithFd /*unused*/, + const char* filename, + int fd, + int flags, + size_t size, + size_t* actual_size_out); + + // Closes the data. Helps us avoid destructor shenanigans + virtual void close(); + + // This is very dangerous. You have to redefine this destructor for each + // subclass + virtual ~MapAllocator(); + + protected: + bool closed_ = false; + std::string filename_; + int flags_ = 0; + ptrdiff_t size_; /* mapped size */ +#ifdef _WIN32 + void* handle_; + void* event_; + std::string eventname_; +#else + int fd_ = -1; +#endif + void* base_ptr_ = nullptr; +}; + +// Base-from-member idiom +struct TORCH_API RefcountedMapAllocatorArgCheck { + RefcountedMapAllocatorArgCheck(int flags); +}; + +class TORCH_API RefcountedMapAllocator : private RefcountedMapAllocatorArgCheck, + public MapAllocator { + public: + RefcountedMapAllocator(const char* filename, int flags, size_t size); + RefcountedMapAllocator( + WithFd /*unused*/, + const char* filename, + int fd, + int flags, + size_t size); + + static RefcountedMapAllocator* fromDataPtr(const at::DataPtr& /*dptr*/); + RefcountedMapAllocator(const RefcountedMapAllocator&) = delete; + RefcountedMapAllocator(RefcountedMapAllocator&&) = delete; + RefcountedMapAllocator& operator=(const RefcountedMapAllocator&) = delete; + RefcountedMapAllocator& operator=(RefcountedMapAllocator&&) = delete; + static at::DataPtr makeDataPtr( + const char* filename, + int flags, + size_t size, + size_t* actual_size_out); + static at::DataPtr makeDataPtr( + WithFd /*unused*/, + const char* filename, + int fd, + int flags, + size_t size, + size_t* actual_size_out); + + void* data() const override; + + void incref(); + int decref(); + void close() override; + + ~RefcountedMapAllocator() override { + RefcountedMapAllocator::close(); + } + + protected: + void checkFlags(); + void initializeAlloc(); +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/MatrixRef.h b/western_ai/usa/pytorch/aten/src/ATen/MatrixRef.h new file mode 100644 index 0000000000000000000000000000000000000000..354d7c241c9a732b34b839c27b59a27f71d2ea2f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/MatrixRef.h @@ -0,0 +1,109 @@ +#pragma once +#include +#include + +namespace at { +/// MatrixRef - Like an ArrayRef, but with an extra recorded strides so that +/// we can easily view it as a multidimensional array. +/// +/// Like ArrayRef, this class does not own the underlying data, it is expected +/// to be used in situations where the data resides in some other buffer. +/// +/// This is intended to be trivially copyable, so it should be passed by +/// value. +/// +/// For now, 2D only (so the copies are actually cheap, without having +/// to write a SmallVector class) and contiguous only (so we can +/// return non-strided ArrayRef on index). +/// +/// P.S. dimension 0 indexes rows, dimension 1 indexes columns +template +class MatrixRef { + public: + typedef size_t size_type; + + private: + /// Underlying ArrayRef + ArrayRef arr; + + /// Stride of dim 0 (outer dimension) + size_type stride0; + + // Stride of dim 1 is assumed to be 1 + + public: + /// Construct an empty Matrixref. + /*implicit*/ MatrixRef() : arr(nullptr), stride0(0) {} + + /// Construct an MatrixRef from an ArrayRef and outer stride. + /*implicit*/ MatrixRef(ArrayRef arr, size_type stride0) + : arr(arr), stride0(stride0) { + TORCH_CHECK( + arr.size() % stride0 == 0, + "MatrixRef: ArrayRef size ", + arr.size(), + " not divisible by stride ", + stride0) + } + + /// @} + /// @name Simple Operations + /// @{ + + /// empty - Check if the matrix is empty. + bool empty() const { + return arr.empty(); + } + + const T* data() const { + return arr.data(); + } + + /// size - Get size a dimension + size_t size(size_t dim) const { + if (dim == 0) { + return arr.size() / stride0; + } else if (dim == 1) { + return stride0; + } else { + TORCH_CHECK( + 0, "MatrixRef: out of bounds dimension ", dim, "; expected 0 or 1"); + } + } + + size_t numel() const { + return arr.size(); + } + + /// equals - Check for element-wise equality. + bool equals(MatrixRef RHS) const { + return stride0 == RHS.stride0 && arr.equals(RHS.arr); + } + + /// @} + /// @name Operator Overloads + /// @{ + ArrayRef operator[](size_t Index) const { + return arr.slice(Index * stride0, stride0); + } + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + std::enable_if_t, MatrixRef>& operator=( + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + U&& Temporary) = delete; + + /// Disallow accidental assignment from a temporary. + /// + /// The declaration here is extra complicated so that "arrayRef = {}" + /// continues to select the move assignment operator. + template + std::enable_if_t, MatrixRef>& operator=( + std::initializer_list) = delete; +}; + +} // end namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.cpp b/western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1da4e98e7b0f338d1b6dba7d8b6ed3302e93cba5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.cpp @@ -0,0 +1,114 @@ +#include +#include +#include + +namespace at { + +MemOverlap has_internal_overlap(const TensorBase& tensor) { + return has_internal_overlap(tensor.unsafeGetTensorImpl()); +} + +MemOverlap has_internal_overlap(TensorImpl* t) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(t->layout() == kStrided); + + auto sizes = t->sym_sizes(); + auto strides = t->sym_strides(); + + // When we have unbacked symint strides, is_non_overlapping_and_dense + // often results in guard on data dependent errors. For now + // let us bail early if there are unbacked symint strides. + for (const auto i : c10::irange(strides.size())) { + if (!strides[i].has_hint()) { + return MemOverlap::TooHard; + } + } + + if (t->is_non_overlapping_and_dense_or_false()) { + return MemOverlap::No; + } + + for (const auto i : c10::irange(strides.size())) { + // NB: The size oblivious test is written very carefully here. When + // unbacked SymInts are involved, we should try to conservatively report + // if memory overlap /could/ happen under some setting of unbacked + // SymInts. Thus, if I have u0 size, we should assume that this has > 1 + // elements (first expression), but if I have a u0 stride, I should NOT + // assume that it is not zero (second expression) + if (TORCH_GUARD_OR_FALSE(sizes[i].sym_gt(1)) && strides[i] == 0) { + return MemOverlap::Yes; + } + } + + return MemOverlap::TooHard; +} + +void assert_no_internal_overlap(const TensorBase& t) { + assert_no_internal_overlap(t.unsafeGetTensorImpl()); +} + +void assert_no_internal_overlap(TensorImpl* t) { + TORCH_CHECK(has_internal_overlap(t) != MemOverlap::Yes, + "unsupported operation: more than one element of the written-to tensor " + "refers to a single memory location. Please clone() the tensor before " + "performing the operation."); +} + +MemOverlapStatus get_overlap_status(const TensorBase& a, const TensorBase& b) { + return get_overlap_status(a.unsafeGetTensorImpl(), b.unsafeGetTensorImpl()); +} + +MemOverlapStatus get_overlap_status(const TensorImpl* a, const TensorImpl* b) { + if (a == b) return MemOverlapStatus::Full; + if (a->numel() == 0 || b->numel() == 0) { + return MemOverlapStatus::No; + } + if (!a->is_non_overlapping_and_dense_or_false() || !b->is_non_overlapping_and_dense_or_false()) { + return MemOverlapStatus::TooHard; + } + // Test for storage equality, rather than pointer equality. + // This reduces precision, but if people are aliasing the + // same pointer across multiple storages there are many + // similar situations (e.g., storage().data() == storage().data()+1) + // which we will miss. + const auto& a_storage = a->unsafe_storage(); + if (a_storage && a_storage.is_alias_of(b->unsafe_storage())) { + const auto a_begin = static_cast(a->data()); + const auto a_end = a_begin + a->numel() * a->itemsize(); + const auto b_begin = static_cast(b->data()); + const auto b_end = b_begin + b->numel() * b->itemsize(); + + if (a_begin == b_begin && a_end == b_end) { + return (a->strides() == b->strides()) ? + MemOverlapStatus::Full : MemOverlapStatus::Partial; + } + if (a_begin < b_end && b_begin < a_end) { + return MemOverlapStatus::Partial; + } + } + return MemOverlapStatus::No; +} + +void assert_no_partial_overlap(const TensorBase& a, const TensorBase& b) { + assert_no_partial_overlap(a.unsafeGetTensorImpl(), b.unsafeGetTensorImpl()); +} + +void assert_no_partial_overlap(TensorImpl* a, TensorImpl* b) { + TORCH_CHECK(get_overlap_status(a, b) != MemOverlapStatus::Partial, + "unsupported operation: some elements of the input tensor and " + "the written-to tensor refer to a single memory location. " + "Please clone() the tensor before performing the operation."); +} + +void assert_no_overlap(const TensorBase& a, const TensorBase& b) { + assert_no_overlap(a.unsafeGetTensorImpl(), b.unsafeGetTensorImpl()); +} + +void assert_no_overlap(TensorImpl* a, TensorImpl* b) { + const auto lap = get_overlap_status(a, b); + TORCH_CHECK(lap != MemOverlapStatus::Partial && lap != MemOverlapStatus::Full, + "unsupported operation: some elements of the input tensor and " + "the written-to tensor refer to a single memory location. " + "Please clone() the tensor before performing the operation."); +} + +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.h b/western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.h new file mode 100644 index 0000000000000000000000000000000000000000..f8427eef13cdd1741262f4dcdb84900389157e22 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/MemoryOverlap.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +namespace c10 { +struct TensorImpl; +} + +namespace at { +class TensorBase; + +// MemOverlap: Whether or not there is memory overlap +// +// No: Absolutely no memory overlap +// Yes: Absolutely yes memory overlap +// TooHard: There might be memory overlap, but it was too expensive to compute. +// +// NB: Please update the python test for these if you renumber them. +enum class MemOverlap { No, Yes, TooHard }; + +enum class MemOverlapStatus { Full, Partial, No, TooHard }; + +TORCH_API MemOverlap has_internal_overlap(const TensorBase& t); +TORCH_API MemOverlap has_internal_overlap(c10::TensorImpl* t); + +TORCH_API void assert_no_internal_overlap(const TensorBase& t); +TORCH_API void assert_no_internal_overlap(c10::TensorImpl* t); + +TORCH_API MemOverlapStatus +get_overlap_status(const TensorBase& a, const TensorBase& b); +TORCH_API MemOverlapStatus +get_overlap_status(const c10::TensorImpl* a, const c10::TensorImpl* b); + +TORCH_API void assert_no_partial_overlap( + const TensorBase& a, + const TensorBase& b); +void assert_no_partial_overlap(c10::TensorImpl* a, c10::TensorImpl* b); + +TORCH_API void assert_no_overlap(const TensorBase& a, const TensorBase& b); +TORCH_API void assert_no_overlap(c10::TensorImpl* a, c10::TensorImpl* b); + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vec256_qint8_vsx.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vec256_qint8_vsx.h new file mode 100644 index 0000000000000000000000000000000000000000..a035b78ddfb89644d2b28878f5dbf44dca9eeef0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vec256_qint8_vsx.h @@ -0,0 +1,512 @@ +#pragma once + +#include +#include +#include +#include +#include + +// This file defines Vectorized<> for the quantized types. +// +// +// Currently, we simply use these classes as efficient converters between +// the quantized types and Vectorized, usually in bandwidth-bound cases +// where doing the arithmetic in full-precision is acceptable (e.g. +// elementwise operators). +// +// +// Conversions are as follows: +// Vectorized -> 4x Vectorized +// +// The size of the returned float vector is specified by the special +// constexpr function float_num_vecs. The type of the value returned +// from dequantize (and expected as an argument to quantize) is +// specified by float_vec_return_type. +// +// When writing kernels with these vectors, it is expected that floating- +// point operations will be carried out in a loop over +// Vectorized::float_num_vecs iterations. + +namespace at { +namespace vec { +inline namespace CPU_CAPABILITY { + +template <> +struct is_vec_specialized_for : std::bool_constant {}; +template <> +struct Vectorized { + private: + union { + struct { + vint8 _vec0; + vint8 _vec1; + }; + struct { + vbool8 _vecb0; + vbool8 _vecb1; + }; + + } __attribute__((__may_alias__)); + + public: + Vectorized() = default; + using size_type = int; + static constexpr size_type size() { + return 32; + } + + static constexpr size_t float_num_vecs() { + return 4; + } + static constexpr int int_num_vecs() { + return 4; + } + using float_vec_return_type = std::array, 4>; + using int_vec_return_type = std::array, 4>; + using value_type = typename c10::qint8::underlying; + using vec_internal_type = vint8; + using vec_internal_mask_type = vbool8; + // Broadcast constructor + C10_ALWAYS_INLINE Vectorized(const c10::qint8& val) + : _vec0{vec_splats(val.val_)}, _vec1{vec_splats(val.val_)} {} + + C10_ALWAYS_INLINE Vectorized(const Vectorized& other) + : _vec0{other._vec0}, _vec1(other._vec1) {} + + C10_ALWAYS_INLINE Vectorized(vint8 v) : _vec0{v}, _vec1{v} {} + C10_ALWAYS_INLINE Vectorized(vbool8 vmask) : _vecb0{vmask}, _vecb1{vmask} {} + C10_ALWAYS_INLINE Vectorized(vint8 v1, vint8 v2) : _vec0{v1}, _vec1{v2} {} + C10_ALWAYS_INLINE Vectorized(vbool8 v1, vbool8 v2) : _vecb0{v1}, _vecb1{v2} {} + + C10_ALWAYS_INLINE const vec_internal_type& vec0() const { + return _vec0; + } + C10_ALWAYS_INLINE const vec_internal_type& vec1() const { + return _vec1; + } + + static C10_ALWAYS_INLINE Vectorized loadu( + const void* ptr, + int count = size()) { + if (count == size()) { + return { + vec_vsx_ld(offset0, reinterpret_cast(ptr)), + vec_vsx_ld(offset16, reinterpret_cast(ptr))}; + } + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy(tmp_values, ptr, std::min(count, size()) * sizeof(value_type)); + return {vec_vsx_ld(offset0, tmp_values), vec_vsx_ld(offset16, tmp_values)}; + } + void C10_ALWAYS_INLINE store(void* ptr, int count = size()) const { + if (count == size()) { + vec_vsx_st(_vec0, offset0, reinterpret_cast(ptr)); + vec_vsx_st(_vec1, offset16, reinterpret_cast(ptr)); + } else if (count > 0) { + __at_align__ value_type tmp_values[size()]; + vec_vsx_st(_vec0, offset0, tmp_values); + vec_vsx_st(_vec1, offset16, tmp_values); + std::memcpy( + ptr, tmp_values, std::min(count, size()) * sizeof(value_type)); + } + } + + public: + float_vec_return_type C10_ALWAYS_INLINE dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { + vint16 vecshi0 = vec_unpackh(_vec0); + vint16 vecshi1 = vec_unpackl(_vec0); + + vint16 vecshi2 = vec_unpackh(_vec1); + vint16 vecshi3 = vec_unpackl(_vec1); + + vint32 veci0 = vec_unpackh(vecshi0); + vint32 veci1 = vec_unpackl(vecshi0); + + vint32 veci2 = vec_unpackh(vecshi1); + vint32 veci3 = vec_unpackl(vecshi1); + + vint32 veci4 = vec_unpackh(vecshi2); + vint32 veci5 = vec_unpackl(vecshi2); + + vint32 veci6 = vec_unpackh(vecshi3); + vint32 veci7 = vec_unpackl(vecshi3); + + vfloat32 vecf0_0 = vec_float(veci0); + vfloat32 vecf1_0 = vec_float(veci1); + + vfloat32 vecf0_1 = vec_float(veci2); + vfloat32 vecf1_1 = vec_float(veci3); + + vfloat32 vecf0_2 = vec_float(veci4); + vfloat32 vecf1_2 = vec_float(veci5); + + vfloat32 vecf0_3 = vec_float(veci6); + vfloat32 vecf1_3 = vec_float(veci7); + vfloat32 scale_vec0 = scale.vec0(); + vfloat32 scale_vec1 = scale.vec1(); + + vfloat32 zero_point_vec0 = zero_point.vec0(); + vfloat32 zero_point_vec1 = zero_point.vec1(); + + vfloat32 vec_substract_src_zp0_0 = vec_sub(vecf0_0, zero_point_vec0); + vfloat32 vec_substract_src_zp1_0 = vec_sub(vecf1_0, zero_point_vec1); + Vectorized vf0_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_0), + vec_mul(scale_vec1, vec_substract_src_zp1_0)}; + + vfloat32 vec_substract_src_zp0_1 = vec_sub(vecf0_1, zero_point_vec0); + vfloat32 vec_substract_src_zp1_1 = vec_sub(vecf1_1, zero_point_vec1); + Vectorized vf1_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_1), + vec_mul(scale_vec1, vec_substract_src_zp1_1)}; + + vfloat32 vec_substract_src_zp0_2 = vec_sub(vecf0_2, zero_point_vec0); + vfloat32 vec_substract_src_zp1_2 = vec_sub(vecf1_2, zero_point_vec1); + Vectorized vf2_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_2), + vec_mul(scale_vec1, vec_substract_src_zp1_2)}; + + vfloat32 vec_substract_src_zp0_3 = vec_sub(vecf0_3, zero_point_vec0); + vfloat32 vec_substract_src_zp1_3 = vec_sub(vecf1_3, zero_point_vec1); + Vectorized vf3_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_3), + vec_mul(scale_vec1, vec_substract_src_zp1_3)}; + + return {vf0_zp, vf1_zp, vf2_zp, vf3_zp}; + } + + float_vec_return_type C10_ALWAYS_INLINE + dequantize(Vectorized scale, Vectorized zero_point) const { + vint16 vecshi0 = vec_unpackh(_vec0); + vint16 vecshi1 = vec_unpackl(_vec0); + + vint16 vecshi2 = vec_unpackh(_vec1); + vint16 vecshi3 = vec_unpackl(_vec1); + + vint32 veci0 = vec_unpackh(vecshi0); + vint32 veci1 = vec_unpackl(vecshi0); + + vint32 veci2 = vec_unpackh(vecshi1); + vint32 veci3 = vec_unpackl(vecshi1); + + vint32 veci4 = vec_unpackh(vecshi2); + vint32 veci5 = vec_unpackl(vecshi2); + + vint32 veci6 = vec_unpackh(vecshi3); + vint32 veci7 = vec_unpackl(vecshi3); + + vfloat32 vecf0_0 = vec_float(veci0); + vfloat32 vecf1_0 = vec_float(veci1); + + vfloat32 vecf0_1 = vec_float(veci2); + vfloat32 vecf1_1 = vec_float(veci3); + + vfloat32 vecf0_2 = vec_float(veci4); + vfloat32 vecf1_2 = vec_float(veci5); + + vfloat32 vecf0_3 = vec_float(veci6); + vfloat32 vecf1_3 = vec_float(veci7); + vfloat32 scale_vec0 = scale.vec0(); + vfloat32 scale_vec1 = scale.vec1(); + vfloat32 zero_point0 = zero_point.vec0(); + vfloat32 zero_point1 = zero_point.vec1(); + return { + Vectorized{ + (vecf0_0 - zero_point0) * scale_vec0, + (vecf1_0 - zero_point1) * scale_vec1}, + Vectorized{ + (vecf0_1 - zero_point0) * scale_vec0, + (vecf1_1 - zero_point1) * scale_vec1}, + Vectorized{ + (vecf0_2 - zero_point0) * scale_vec0, + (vecf1_2 - zero_point1) * scale_vec1}, + Vectorized{ + (vecf0_3 - zero_point0) * scale_vec0, + (vecf1_3 - zero_point1) * scale_vec1}}; + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + // constexpr int32_t min_val = std::numeric_limits::min(); + // constexpr int32_t max_val = std::numeric_limits::max(); + + vfloat32 inverse_scale_v = vec_splats(inverse_scale); + vfloat32 vec_zero_point = vec_splats((float)zero_point); + // vint32 vmin = vec_splats(min_val); + // vint32 vmax = vec_splats(max_val); + + Vectorized vf0 = rhs[0]; + Vectorized vf1 = rhs[1]; + Vectorized vf2 = rhs[2]; + Vectorized vf3 = rhs[3]; + vfloat32 vecf0 = vf0.vec0(); + vfloat32 vecf1 = vf0.vec1(); + vfloat32 vecf2 = vf1.vec0(); + vfloat32 vecf3 = vf1.vec1(); + + vfloat32 vecf4 = vf2.vec0(); + vfloat32 vecf5 = vf2.vec1(); + vfloat32 vecf6 = vf3.vec0(); + vfloat32 vecf7 = vf3.vec1(); + + vecf0 = vec_mul(vecf0, inverse_scale_v); + vecf1 = vec_mul(vecf1, inverse_scale_v); + vecf2 = vec_mul(vecf2, inverse_scale_v); + vecf3 = vec_mul(vecf3, inverse_scale_v); + + vecf4 = vec_mul(vecf4, inverse_scale_v); + vecf5 = vec_mul(vecf5, inverse_scale_v); + vecf6 = vec_mul(vecf6, inverse_scale_v); + vecf7 = vec_mul(vecf7, inverse_scale_v); + + vecf0 = vec_add(vec_rint(vecf0), vec_zero_point); + vecf1 = vec_add(vec_rint(vecf1), vec_zero_point); + vecf2 = vec_add(vec_rint(vecf2), vec_zero_point); + vecf3 = vec_add(vec_rint(vecf3), vec_zero_point); + + vecf4 = vec_add(vec_rint(vecf4), vec_zero_point); + vecf5 = vec_add(vec_rint(vecf5), vec_zero_point); + vecf6 = vec_add(vec_rint(vecf6), vec_zero_point); + vecf7 = vec_add(vec_rint(vecf7), vec_zero_point); + + vint32 veci0 = vec_signed(vecf0); + vint32 veci1 = vec_signed(vecf1); + vint32 veci2 = vec_signed(vecf2); + vint32 veci3 = vec_signed(vecf3); + + vint32 veci4 = vec_signed(vecf4); + vint32 veci5 = vec_signed(vecf5); + vint32 veci6 = vec_signed(vecf6); + vint32 veci7 = vec_signed(vecf7); + + // veci0 = vec_min(vmax, vec_max( vmin, vecf0)) ; + // veci1 = vec_min(vmax, vec_max( vmin, vecf1)) ; + // veci2 = vec_min(vmax, vec_max( vmin, vecf2)) ; + // veci3 = vec_min(vmax, vec_max( vmin, vecf3)) ; + + // veci4 = vec_min(vmax, vec_max( vmin, vecf4)) ; + // veci5 = vec_min(vmax, vec_max( vmin, vecf5)) ; + // veci6 = vec_min(vmax, vec_max( vmin, vecf6)) ; + // veci7 = vec_min(vmax, vec_max( vmin, vecf7)) ; + // vec_packs CLAMP already + vint16 vecshi0 = vec_packs(veci0, veci1); + vint16 vecshi1 = vec_packs(veci2, veci3); + vint16 vecshi2 = vec_packs(veci4, veci5); + vint16 vecshi3 = vec_packs(veci6, veci7); + + vint8 vec0 = vec_packs(vecshi0, vecshi1); + vint8 vec1 = vec_packs(vecshi2, vecshi3); + + return {vec0, vec1}; + } + + Vectorized C10_ALWAYS_INLINE + relu(Vectorized zero_point) const { + return {vec_max(_vec0, zero_point._vec0), vec_max(_vec1, zero_point._vec1)}; + } + + Vectorized C10_ALWAYS_INLINE + relu6(Vectorized zero_point, Vectorized q_six) const { + vint8 max0 = vec_max(_vec0, zero_point._vec0); + vint8 max1 = vec_max(_vec1, zero_point._vec1); + return {vec_min(max0, q_six._vec0), vec_min(max1, q_six._vec1)}; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + vint16 vecshi0 = vec_unpackh(_vec0); + vint16 vecBshi0 = vec_unpackh(b._vec0); + vint16 vecshi1 = vec_unpackl(_vec0); + vint16 vecBshi1 = vec_unpackl(b._vec0); + + vint16 vecshi2 = vec_unpackh(_vec1); + vint16 vecBshi2 = vec_unpackh(b._vec1); + vint16 vecshi3 = vec_unpackl(_vec1); + vint16 vecBshi3 = vec_unpackl(b._vec1); + + vint32 veci0 = vec_unpackh(vecshi0); + vint32 vecBi0 = vec_unpackh(vecBshi0); + vint32 veci1 = vec_unpackl(vecshi0); + vint32 vecBi1 = vec_unpackl(vecBshi0); + + vint32 veci2 = vec_unpackh(vecshi1); + vint32 vecBi2 = vec_unpackh(vecBshi1); + vint32 veci3 = vec_unpackl(vecshi1); + vint32 vecBi3 = vec_unpackl(vecBshi1); + + vint32 veci4 = vec_unpackh(vecshi2); + vint32 vecBi4 = vec_unpackh(vecBshi2); + vint32 veci5 = vec_unpackl(vecshi2); + vint32 vecBi5 = vec_unpackl(vecBshi2); + + vint32 veci6 = vec_unpackh(vecshi3); + vint32 vecBi6 = vec_unpackh(vecBshi3); + vint32 veci7 = vec_unpackl(vecshi3); + vint32 vecBi7 = vec_unpackl(vecBshi3); + + return { + Vectorized(veci0 - vecBi0, veci1 - vecBi1), + Vectorized(veci2 - vecBi2, veci3 - vecBi3), + Vectorized(veci4 - vecBi4, veci5 - vecBi5), + Vectorized(veci6 - vecBi6, veci7 - vecBi7)}; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + vfloat32 vec_multiplier = vec_splats(multiplier); + vint32 vec_zero_point = vec_splats(zero_point); + + Vectorized vi0 = inp[0]; + Vectorized vi1 = inp[1]; + Vectorized vi2 = inp[2]; + Vectorized vi3 = inp[3]; + + vfloat32 vecf0 = vec_float(vi0.vec0()); + vfloat32 vecf1 = vec_float(vi0.vec1()); + vfloat32 vecf2 = vec_float(vi1.vec0()); + vfloat32 vecf3 = vec_float(vi1.vec1()); + + vfloat32 vecf4 = vec_float(vi2.vec0()); + vfloat32 vecf5 = vec_float(vi2.vec1()); + vfloat32 vecf6 = vec_float(vi3.vec0()); + vfloat32 vecf7 = vec_float(vi3.vec1()); + + vecf0 = vec_mul(vecf0, vec_multiplier); + vecf1 = vec_mul(vecf1, vec_multiplier); + vecf2 = vec_mul(vecf2, vec_multiplier); + vecf3 = vec_mul(vecf3, vec_multiplier); + + vecf4 = vec_mul(vecf4, vec_multiplier); + vecf5 = vec_mul(vecf5, vec_multiplier); + vecf6 = vec_mul(vecf6, vec_multiplier); + vecf7 = vec_mul(vecf7, vec_multiplier); + + vecf0 = vec_rint(vecf0); + vecf1 = vec_rint(vecf1); + vecf2 = vec_rint(vecf2); + vecf3 = vec_rint(vecf3); + + vecf4 = vec_rint(vecf4); + vecf5 = vec_rint(vecf5); + vecf6 = vec_rint(vecf6); + vecf7 = vec_rint(vecf7); + + vint32 veci0 = vec_signed(vecf0); + vint32 veci1 = vec_signed(vecf1); + vint32 veci2 = vec_signed(vecf2); + vint32 veci3 = vec_signed(vecf3); + + vint32 veci4 = vec_signed(vecf4); + vint32 veci5 = vec_signed(vecf5); + vint32 veci6 = vec_signed(vecf6); + vint32 veci7 = vec_signed(vecf7); + + veci0 = vec_add(veci0, vec_zero_point); + veci1 = vec_add(veci1, vec_zero_point); + veci2 = vec_add(veci2, vec_zero_point); + veci3 = vec_add(veci3, vec_zero_point); + + veci4 = vec_add(veci4, vec_zero_point); + veci5 = vec_add(veci5, vec_zero_point); + veci6 = vec_add(veci6, vec_zero_point); + veci7 = vec_add(veci7, vec_zero_point); + + vint16 vecshi0 = vec_packs(veci0, veci1); + vint16 vecshi1 = vec_packs(veci2, veci3); + vint16 vecshi2 = vec_packs(veci4, veci5); + vint16 vecshi3 = vec_packs(veci6, veci7); + + vint8 vec0 = vec_packs(vecshi0, vecshi1); + vint8 vec1 = vec_packs(vecshi2, vecshi3); + + return {vec0, vec1}; + } + + DEFINE_MEMBER_OP(operator==, c10::qint8, vec_cmpeq) + DEFINE_MEMBER_OP(operator!=, c10::qint8, vec_cmpne) + DEFINE_MEMBER_OP(operator<, c10::qint8, vec_cmplt) + DEFINE_MEMBER_OP(operator<=, c10::qint8, vec_cmple) + DEFINE_MEMBER_OP(operator>, c10::qint8, vec_cmpgt) + DEFINE_MEMBER_OP(operator>=, c10::qint8, vec_cmpge) + DEFINE_MEMBER_OP(operator+, c10::qint8, vec_add) + DEFINE_MEMBER_OP(operator-, c10::qint8, vec_sub) + DEFINE_MEMBER_OP(operator*, c10::qint8, vec_mul) + DEFINE_MEMBER_EMULATE_BINARY_OP(operator/, c10::qint8, /) + DEFINE_MEMBER_OP(maximum, c10::qint8, vec_max) + DEFINE_MEMBER_OP(minimum, c10::qint8, vec_min) + DEFINE_MEMBER_OP(operator&, c10::qint8, vec_and) + DEFINE_MEMBER_OP(operator|, c10::qint8, vec_or) + DEFINE_MEMBER_OP(operator^, c10::qint8, vec_xor) +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return a.minimum(b); +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator+(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_add(a.vec0(), b.vec0()), vec_add(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator-(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_sub(a.vec0(), b.vec0()), vec_sub(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator*(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_mul(a.vec0(), b.vec0()), vec_mul(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator/(const Vectorized& a, const Vectorized& b) { + return Vectorized{a.vec0() / b.vec0(), a.vec1() / b.vec1()}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator&(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_and(a.vec0(), b.vec0()), vec_and(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator|(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_or(a.vec0(), b.vec0()), vec_or(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator^(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_xor(a.vec0(), b.vec0()), vec_xor(a.vec1(), b.vec1())}; +} + +} // namespace CPU_CAPABILITY +} // namespace vec +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vec256_quint8_vsx.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vec256_quint8_vsx.h new file mode 100644 index 0000000000000000000000000000000000000000..acf454e76774aed540422957c7344a5d1d718807 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vec256_quint8_vsx.h @@ -0,0 +1,533 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +// This file defines Vectorized<> for the quantized types. +// +// +// Currently, we simply use these classes as efficient converters between +// the quantized types and Vectorized, usually in bandwidth-bound cases +// where doing the arithmetic in full-precision is acceptable (e.g. +// elementwise operators). +// +// +// Conversions are as follows: +// Vectorized -> 4x Vectorized +// +// The size of the returned float vector is specified by the special +// constexpr function float_num_vecs. The type of the value returned +// from dequantize (and expected as an argument to quantize) is +// specified by float_vec_return_type. +// +// When writing kernels with these vectors, it is expected that floating- +// point operations will be carried out in a loop over +// Vectorized::float_num_vecs iterations. + +namespace at { +namespace vec { +inline namespace CPU_CAPABILITY { + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +const vint16 mask_unsigned = vec_splats((short int)0xFF); +template <> +struct Vectorized { + private: + union { + struct { + vuint8 _vec0; + vuint8 _vec1; + }; + struct { + vbool8 _vecb0; + vbool8 _vecb1; + }; + + } __attribute__((__may_alias__)); + + public: + Vectorized() = default; + using size_type = int; + static constexpr size_type size() { + return 32; + } + + static constexpr size_t float_num_vecs() { + return 4; + } + static constexpr int int_num_vecs() { + return 4; + } + using float_vec_return_type = std::array, 4>; + using int_vec_return_type = std::array, 4>; + using value_type = typename c10::quint8::underlying; + using vec_internal_type = vuint8; + using vec_internal_mask_type = vbool8; + // Broadcast constructor + C10_ALWAYS_INLINE Vectorized(const c10::quint8& val) + : _vec0(vec_splats(val.val_)), _vec1(vec_splats(val.val_)) {} + + C10_ALWAYS_INLINE Vectorized(const Vectorized& other) + : _vec0{other._vec0}, _vec1(other._vec1) {} + + C10_ALWAYS_INLINE Vectorized(vuint8 v) : _vec0{v}, _vec1{v} {} + C10_ALWAYS_INLINE Vectorized(vbool8 vmask) : _vecb0{vmask}, _vecb1{vmask} {} + C10_ALWAYS_INLINE Vectorized(vuint8 v1, vuint8 v2) : _vec0{v1}, _vec1{v2} {} + C10_ALWAYS_INLINE Vectorized(vbool8 v1, vbool8 v2) : _vecb0{v1}, _vecb1{v2} {} + + C10_ALWAYS_INLINE const vec_internal_type& vec0() const { + return _vec0; + } + C10_ALWAYS_INLINE const vec_internal_type& vec1() const { + return _vec1; + } + + static C10_ALWAYS_INLINE Vectorized loadu( + const void* ptr, + int count = size()) { + if (count == size()) { + return { + vec_vsx_ld(offset0, reinterpret_cast(ptr)), + vec_vsx_ld(offset16, reinterpret_cast(ptr))}; + } + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy(tmp_values, ptr, std::min(count, size()) * sizeof(value_type)); + return {vec_vsx_ld(offset0, tmp_values), vec_vsx_ld(offset16, tmp_values)}; + } + void C10_ALWAYS_INLINE store(void* ptr, int count = size()) const { + if (count == size()) { + vec_vsx_st(_vec0, offset0, reinterpret_cast(ptr)); + vec_vsx_st(_vec1, offset16, reinterpret_cast(ptr)); + } else if (count > 0) { + __at_align__ value_type tmp_values[size()]; + vec_vsx_st(_vec0, offset0, tmp_values); + vec_vsx_st(_vec1, offset16, tmp_values); + std::memcpy( + ptr, tmp_values, std::min(count, size()) * sizeof(value_type)); + } + } + + public: + float_vec_return_type C10_ALWAYS_INLINE dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { + // unpacking unsigned as signed + vint16 vecshi0 = vec_unpackh((vint8)_vec0); + vint16 vecshi1 = vec_unpackl((vint8)_vec0); + + vint16 vecshi2 = vec_unpackh((vint8)_vec1); + vint16 vecshi3 = vec_unpackl((vint8)_vec1); + + // signed -> unsigned + vecshi0 = vec_and(vecshi0, mask_unsigned); + vecshi1 = vec_and(vecshi1, mask_unsigned); + + vecshi2 = vec_and(vecshi2, mask_unsigned); + vecshi3 = vec_and(vecshi3, mask_unsigned); + + vint32 veci0 = vec_unpackh(vecshi0); + vint32 veci1 = vec_unpackl(vecshi0); + + vint32 veci2 = vec_unpackh(vecshi1); + vint32 veci3 = vec_unpackl(vecshi1); + + vint32 veci4 = vec_unpackh(vecshi2); + vint32 veci5 = vec_unpackl(vecshi2); + + vint32 veci6 = vec_unpackh(vecshi3); + vint32 veci7 = vec_unpackl(vecshi3); + + vfloat32 vecf0_0 = vec_float(veci0); + vfloat32 vecf1_0 = vec_float(veci1); + + vfloat32 vecf0_1 = vec_float(veci2); + vfloat32 vecf1_1 = vec_float(veci3); + + vfloat32 vecf0_2 = vec_float(veci4); + vfloat32 vecf1_2 = vec_float(veci5); + + vfloat32 vecf0_3 = vec_float(veci6); + vfloat32 vecf1_3 = vec_float(veci7); + vfloat32 scale_vec0 = scale.vec0(); + vfloat32 scale_vec1 = scale.vec1(); + + vfloat32 zero_point_vec0 = zero_point.vec0(); + vfloat32 zero_point_vec1 = zero_point.vec1(); + + vfloat32 vec_substract_src_zp0_0 = vec_sub(vecf0_0, zero_point_vec0); + vfloat32 vec_substract_src_zp1_0 = vec_sub(vecf1_0, zero_point_vec1); + Vectorized vf0_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_0), + vec_mul(scale_vec1, vec_substract_src_zp1_0)}; + + vfloat32 vec_substract_src_zp0_1 = vec_sub(vecf0_1, zero_point_vec0); + vfloat32 vec_substract_src_zp1_1 = vec_sub(vecf1_1, zero_point_vec1); + Vectorized vf1_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_1), + vec_mul(scale_vec1, vec_substract_src_zp1_1)}; + + vfloat32 vec_substract_src_zp0_2 = vec_sub(vecf0_2, zero_point_vec0); + vfloat32 vec_substract_src_zp1_2 = vec_sub(vecf1_2, zero_point_vec1); + Vectorized vf2_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_2), + vec_mul(scale_vec1, vec_substract_src_zp1_2)}; + + vfloat32 vec_substract_src_zp0_3 = vec_sub(vecf0_3, zero_point_vec0); + vfloat32 vec_substract_src_zp1_3 = vec_sub(vecf1_3, zero_point_vec1); + Vectorized vf3_zp = { + vec_mul(scale_vec0, vec_substract_src_zp0_3), + vec_mul(scale_vec1, vec_substract_src_zp1_3)}; + + return {vf0_zp, vf1_zp, vf2_zp, vf3_zp}; + } + + float_vec_return_type C10_ALWAYS_INLINE + dequantize(Vectorized scale, Vectorized zero_point) const { + // unpacking unsigned as signed + vint16 vecshi0 = vec_unpackh((vint8)_vec0); + vint16 vecshi1 = vec_unpackl((vint8)_vec0); + + vint16 vecshi2 = vec_unpackh((vint8)_vec1); + vint16 vecshi3 = vec_unpackl((vint8)_vec1); + + // signed -> unsigned + vecshi0 = vec_and(vecshi0, mask_unsigned); + vecshi1 = vec_and(vecshi1, mask_unsigned); + + vecshi2 = vec_and(vecshi2, mask_unsigned); + vecshi3 = vec_and(vecshi3, mask_unsigned); + + vint32 veci0 = vec_unpackh(vecshi0); + vint32 veci1 = vec_unpackl(vecshi0); + + vint32 veci2 = vec_unpackh(vecshi1); + vint32 veci3 = vec_unpackl(vecshi1); + + vint32 veci4 = vec_unpackh(vecshi2); + vint32 veci5 = vec_unpackl(vecshi2); + + vint32 veci6 = vec_unpackh(vecshi3); + vint32 veci7 = vec_unpackl(vecshi3); + + vfloat32 vecf0_0 = vec_float(veci0); + vfloat32 vecf1_0 = vec_float(veci1); + + vfloat32 vecf0_1 = vec_float(veci2); + vfloat32 vecf1_1 = vec_float(veci3); + + vfloat32 vecf0_2 = vec_float(veci4); + vfloat32 vecf1_2 = vec_float(veci5); + + vfloat32 vecf0_3 = vec_float(veci6); + vfloat32 vecf1_3 = vec_float(veci7); + vfloat32 scale_vec0 = scale.vec0(); + vfloat32 scale_vec1 = scale.vec1(); + + vfloat32 zero_point0 = zero_point.vec0(); + vfloat32 zero_point1 = zero_point.vec1(); + return { + Vectorized{ + (vecf0_0 - zero_point0) * scale_vec0, + (vecf1_0 - zero_point1) * scale_vec1}, + Vectorized{ + (vecf0_1 - zero_point0) * scale_vec0, + (vecf1_1 - zero_point1) * scale_vec1}, + Vectorized{ + (vecf0_2 - zero_point0) * scale_vec0, + (vecf1_2 - zero_point1) * scale_vec1}, + Vectorized{ + (vecf0_3 - zero_point0) * scale_vec0, + (vecf1_3 - zero_point1) * scale_vec1}}; + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + // constexpr int32_t min_val = std::numeric_limits::min(); + // constexpr int32_t max_val = std::numeric_limits::max(); + + vfloat32 vec_inverse = vec_splats(inverse_scale); + vfloat32 vec_zero_point = vec_splats((float)zero_point); + // vuint32 vmin = vec_splats(min_val); + // vuint32 vmax = vec_splats(max_val); + Vectorized vf0 = rhs[0]; + Vectorized vf1 = rhs[1]; + Vectorized vf2 = rhs[2]; + Vectorized vf3 = rhs[3]; + vfloat32 vecf0 = vf0.vec0(); + vfloat32 vecf1 = vf0.vec1(); + vfloat32 vecf2 = vf1.vec0(); + vfloat32 vecf3 = vf1.vec1(); + + vfloat32 vecf4 = vf2.vec0(); + vfloat32 vecf5 = vf2.vec1(); + vfloat32 vecf6 = vf3.vec0(); + vfloat32 vecf7 = vf3.vec1(); + + vecf0 = vec_mul(vecf0, vec_inverse); + vecf1 = vec_mul(vecf1, vec_inverse); + vecf2 = vec_mul(vecf2, vec_inverse); + vecf3 = vec_mul(vecf3, vec_inverse); + + vecf4 = vec_mul(vecf4, vec_inverse); + vecf5 = vec_mul(vecf5, vec_inverse); + vecf6 = vec_mul(vecf6, vec_inverse); + vecf7 = vec_mul(vecf7, vec_inverse); + + vecf0 = vec_add(vec_rint(vecf0), vec_zero_point); + vecf1 = vec_add(vec_rint(vecf1), vec_zero_point); + vecf2 = vec_add(vec_rint(vecf2), vec_zero_point); + vecf3 = vec_add(vec_rint(vecf3), vec_zero_point); + + vecf4 = vec_add(vec_rint(vecf4), vec_zero_point); + vecf5 = vec_add(vec_rint(vecf5), vec_zero_point); + vecf6 = vec_add(vec_rint(vecf6), vec_zero_point); + vecf7 = vec_add(vec_rint(vecf7), vec_zero_point); + + vint32 veci0 = vec_signed(vecf0); + vint32 veci1 = vec_signed(vecf1); + vint32 veci2 = vec_signed(vecf2); + vint32 veci3 = vec_signed(vecf3); + + vint32 veci4 = vec_signed(vecf4); + vint32 veci5 = vec_signed(vecf5); + vint32 veci6 = vec_signed(vecf6); + vint32 veci7 = vec_signed(vecf7); + + vint16 vecshi0 = vec_packs(veci0, veci1); + vint16 vecshi1 = vec_packs(veci2, veci3); + vint16 vecshi2 = vec_packs(veci4, veci5); + vint16 vecshi3 = vec_packs(veci6, veci7); + + vuint8 vec0 = vec_packsu(vecshi0, vecshi1); + vuint8 vec1 = vec_packsu(vecshi2, vecshi3); + + return {vec0, vec1}; + } + + Vectorized C10_ALWAYS_INLINE + relu(Vectorized zero_point) const { + return {vec_max(_vec0, zero_point._vec0), vec_max(_vec1, zero_point._vec1)}; + } + + Vectorized C10_ALWAYS_INLINE relu6( + Vectorized zero_point, + Vectorized q_six) const { + vuint8 max0 = vec_max(_vec0, zero_point._vec0); + vuint8 max1 = vec_max(_vec1, zero_point._vec1); + return {vec_min(max0, q_six._vec0), vec_min(max1, q_six._vec1)}; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + vint16 vecshi0 = vec_unpackh((vint8)_vec0); + vint16 vecBshi0 = vec_unpackh((vint8)b._vec0); + vint16 vecshi1 = vec_unpackl((vint8)_vec0); + vint16 vecBshi1 = vec_unpackl((vint8)b._vec0); + + vint16 vecshi2 = vec_unpackh((vint8)_vec1); + vint16 vecBshi2 = vec_unpackh((vint8)b._vec1); + vint16 vecshi3 = vec_unpackl((vint8)_vec1); + vint16 vecBshi3 = vec_unpackl((vint8)b._vec1); + + vecshi0 = vec_and(vecshi0, mask_unsigned); + vecBshi0 = vec_and(vecBshi0, mask_unsigned); + vecshi1 = vec_and(vecshi1, mask_unsigned); + vecBshi1 = vec_and(vecBshi1, mask_unsigned); + + vecshi2 = vec_and(vecshi2, mask_unsigned); + vecBshi2 = vec_and(vecBshi2, mask_unsigned); + vecshi3 = vec_and(vecshi3, mask_unsigned); + vecBshi3 = vec_and(vecBshi3, mask_unsigned); + + vint32 veci0 = vec_unpackh(vecshi0); + vint32 vecBi0 = vec_unpackh(vecBshi0); + vint32 veci1 = vec_unpackl(vecshi0); + vint32 vecBi1 = vec_unpackl(vecBshi0); + + vint32 veci2 = vec_unpackh(vecshi1); + vint32 vecBi2 = vec_unpackh(vecBshi1); + vint32 veci3 = vec_unpackl(vecshi1); + vint32 vecBi3 = vec_unpackl(vecBshi1); + + vint32 veci4 = vec_unpackh(vecshi2); + vint32 vecBi4 = vec_unpackh(vecBshi2); + vint32 veci5 = vec_unpackl(vecshi2); + vint32 vecBi5 = vec_unpackl(vecBshi2); + + vint32 veci6 = vec_unpackh(vecshi3); + vint32 vecBi6 = vec_unpackh(vecBshi3); + vint32 veci7 = vec_unpackl(vecshi3); + vint32 vecBi7 = vec_unpackl(vecBshi3); + + return { + Vectorized(veci0 - vecBi0, veci1 - vecBi1), + Vectorized(veci2 - vecBi2, veci3 - vecBi3), + Vectorized(veci4 - vecBi4, veci5 - vecBi5), + Vectorized(veci6 - vecBi6, veci7 - vecBi7)}; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + vfloat32 vec_multiplier = vec_splats(multiplier); + vint32 vec_zero_point = vec_splats(zero_point); + + Vectorized vi0 = inp[0]; + Vectorized vi1 = inp[1]; + Vectorized vi2 = inp[2]; + Vectorized vi3 = inp[3]; + + vfloat32 vecf0 = vec_float(vi0.vec0()); + vfloat32 vecf1 = vec_float(vi0.vec1()); + vfloat32 vecf2 = vec_float(vi1.vec0()); + vfloat32 vecf3 = vec_float(vi1.vec1()); + + vfloat32 vecf4 = vec_float(vi2.vec0()); + vfloat32 vecf5 = vec_float(vi2.vec1()); + vfloat32 vecf6 = vec_float(vi3.vec0()); + vfloat32 vecf7 = vec_float(vi3.vec1()); + + vecf0 = vec_mul(vecf0, vec_multiplier); + vecf1 = vec_mul(vecf1, vec_multiplier); + vecf2 = vec_mul(vecf2, vec_multiplier); + vecf3 = vec_mul(vecf3, vec_multiplier); + + vecf4 = vec_mul(vecf4, vec_multiplier); + vecf5 = vec_mul(vecf5, vec_multiplier); + vecf6 = vec_mul(vecf6, vec_multiplier); + vecf7 = vec_mul(vecf7, vec_multiplier); + + vecf0 = vec_rint(vecf0); + vecf1 = vec_rint(vecf1); + vecf2 = vec_rint(vecf2); + vecf3 = vec_rint(vecf3); + + vecf4 = vec_rint(vecf4); + vecf5 = vec_rint(vecf5); + vecf6 = vec_rint(vecf6); + vecf7 = vec_rint(vecf7); + + vint32 veci0 = vec_signed(vecf0); + vint32 veci1 = vec_signed(vecf1); + vint32 veci2 = vec_signed(vecf2); + vint32 veci3 = vec_signed(vecf3); + + vint32 veci4 = vec_signed(vecf4); + vint32 veci5 = vec_signed(vecf5); + vint32 veci6 = vec_signed(vecf6); + vint32 veci7 = vec_signed(vecf7); + + veci0 = vec_add(veci0, vec_zero_point); + veci1 = vec_add(veci1, vec_zero_point); + veci2 = vec_add(veci2, vec_zero_point); + veci3 = vec_add(veci3, vec_zero_point); + + veci4 = vec_add(veci4, vec_zero_point); + veci5 = vec_add(veci5, vec_zero_point); + veci6 = vec_add(veci6, vec_zero_point); + veci7 = vec_add(veci7, vec_zero_point); + + vint16 vecshi0 = vec_packs(veci0, veci1); + vint16 vecshi1 = vec_packs(veci2, veci3); + vint16 vecshi2 = vec_packs(veci4, veci5); + vint16 vecshi3 = vec_packs(veci6, veci7); + + vuint8 vec0 = vec_packsu(vecshi0, vecshi1); + vuint8 vec1 = vec_packsu(vecshi2, vecshi3); + + return {vec0, vec1}; + } + + DEFINE_MEMBER_OP(operator==, c10::quint8, vec_cmpeq) + DEFINE_MEMBER_OP(operator!=, c10::quint8, vec_cmpne) + DEFINE_MEMBER_OP(operator<, c10::quint8, vec_cmplt) + DEFINE_MEMBER_OP(operator<=, c10::quint8, vec_cmple) + DEFINE_MEMBER_OP(operator>, c10::quint8, vec_cmpgt) + DEFINE_MEMBER_OP(operator>=, c10::quint8, vec_cmpge) + DEFINE_MEMBER_OP(operator+, c10::quint8, vec_add) + DEFINE_MEMBER_OP(operator-, c10::quint8, vec_sub) + DEFINE_MEMBER_OP(operator*, c10::quint8, vec_mul) + DEFINE_MEMBER_EMULATE_BINARY_OP(operator/, c10::quint8, /) + DEFINE_MEMBER_OP(maximum, c10::quint8, vec_max) + DEFINE_MEMBER_OP(minimum, c10::quint8, vec_min) + DEFINE_MEMBER_OP(operator&, c10::quint8, vec_and) + DEFINE_MEMBER_OP(operator|, c10::quint8, vec_or) + DEFINE_MEMBER_OP(operator^, c10::quint8, vec_xor) +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return a.minimum(b); +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator+(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_add(a.vec0(), b.vec0()), vec_add(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator-(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_sub(a.vec0(), b.vec0()), vec_sub(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator*(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_mul(a.vec0(), b.vec0()), vec_mul(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator/(const Vectorized& a, const Vectorized& b) { + return Vectorized{a.vec0() / b.vec0(), a.vec1() / b.vec1()}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator&(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_and(a.vec0(), b.vec0()), vec_and(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator|(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_or(a.vec0(), b.vec0()), vec_or(a.vec1(), b.vec1())}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +operator^(const Vectorized& a, const Vectorized& b) { + return Vectorized{ + vec_xor(a.vec0(), b.vec0()), vec_xor(a.vec1(), b.vec1())}; +} + +} // namespace CPU_CAPABILITY +} // namespace vec +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vsx_helpers.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vsx_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..eefb9b227ceb5d871a8b86003befc87118959826 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/vsx/vsx_helpers.h @@ -0,0 +1,576 @@ +#pragma once +#include +#include +#include +#include + +#if defined(__clang__) +typedef __vector __bool char vbool8; +typedef __vector __bool short vbool16; +typedef __vector __bool int vbool32; +typedef __vector __bool long long vbool64; +using vint8 = __attribute__((vector_size(16))) signed char; +using vint16 = __attribute__((vector_size(16))) signed short; +using vint32 = __attribute__((vector_size(16))) signed int; +using vint64 = __attribute__((vector_size(16))) signed long long; +using vuint8 = __attribute__((vector_size(16))) unsigned char; +using vuint16 = __attribute__((vector_size(16))) unsigned short; +using vuint32 = __attribute__((vector_size(16))) unsigned int; +using vuint64 = __attribute__((vector_size(16))) unsigned long long; +using vfloat32 = __attribute__((vector_size(16))) float; +using vfloat64 = __attribute__((vector_size(16))) double; +#else +using vbool8 = + __attribute__((altivec(vector__))) __attribute__((altivec(bool__))) char; +using vbool16 = + __attribute__((altivec(vector__))) __attribute__((altivec(bool__))) short; +using vbool32 = + __attribute__((altivec(vector__))) __attribute__((altivec(bool__))) int; +using vbool64 = __attribute__((altivec(vector__))) +__attribute__((altivec(bool__))) long long; +using vint8 = __attribute__((altivec(vector__))) signed char; +using vint16 = __attribute__((altivec(vector__))) signed short; +using vint32 = __attribute__((altivec(vector__))) signed int; +using vint64 = __attribute__((altivec(vector__))) signed long long; +using vuint8 = __attribute__((altivec(vector__))) unsigned char; +using vuint16 = __attribute__((altivec(vector__))) unsigned short; +using vuint32 = __attribute__((altivec(vector__))) unsigned int; +using vuint64 = __attribute__((altivec(vector__))) unsigned long long; +using vfloat32 = __attribute__((altivec(vector__))) float; +using vfloat64 = __attribute__((altivec(vector__))) double; +#endif + +inline auto make_vuint(vint8 v) { + return reinterpret_cast(v); +} +inline auto make_vuint(vint16 v) { + return reinterpret_cast(v); +} +inline auto make_vuint(vint32 v) { + return reinterpret_cast(v); +} +inline auto make_vuint(vint64 v) { + return reinterpret_cast(v); +} + +#if !defined(vec_float) +C10_ALWAYS_INLINE vfloat32 vec_float(const vint32& vec_in) { + vfloat32 vec_out; + __asm__("xvcvsxwsp %x0,%x1" : "=wf"(vec_out) : "wa"(vec_in)); + return vec_out; +} +#endif + +#if !defined(vec_signed) +C10_ALWAYS_INLINE vint32 vec_signed(const vfloat32& vec_in) { + vint32 vec_out; + __asm__("xvcvspsxws %x0,%x1" : "=wa"(vec_out) : "wf"(vec_in)); + return vec_out; +} + +C10_ALWAYS_INLINE vint64 vec_signed(const vfloat64& vec_in) { + vint64 vec_out; + __asm__("xvcvdpsxds %x0,%x1" : "=wa"(vec_out) : "wd"(vec_in)); + return vec_out; +} +#endif + +#if !defined(vec_neg) +C10_ALWAYS_INLINE vfloat32 vec_neg(const vfloat32& vec_in) { + vfloat32 vec_out; + __asm__("xvnegsp %x0,%x1" : "=wf"(vec_out) : "wf"(vec_in)); + return vec_out; +} + +C10_ALWAYS_INLINE vfloat64 vec_neg(const vfloat64& vec_in) { + vfloat64 vec_out; + __asm__("xvnegdp %x0,%x1" : "=wd"(vec_out) : "wd"(vec_in)); + return vec_out; +} + +C10_ALWAYS_INLINE vint16 vec_neg(const vint16& vec_in) { + vint16 vint0 = {0, 0, 0, 0, 0, 0, 0, 0}; + return vec_vsubuhm(vint0, vec_in); +} + +C10_ALWAYS_INLINE vint32 vec_neg(const vint32& vec_in) { + vint32 vint0 = {0, 0, 0, 0}; + return vec_vsubuwm(vint0, vec_in); +} + +C10_ALWAYS_INLINE vint64 vec_neg(const vint64& vec_in) { + return -vec_in; +} +#endif + +#if !defined(vec_sldw) +template +C10_ALWAYS_INLINE vfloat32 +vec_sldw_aux(const vfloat32& vec_in0, const vfloat32& vec_in1) { + vfloat32 vec_out; + __asm("xxsldwi %x0, %x1, %x2, %3 " + : "=wa"(vec_out) + : "wa"(vec_in0), "wa"(vec_in1), "I"(C)); + return vec_out; +} + +#define vec_sldw(a, b, c) vec_sldw_aux(a, b) +#endif + +#define vec_not(a) vec_nor(a, a) +#if defined(__clang__) && !defined(vec_splats) +C10_ALWAYS_INLINE vint64 vec_splats(const int64_t& a) { + return vec_splats(a); +} +#endif +// Vectorized min/max which return a if any operand is nan +template +C10_ALWAYS_INLINE T vec_min_nan(const T& a, const T& b) { + return vec_min(a, b); +} +template +C10_ALWAYS_INLINE T vec_max_nan(const T& a, const T& b) { + return vec_max(a, b); +} + +// Specializations for float/double taken from Eigen +template <> +C10_ALWAYS_INLINE vfloat32 +vec_min_nan(const vfloat32& a, const vfloat32& b) { + // NOTE: about 10% slower than vec_min, but consistent with std::min and SSE + // regarding NaN + vfloat32 ret; + __asm__("xvcmpgesp %x0,%x1,%x2\n\txxsel %x0,%x1,%x2,%x0" + : "=&wa"(ret) + : "wa"(a), "wa"(b)); + return ret; +} +// Specializations for float/double taken from Eigen +template <> +C10_ALWAYS_INLINE vfloat32 +vec_max_nan(const vfloat32& a, const vfloat32& b) { + // NOTE: about 10% slower than vec_max, but consistent with std::min and SSE + // regarding NaN + vfloat32 ret; + __asm__("xvcmpgtsp %x0,%x2,%x1\n\txxsel %x0,%x1,%x2,%x0" + : "=&wa"(ret) + : "wa"(a), "wa"(b)); + return ret; +} + +template <> +C10_ALWAYS_INLINE vfloat64 +vec_min_nan(const vfloat64& a, const vfloat64& b) { + // NOTE: about 10% slower than vec_min, but consistent with std::min and SSE + // regarding NaN + vfloat64 ret; + __asm__("xvcmpgedp %x0,%x1,%x2\n\txxsel %x0,%x1,%x2,%x0" + : "=&wa"(ret) + : "wa"(a), "wa"(b)); + return ret; +} +template <> +C10_ALWAYS_INLINE vfloat64 +vec_max_nan(const vfloat64& a, const vfloat64& b) { + // NOTE: about 10% slower than vec_max, but consistent with std::max and SSE + // regarding NaN + vfloat64 ret; + __asm__("xvcmpgtdp %x0,%x2,%x1\n\txxsel %x0,%x1,%x2,%x0" + : "=&wa"(ret) + : "wa"(a), "wa"(b)); + return ret; +} + +// Vectorizes min/max function which returns nan if any side is nan +#define C10_VSX_VEC_NAN_PROPAG(name, type, btype, func) \ + C10_ALWAYS_INLINE type name(const type& a, const type& b) { \ + type tmp = func(a, b); \ + btype nan_a = vec_cmpne(a, a); \ + btype nan_b = vec_cmpne(b, b); \ + tmp = vec_sel(tmp, a, nan_a); \ + return vec_sel(tmp, b, nan_b); \ + } + +C10_VSX_VEC_NAN_PROPAG(vec_min_nan2, vfloat32, vbool32, vec_min) +C10_VSX_VEC_NAN_PROPAG(vec_max_nan2, vfloat32, vbool32, vec_max) +C10_VSX_VEC_NAN_PROPAG(vec_min_nan2, vfloat64, vbool64, vec_min) +C10_VSX_VEC_NAN_PROPAG(vec_max_nan2, vfloat64, vbool64, vec_max) + +#undef C10_VSX_VEC_NAN_PROPAG + +#define DEFINE_MEMBER_UNARY_OP(op, op_type, func) \ + Vectorized C10_ALWAYS_INLINE op() const { \ + return Vectorized{func(_vec0), func(_vec1)}; \ + } + +#define DEFINE_MEMBER_OP(op, op_type, func) \ + Vectorized C10_ALWAYS_INLINE op(const Vectorized& other) \ + const { \ + return Vectorized{ \ + func(_vec0, other._vec0), func(_vec1, other._vec1)}; \ + } + +#define DEFINE_MEMBER_BITWISE_OP(op, op_type, func) \ + Vectorized C10_ALWAYS_INLINE op(const Vectorized& other) \ + const { \ + return Vectorized{ \ + func(_vecb0, other._vecb0), func(_vecb1, other._vecb1)}; \ + } + +#define DEFINE_MEMBER_TERNARY_OP(op, op_type, func) \ + Vectorized C10_ALWAYS_INLINE op( \ + const Vectorized& b, const Vectorized& c) const { \ + return Vectorized{ \ + func(_vec0, b._vec0, c._vec0), func(_vec1, b._vec1, c._vec1)}; \ + } + +#define DEFINE_MEMBER_EMULATE_BINARY_OP(op, op_type, binary_op) \ + Vectorized C10_ALWAYS_INLINE op(const Vectorized& b) \ + const { \ + Vectorized::vec_internal_type ret_0; \ + Vectorized::vec_internal_type ret_1; \ + for (int i = 0; i < Vectorized::size() / 2; i++) { \ + ret_0[i] = _vec0[i] binary_op b._vec0[i]; \ + ret_1[i] = _vec1[i] binary_op b._vec1[i]; \ + } \ + return Vectorized{ret_0, ret_1}; \ + } + +#define DEFINE_MEMBER_OP_AND_ONE(op, op_type, func) \ + Vectorized C10_ALWAYS_INLINE op(const Vectorized& other) \ + const { \ + using vvtype = Vectorized::vec_internal_type; \ + const vvtype v_one = vec_splats(static_cast(1.0)); \ + vvtype ret0 = (vvtype)func(_vec0, other._vec0); \ + vvtype ret1 = (vvtype)func(_vec1, other._vec1); \ + return Vectorized{vec_and(ret0, v_one), vec_and(ret1, v_one)}; \ + } + +#define DEFINE_CLAMP_FUNCS(operand_type) \ + template <> \ + Vectorized C10_ALWAYS_INLINE clamp( \ + const Vectorized& a, \ + const Vectorized& min, \ + const Vectorized& max) { \ + return Vectorized{ \ + vec_min_nan(vec_max_nan(a.vec0(), min.vec0()), max.vec0()), \ + vec_min_nan(vec_max_nan(a.vec1(), min.vec1()), max.vec1())}; \ + } \ + template <> \ + Vectorized C10_ALWAYS_INLINE clamp_min( \ + const Vectorized& a, \ + const Vectorized& min) { \ + return Vectorized{ \ + vec_max_nan(a.vec0(), min.vec0()), vec_max_nan(a.vec1(), min.vec1())}; \ + } \ + template <> \ + Vectorized C10_ALWAYS_INLINE clamp_max( \ + const Vectorized& a, \ + const Vectorized& max) { \ + return Vectorized{ \ + vec_min_nan(a.vec0(), max.vec0()), vec_min_nan(a.vec1(), max.vec1())}; \ + } + +#define DEFINE_REINTERPRET_CAST_FUNCS( \ + first_type, cast_type, cast_inner_vector_type) \ + template <> \ + C10_ALWAYS_INLINE Vectorized cast( \ + const Vectorized& src) { \ + return Vectorized{ \ + (cast_inner_vector_type)src.vec0(), \ + (cast_inner_vector_type)src.vec1()}; \ + } + +#define DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(first_type) \ + DEFINE_REINTERPRET_CAST_FUNCS(first_type, double, vfloat64) \ + DEFINE_REINTERPRET_CAST_FUNCS(first_type, float, vfloat32) \ + DEFINE_REINTERPRET_CAST_FUNCS(first_type, int64_t, vint64) \ + DEFINE_REINTERPRET_CAST_FUNCS(first_type, int32_t, vint32) \ + DEFINE_REINTERPRET_CAST_FUNCS(first_type, int16_t, vint16) + +// it can be used to emulate blend faster +constexpr int blendChoice( + uint32_t mask, + uint32_t half1 = 0xF, + uint32_t half2 = 0xF0) { + uint32_t none = 0; + uint32_t both = half1 | half2; + // clamp it between 0 and both + mask = mask & both; + // return (a._vec0, a._vec1) + if (mask == none) + return 0; + // return (b._vec0,b._vec1) + else if (mask == both) + return 1; + // return (b._vec0,a._vec1) + else if (mask == half1) + return 2; + // return (a._vec0,b._vec1) + else if (mask == half2) + return 3; + // return (*_vec0,a._vec1) + else if (mask > 0 && mask < half1) + return 4; + // return (*_vec0,b._vec1) + else if ((mask & half2) == half2) + return 5; + // return (a._vec0,*_vec1) + else if ((mask & half1) == 0 && mask > half1) + return 6; + // return (b._vec0,*_vec1) + else if ((mask & half1) == half1 && mask > half1) + return 7; + // return (*_vec0,*_vec1) + return 8; +} + +// it can be used to emulate blend faster +constexpr int blendChoiceDbl(uint32_t mask) { + // clamp it 0 and 0xF + return blendChoice(mask, 0x3, 0xC); +} + +constexpr vbool32 VsxMask1(uint32_t mask) { + uint32_t g0 = (mask & 1) * 0xffffffff; + uint32_t g1 = ((mask & 2) >> 1) * 0xffffffff; + uint32_t g2 = ((mask & 4) >> 2) * 0xffffffff; + uint32_t g3 = ((mask & 8) >> 3) * 0xffffffff; + return (vbool32){g0, g1, g2, g3}; +} + +constexpr vbool32 VsxMask2(uint32_t mask) { + uint32_t mask2 = (mask & 0xFF) >> 4; + return VsxMask1(mask2); +} + +constexpr vbool64 VsxDblMask1(uint32_t mask) { + uint64_t g0 = (mask & 1) * 0xffffffffffffffff; + uint64_t g1 = ((mask & 2) >> 1) * 0xffffffffffffffff; + return (vbool64){g0, g1}; +} + +constexpr vbool64 VsxDblMask2(uint32_t mask) { + uint32_t mask2 = (mask & 0xF) >> 2; + return VsxDblMask1(mask2); +} + +constexpr int maskForComplex(uint32_t mask) { + mask = mask & 0xF; + int complex_mask = 0; + if (mask & 1) + complex_mask |= 3; + if (mask & 2) + complex_mask |= (3 << 2); + if (mask & 4) + complex_mask |= (3 << 4); + if (mask & 8) + complex_mask |= (3 << 6); + return complex_mask; +} + +constexpr int maskForComplexDbl(uint32_t mask) { + mask = mask & 0x3; + int complex_mask = 0; + if (mask & 1) + complex_mask |= 3; + if (mask & 2) + complex_mask |= (3 << 2); + return complex_mask; +} + +constexpr int blendChoiceComplex(uint32_t mask) { + return blendChoice(maskForComplex(mask)); +} + +constexpr int blendChoiceComplexDbl(uint32_t mask) { + return blendChoiceDbl(maskForComplexDbl(mask)); +} + +constexpr vbool32 VsxComplexMask1(uint32_t mask) { + return VsxMask1(maskForComplex(mask)); +} + +constexpr vbool32 VsxComplexMask2(uint32_t mask) { + uint32_t mask2 = (mask & 0xF) >> 2; + return VsxMask1(maskForComplex(mask2)); +} + +constexpr vbool64 VsxComplexDblMask1(uint32_t mask) { + return VsxDblMask1(mask); +} + +constexpr vbool64 VsxComplexDblMask2(uint32_t mask) { + uint32_t mask2 = (mask & 0xF) >> 2; + return VsxDblMask1(mask2); +} + +// constants +namespace at { +namespace vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { +// +constexpr int offset0 = 0; +constexpr int offset16 = 16; + +// #Constants +const vuint8 mask_zero_bits = vuint8{ + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 96, + 64, + 32, + 0}; + +const vuint8 swap_mask = + vuint8{4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11}; + +const vint32 v0x7f = vec_splats(0x7f); +const vint32 vi_0 = vec_splats((int)(0)); +const vint32 vi_1 = vec_splats((int)1); +const vint32 vi_2 = vec_splats((int)2); +const vint32 vi_4 = vec_splats((int)4); +const vint32 vi_inv1 = vec_splats((int)~1); +const vuint32 vu_29 = vec_splats(29u); +const vuint32 vu_23 = vec_splats(23u); + +const vbool32 inv_mant_mask = (vbool32)vec_splats((unsigned int)~0xff800000); +const vbool32 sign_mask = (vbool32)vec_splats((int)0x80000000); +const vbool32 real_mask = vbool32{0xFFFFFFFF, 0x0, 0xFFFFFFFF, 0x0}; +const vbool32 imag_mask = vbool32{0x0, 0xFFFFFFFF, 0x0, 0xFFFFFFFF}; +const vbool32 isign_mask = vbool32{0x0, 0x80000000, 0x0, 0x80000000}; +const vbool32 rsign_mask = vbool32{0x80000000, 0x0, 0x80000000, 0x0}; + +const vbool64 vd_sign_mask = vbool64{0x8000000000000000, 0x8000000000000000}; +const vbool64 vd_imag_mask = vbool64{0x0, 0xFFFFFFFFFFFFFFFF}; +const vbool64 vd_real_mask = vbool64{0xFFFFFFFFFFFFFFFF, 0x0}; +const vbool64 vd_isign_mask = vbool64{0x0, 0x8000000000000000}; +const vbool64 vd_rsign_mask = vbool64{0x8000000000000000, 0x0}; + +const vfloat32 zero = vec_splats(0.f); +const vfloat32 half = vec_splats(0.5f); +const vfloat32 one = vec_splats(1.f); +const vfloat32 two = vec_splats(2.0f); +const vfloat32 _4div_pi = vec_splats(1.27323954473516f); +const vfloat32 v_inf = (vfloat32)vec_splats(0x7f800000u); +const vfloat32 v_minus_inf = + vfloat32{0xff800000u, 0xff800000u, 0xff800000u, 0xff800000u}; +const vfloat32 v_nan = (vfloat32)vec_splats(0x7fffffff); +const vfloat32 log10e_inv = vec_splats(0.43429448190325176f); +const vfloat32 log2e_inv = vec_splats(1.4426950408889634f); +const vfloat32 log2eB_inv = vec_splats(1.442695036924675f); +const vfloat32 cephes_SQRTHF = vec_splats(0.707106781186547524f); +const vfloat32 coscof_p0 = vec_splats(2.443315711809948E-005f); +const vfloat32 coscof_p1 = vec_splats(-1.388731625493765E-003f); +const vfloat32 coscof_p2 = vec_splats(4.166664568298827E-002f); +const vfloat32 exp_hi = vec_splats(104.f); +const vfloat32 exp_lo = vec_splats(-104.f); +const vfloat32 exp_p0 = vec_splats(0.000198527617612853646278381f); +const vfloat32 exp_p1 = vec_splats((0.00139304355252534151077271f)); +const vfloat32 exp_p2 = vec_splats(0.00833336077630519866943359f); +const vfloat32 exp_p3 = vec_splats(0.0416664853692054748535156f); +const vfloat32 exp_p4 = vec_splats(0.166666671633720397949219f); +const vfloat32 exp_p5 = vec_splats(0.5f); +const vfloat32 log_p0 = vec_splats(7.0376836292E-2f); +const vfloat32 log_p1 = vec_splats(-1.1514610310E-1f); +const vfloat32 log_p2 = vec_splats(1.1676998740E-1f); +const vfloat32 log_p3 = vec_splats(-1.2420140846E-1f); +const vfloat32 log_p4 = vec_splats(+1.4249322787E-1f); +const vfloat32 log_p5 = vec_splats(-1.6668057665E-1f); +const vfloat32 log_p6 = vec_splats(+2.0000714765E-1f); +const vfloat32 log_p7 = vec_splats(-2.4999993993E-1f); +const vfloat32 log_p8 = vec_splats(+3.3333331174E-1f); +const vfloat32 log_q1 = vec_splats(-2.12194440e-4f); +const vfloat32 log_q2 = vec_splats(0.693359375f); +const vfloat32 max_logf = vec_splats(88.02969187150841f); +const vfloat32 max_numf = + vec_splats(1.7014117331926442990585209174225846272e38f); +const vfloat32 min_inf = (vfloat32)vec_splats(0xff800000u); +const vfloat32 min_norm_pos = (vfloat32)vec_splats(0x0800000u); +const vfloat32 minus_cephes_dp1 = vec_splats(-0.78515625f); +const vfloat32 minus_cephes_dp2 = vec_splats(-2.4187564849853515625e-4f); +const vfloat32 minus_cephes_dp3 = vec_splats(-3.77489497744594108e-8f); +const vfloat32 negln2f_hi = vec_splats(-0.693145751953125f); +const vfloat32 negln2f_lo = vec_splats(-1.428606765330187045e-06f); +const vfloat32 p0 = vec_splats(2.03721912945E-4f); +const vfloat32 p1 = vec_splats(8.33028376239E-3f); +const vfloat32 p2 = vec_splats(1.66667160211E-1f); +const vfloat32 sincof_p0 = vec_splats(-1.9515295891E-4f); +const vfloat32 sincof_p1 = vec_splats(8.3321608736E-3f); +const vfloat32 sincof_p2 = vec_splats(-1.6666654611E-1f); +const vfloat32 tanh_0p625 = vec_splats(0.625f); +const vfloat32 tanh_half_max = vec_splats(44.014845935754205f); +const vfloat32 tanh_p0 = vec_splats(-5.70498872745E-3f); +const vfloat32 tanh_p1 = vec_splats(2.06390887954E-2f); +const vfloat32 tanh_p2 = vec_splats(-5.37397155531E-2f); +const vfloat32 tanh_p3 = vec_splats(1.33314422036E-1f); +const vfloat32 tanh_p4 = vec_splats(-3.33332819422E-1f); +const vfloat32 vcheck = vec_splats((float)(1LL << 24)); +const vfloat32 imag_one = vfloat32{0.f, 1.f, 0.f, 1.f}; +const vfloat32 imag_half = vfloat32{0.f, 0.5f, 0.f, 0.5f}; +const vfloat32 sqrt2_2 = vfloat32{ + 0.70710676908493042f, + 0.70710676908493042, + 0.70710676908493042, + 0.70710676908493042}; +const vfloat32 pi_2 = vfloat32{M_PI / 2, 0.0, M_PI / 2, 0.0}; +const vfloat32 vf_89 = vfloat32{89.f, 89.f, 89.f, 89.f}; +const vfloat64 vd_one = vec_splats(1.0); +const vfloat64 vd_zero = vec_splats(0.0); +const vfloat64 vd_log10e_inv = vec_splats(0.43429448190325176); +const vfloat64 vd_log2e_inv = vec_splats(1.4426950408889634); +const vfloat64 vd_imag_one = vfloat64{0.0, 1.0}; +const vfloat64 vd_imag_half = vfloat64{0.0, 0.5}; +const vfloat64 vd_sqrt2_2 = vfloat64{0.70710678118654757, 0.70710678118654757}; +const vfloat64 vd_pi_2 = vfloat64{M_PI / 2.0, 0.0}; + +template +Vectorized VsxShiftRightArith( + const Vectorized& a, + const Vectorized& b) { + const Vectorized max_shift(sizeof(T) * CHAR_BIT - std::is_signed_v); + const auto mask = (b < Vectorized(0)) | (b >= max_shift); + const auto shift = Vectorized::blendv(b, max_shift, mask); + return Vectorized{ + vec_sra(a.vec0(), make_vuint(shift.vec0())), + vec_sra(a.vec1(), make_vuint(shift.vec1()))}; +} + +template +Vectorized VsxShiftLeftArith( + const Vectorized& a, + const Vectorized& b) { + const Vectorized max_shift(sizeof(T) * CHAR_BIT); + const auto mask = (b < Vectorized(0)) | (b >= max_shift); + Vectorized ret( + vec_sl(a.vec0(), make_vuint(b.vec0())), + vec_sl(a.vec1(), make_vuint(b.vec1()))); + return Vectorized::blendv(ret, Vectorized(0), mask); +} + +#define DEFINE_SHIFT_FUNCS(operand_type) \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator>>( \ + const Vectorized& a, const Vectorized& b) { \ + return VsxShiftRightArith(a, b); \ + } \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator<<( \ + const Vectorized& a, const Vectorized& b) { \ + return VsxShiftLeftArith(a, b); \ + } + +} // namespace CPU_CAPABILITY +} // namespace vec +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/zarch/vec256_zarch.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/zarch/vec256_zarch.h new file mode 100644 index 0000000000000000000000000000000000000000..9886f44f62249c3ac15a9630c7b5854563847e44 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec256/zarch/vec256_zarch.h @@ -0,0 +1,2984 @@ +#include +#include +#include +#include +#include +#if defined(__clang__) +#include +#elif defined(__GNUC__) || defined(__GNUG__) +#include +#include +#endif +#include +#include +#include + +namespace at { +namespace vec { + +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +template +constexpr bool is_zarch_implemented() { + return ( + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v); +} + +template +constexpr bool is_zarch_implemented_quant() { + return ( + std::is_same_v || std::is_same_v || + std::is_same_v); +} + +template +constexpr bool is_zarch_implemented_complex() { + return std::is_same_v> || + std::is_same_v>; +} + +constexpr int offset0 = 0; +constexpr int offset16 = 16; + +template +struct VecBinaryType { + using type __attribute__((vector_size(16))) = uintmax_t; +}; + +template <> +struct VecBinaryType<8> { + using type = __attribute__((vector_size(16))) unsigned long long; +}; + +template <> +struct VecBinaryType<4> { + using type = __attribute__((vector_size(16))) unsigned int; +}; + +template <> +struct VecBinaryType<2> { + using type = __attribute__((vector_size(16))) unsigned short; +}; + +template <> +struct VecBinaryType<1> { + using type = __attribute__((vector_size(16))) unsigned char; +}; + +template +struct VecInnerType { + using Type __attribute__((vector_size(16))) = T; + using BinaryType = typename VecBinaryType::type; + using ElementType = T; + static constexpr int size = 16 / sizeof(T); +}; + +// define for int64_t properly for load +template <> +struct VecInnerType { + using Type = __attribute__((vector_size(16))) signed long long; + using ElementType = signed long long; + using BinaryType = typename VecBinaryType::type; + static constexpr int size = 16 / sizeof(signed long long); +}; + +template +using ZSimdVect = typename VecInnerType::Type; +template +using ZSimdVectBinary = typename VecInnerType::BinaryType; +template +using ZSimdVectElement = typename VecInnerType::ElementType; + +constexpr int blendChoiceInner( + const uint64_t mask, + const uint64_t half1 = 0xF, + const uint64_t half2 = 0xF0) { + uint64_t none = 0; + uint64_t both = half1 | half2; + // clamp it between 0 and both + auto res_mask = mask & both; + // return (a._vec0, a._vec1) + if (res_mask == none) + return 0; + // return (b._vec0,b._vec1) + else if (res_mask == both) + return 1; + // return (b._vec0, a._vec1) + else if (res_mask == half1) + return 2; + // return (a._vec0,b._vec1) + else if (res_mask == half2) + return 3; + // return (*_vec0,a._vec1) + else if (res_mask > 0 && res_mask < half1) + return 4; + // return (*_vec0,b._vec1) + else if ((res_mask & half2) == half2) + return 5; + // return (a._vec0,*_vec1) + else if ((res_mask & half1) == 0 && res_mask > half1) + return 6; + // return (b._vec0,*_vec1) + else if ((res_mask & half1) == half1 && res_mask > half1) + return 7; + // return (*_vec0,*_vec1) + return 8; +} + +// it can be used to emulate blend faster +template +constexpr int blendChoice(const uint64_t mask) { + static_assert(Z < 1 || Z > 8, "not implemented"); + return blendChoiceInner(mask); +} + +template <> +constexpr int blendChoice<1>(const uint64_t mask) { + return blendChoiceInner(mask, 0x0000FFFF, 0xFFFF0000); +} + +template <> +constexpr int blendChoice<2>(const uint64_t mask) { + return blendChoiceInner(mask, 0x00FF, 0xFF00); +} + +template <> +constexpr int blendChoice<4>(const uint64_t mask) { + return blendChoiceInner(mask, 0xF, 0xF0); +} + +template <> +constexpr int blendChoice<8>(const uint64_t mask) { + // clamp it 0 and 0xF + return blendChoiceInner(mask, 0x3, 0xC); +} + +template +constexpr auto GetMask1(const uint64_t mask) { + return typename VecBinaryType::type{}; +} + +template +constexpr auto GetMask2(const uint64_t mask) { + return typename VecBinaryType::type{}; +} + +template <> +constexpr auto GetMask1<1>(const uint64_t mask) { + constexpr uint8_t t = (int)0xFF; + uint8_t g0 = (mask & 1) * t; + uint8_t g1 = ((mask & 2) >> 1) * t; + uint8_t g2 = ((mask & 4) >> 2) * t; + uint8_t g3 = ((mask & 8) >> 3) * t; + uint8_t g4 = ((mask & 16) >> 4) * t; + uint8_t g5 = ((mask & 32) >> 5) * t; + uint8_t g6 = ((mask & 64) >> 6) * t; + uint8_t g7 = ((mask & 128) >> 7) * t; + uint8_t g8 = ((mask & 256) >> 8) * t; + uint8_t g9 = ((mask & 512) >> 9) * t; + uint8_t g10 = ((mask & 1024) >> 10) * t; + uint8_t g11 = ((mask & 2048) >> 11) * t; + uint8_t g12 = ((mask & 4096) >> 12) * t; + uint8_t g13 = ((mask & 8192) >> 13) * t; + uint8_t g14 = ((mask & 16384) >> 14) * t; + uint8_t g15 = ((mask & 32768) >> 15) * t; + return (typename VecBinaryType<1>::type){ + g0, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11, g12, g13, g14, g15}; +} + +template <> +constexpr auto GetMask2<1>(const uint64_t mask) { + uint64_t mask2 = (mask & 0xFFFFFFFF) >> 16; + return GetMask1<1>(mask2); +} + +template <> +constexpr auto GetMask1<2>(const uint64_t mask) { + constexpr uint16_t t = (int)0xFFFF; + uint16_t g0 = (mask & 1) * t; + uint16_t g1 = ((mask & 2) >> 1) * t; + uint16_t g2 = ((mask & 4) >> 2) * t; + uint16_t g3 = ((mask & 8) >> 3) * t; + uint16_t g4 = ((mask & 16) >> 4) * t; + uint16_t g5 = ((mask & 32) >> 5) * t; + uint16_t g6 = ((mask & 64) >> 6) * t; + uint16_t g7 = ((mask & 128) >> 7) * t; + return (typename VecBinaryType<2>::type){g0, g1, g2, g3, g4, g5, g6, g7}; +} + +template <> +constexpr auto GetMask2<2>(const uint64_t mask) { + uint64_t mask2 = (mask & 0xFFFF) >> 8; + return GetMask1<2>(mask2); +} + +template <> +constexpr auto GetMask1<4>(const uint64_t mask) { + uint32_t g0 = (mask & 1) * 0xffffffff; + uint32_t g1 = ((mask & 2) >> 1) * 0xffffffff; + uint32_t g2 = ((mask & 4) >> 2) * 0xffffffff; + uint32_t g3 = ((mask & 8) >> 3) * 0xffffffff; + return (typename VecBinaryType<4>::type){g0, g1, g2, g3}; +} + +template <> +constexpr auto GetMask2<4>(const uint64_t mask) { + uint64_t mask2 = (mask & 0xFF) >> 4; + return GetMask1<4>(mask2); +} + +template <> +constexpr auto GetMask1<8>(const uint64_t mask) { + uint64_t g0 = (mask & 1) * 0xffffffffffffffff; + uint64_t g1 = ((mask & 2) >> 1) * 0xffffffffffffffff; + return (typename VecBinaryType<8>::type){g0, g1}; +} + +template <> +constexpr auto GetMask2<8>(const uint64_t mask) { + uint64_t mask2 = (mask & 0xF) >> 2; + return GetMask1<8>(mask2); +} + +template +constexpr int maskForComplex(uint32_t mask) { + return 0; +} + +template <> +constexpr int maskForComplex<8>(uint32_t mask) { + mask = mask & 0xF; + int complex_mask = 0; + if (mask & 1) + complex_mask |= 3; + if (mask & 2) + complex_mask |= (3 << 2); + if (mask & 4) + complex_mask |= (3 << 4); + if (mask & 8) + complex_mask |= (3 << 6); + return complex_mask; +} + +template <> +constexpr int maskForComplex<16>(uint32_t mask) { + mask = mask & 0x3; + int complex_mask = 0; + if (mask & 1) + complex_mask |= 3; + if (mask & 2) + complex_mask |= (3 << 2); + return complex_mask; +} + +template > +constexpr int blend_choice() { + return 0xAA; +} + +template <> +constexpr int blend_choice>() { + return 0x0A; +} + +constexpr int64_t allbitset(int16_t x) { + int64_t onex = 1; + return (onex << x) - onex; +} + +namespace { /* unnamed namespace */ + +ZSimdVect vec_mergee(ZSimdVect x, ZSimdVect y) { + constexpr ZSimdVectBinary mergee_mask{ + 0, 1, 2, 3, 16, 17, 18, 19, 8, 9, 10, 11, 24, 25, 26, 27}; + return vec_perm(x, y, mergee_mask); +} + +ZSimdVect vec_mergee(ZSimdVect x, ZSimdVect y) { + return vec_mergeh(x, y); +} + +ZSimdVect vec_mergeo(ZSimdVect x, ZSimdVect y) { + constexpr ZSimdVectBinary mergeo_mask{ + 4, 5, 6, 7, 20, 21, 22, 23, 12, 13, 14, 15, 28, 29, 30, 31}; + return vec_perm(x, y, mergeo_mask); +} + +ZSimdVect vec_mergeo(ZSimdVect x, ZSimdVect y) { + return vec_mergel(x, y); +} + +} /* unnamed namespace */ + +// +template +constexpr auto GetBpermZeroMask() { + return ZSimdVectBinary{ + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 96, + 64, + 32, + 0}; +} + +template <> +constexpr auto GetBpermZeroMask() { + return ZSimdVectBinary{ + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 128, + 64, + 0}; +} + +constexpr auto GetSwapMaskFloat() { + return ZSimdVectBinary{ + 4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11}; +} + +template +struct is_vec_specialized_for()>> + : std::bool_constant {}; + +template +struct Vectorized()>> { + public: + using value_type = T; + using vtype = ZSimdVect; + using vmaskType = ZSimdVectBinary; + using size_type = int; + // because of gcc inconsistency for int64_t we are obliged to use this, not + // value_type + using ElementType = ZSimdVectElement; + using vinner_data = std::pair; + + private: + vtype _vec0; + vtype _vec1; + + public: + static constexpr size_type size() { + return VECTOR_WIDTH / sizeof(ElementType); + } + Vectorized() = default; + + C10_ALWAYS_INLINE Vectorized(vtype v) : _vec0{v}, _vec1{v} {} + C10_ALWAYS_INLINE Vectorized(const vinner_data& v) + : _vec0{v.first}, _vec1{v.second} {} + C10_ALWAYS_INLINE Vectorized(vtype v1, vtype v2) : _vec0{v1}, _vec1{v2} {} + C10_ALWAYS_INLINE Vectorized(T s) + : _vec0{vec_splats((ElementType)s)}, _vec1{vec_splats((ElementType)s)} {} + + template + struct LoaduHelper { + static Vectorized C10_ALWAYS_INLINE + loadu(const U* ptr, int count = size()) { + __at_align__ ElementType tmp_values[size()] = {}; + std::memcpy( + tmp_values, ptr, std::min(count, size()) * sizeof(ElementType)); + + return { + vec_xl(offset0, &(tmp_values[0])), + vec_xl(offset16, &(tmp_values[0]))}; + } + }; + + template + struct LoaduHelper { + static Vectorized C10_ALWAYS_INLINE + loadu(const ElementType* ptr, int count = size()) { + if (count == size()) { + return {vec_xl(offset0, ptr), vec_xl(offset16, ptr)}; + } + + __at_align__ ElementType tmp_values[size()] = {}; + std::memcpy( + tmp_values, ptr, std::min(count, size()) * sizeof(ElementType)); + + return { + vec_xl(offset0, &(tmp_values[0])), + vec_xl(offset16, &(tmp_values[0]))}; + } + }; + + template + static Vectorized C10_ALWAYS_INLINE + loadu(const U* ptr, int count = size()) { + return LoaduHelper::loadu(ptr, count); + } + + template + static Vectorized C10_ALWAYS_INLINE loadu_one_fourth(const U* ptr) { + // load only first 8 bytes + // only intended to be used with uint8_t + return loadu(ptr, 8 / sizeof(ElementType)); + } + + template + struct StoreHelper { + static void C10_ALWAYS_INLINE + store(const Vectorized& vec, U* ptr, int count = size()) { + if (count > 0) { + __at_align__ ElementType tmp_values[size()]; + vec_xst(vec._vec0, offset0, &(tmp_values[0])); + vec_xst(vec._vec1, offset16, &(tmp_values[0])); + std::memcpy( + ptr, tmp_values, std::min(count, size()) * sizeof(ElementType)); + } + } + }; + + template + struct StoreHelper { + static void C10_ALWAYS_INLINE + store(const Vectorized& vec, ElementType* ptr, int count = size()) { + if (count == size()) { + vec_xst(vec._vec0, offset0, ptr); + vec_xst(vec._vec1, offset16, ptr); + } else if (count > 0) { + __at_align__ ElementType tmp_values[size()]; + vec_xst(vec._vec0, offset0, &(tmp_values[0])); + vec_xst(vec._vec1, offset16, &(tmp_values[0])); + std::memcpy( + ptr, tmp_values, std::min(count, size()) * sizeof(ElementType)); + } + } + }; + + template + void C10_ALWAYS_INLINE store(U* ptr, int count = size()) const { + return StoreHelper::store(*this, ptr, count); + } + + C10_ALWAYS_INLINE const vtype& vec0() const { + return _vec0; + } + + C10_ALWAYS_INLINE const vtype& vec1() const { + return _vec1; + } + + C10_ALWAYS_INLINE vinner_data data() const { + return std::make_pair<>(_vec0, _vec1); + } + + C10_ALWAYS_INLINE operator vinner_data() const { + return data(); + } + + C10_ALWAYS_INLINE const vmaskType vecb0() const { + return (vmaskType)_vec0; + } + C10_ALWAYS_INLINE const vmaskType vecb1() const { + return (vmaskType)_vec1; + } + + static Vectorized C10_ALWAYS_INLINE blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + return { + vec_sel(a._vec0, b._vec0, mask.vecb0()), + vec_sel(a._vec1, b._vec1, mask.vecb1())}; + } + + template = 0> + C10_ALWAYS_INLINE Vectorized(T s1, T s2, T s3, T s4) + : _vec0{s1, s2}, _vec1{s3, s4} {} + + template = 0> + C10_ALWAYS_INLINE Vectorized(T s1, T s2, T s3, T s4, T s5, T s6, T s7, T s8) + : _vec0{s1, s2, s3, s4}, _vec1{s5, s6, s7, s8} {} + + template = 0> + C10_ALWAYS_INLINE Vectorized( + T s1, + T s2, + T s3, + T s4, + T s5, + T s6, + T s7, + T s8, + T s9, + T s10, + T s11, + T s12, + T s13, + T s14, + T s15, + T s16) + : _vec0{s1, s2, s3, s4, s5, s6, s7, s8}, + _vec1{s9, s10, s11, s12, s13, s14, s15, s16} {} + + template = 0> + C10_ALWAYS_INLINE Vectorized( + T s1, + T s2, + T s3, + T s4, + T s5, + T s6, + T s7, + T s8, + T s9, + T s10, + T s11, + T s12, + T s13, + T s14, + T s15, + T s16, + T s17, + T s18, + T s19, + T s20, + T s21, + T s22, + T s23, + T s24, + T s25, + T s26, + T s27, + T s28, + T s29, + T s30, + T s31, + T s32) + : _vec0{s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16}, + _vec1{ + s17, + s18, + s19, + s20, + s21, + s22, + s23, + s24, + s25, + s26, + s27, + s28, + s29, + s30, + s31, + s32} {} + + template + static std::enable_if_t> arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized(base, base + step, base + 2 * step, base + 3 * step); + } + + template + static std::enable_if_t> arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step); + } + + template + static std::enable_if_t> arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step); + } + + template + static std::enable_if_t> arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step, + base + 16 * step, + base + 17 * step, + base + 18 * step, + base + 19 * step, + base + 20 * step, + base + 21 * step, + base + 22 * step, + base + 23 * step, + base + 24 * step, + base + 25 * step, + base + 26 * step, + base + 27 * step, + base + 28 * step, + base + 29 * step, + base + 30 * step, + base + 31 * step); + } + + // blend section + template + static std::enable_if_t(mask) == 0, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + return a; + } + + template + static std::enable_if_t(mask) == 1, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + return b; + } + + template + static std::enable_if_t(mask) == 2, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + return {b._vec0, a._vec1}; + } + + template + static std::enable_if_t(mask) == 3, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + return {a._vec0, b._vec1}; + } + + template + static std::enable_if_t(mask) == 4, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + const vmaskType mask_1st = GetMask1(mask); + return {(vtype)vec_sel(a._vec0, b._vec0, mask_1st), a._vec1}; + } + + template + static std::enable_if_t(mask) == 5, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + const vmaskType mask_1st = GetMask1(mask); + return {(vtype)vec_sel(a._vec0, b._vec0, mask_1st), b._vec1}; + } + + template + static std::enable_if_t(mask) == 6, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + const vmaskType mask_2nd = GetMask2(mask); + // generated masks + return {a._vec0, (vtype)vec_sel(a._vec1, b._vec1, mask_2nd)}; + } + + template + static std::enable_if_t(mask) == 7, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + const vmaskType mask_2nd = GetMask2(mask); + // generated masks + return {b._vec0, (vtype)vec_sel(a._vec1, b._vec1, mask_2nd)}; + } + + template + static std::enable_if_t(mask) == 8, Vectorized> + C10_ALWAYS_INLINE blend(const Vectorized& a, const Vectorized& b) { + const vmaskType mask_1st = GetMask1(mask); + const vmaskType mask_2nd = GetMask2(mask); + return { + (vtype)vec_sel(a._vec0, b._vec0, mask_1st), + (vtype)vec_sel(a._vec1, b._vec1, mask_2nd)}; + } + + template + static inline std::enable_if_t<(Z >= C), Vectorized> set_inner( + const Vectorized& a, + const Vectorized& b, + size_t count) { + return b; + } + + template + static inline std::enable_if_t<(Z < C), Vectorized> set_inner( + const Vectorized& a, + const Vectorized& b, + size_t count) { + if (count == Z) + return blend(a, b); + else + return set_inner(a, b, count); + } + + static Vectorized set( + const Vectorized& a, + const Vectorized& b, + size_t count = size()) { + if (count == 0) + return a; + return set_inner<1, size()>(a, b, count); + } + + const ElementType& operator[](int idx) const = delete; + ElementType& operator[](int idx) = delete; + + Vectorized _not() const { + return {(vtype)vec_nor(vecb0(), vecb0()), (vtype)vec_nor(vecb1(), vecb1())}; + } + + Vectorized C10_ALWAYS_INLINE eq(const Vectorized& other) const { + return (*this == other) & Vectorized((T)1.0); + } + Vectorized C10_ALWAYS_INLINE ne(const Vectorized& other) const { + return (*this != other) & Vectorized((T)1.0); + } + Vectorized C10_ALWAYS_INLINE gt(const Vectorized& other) const { + return (*this > other) & Vectorized((T)1.0); + } + Vectorized C10_ALWAYS_INLINE ge(const Vectorized& other) const { + return (*this >= other) & Vectorized((T)1.0); + } + Vectorized C10_ALWAYS_INLINE lt(const Vectorized& other) const { + return (*this < other) & Vectorized((T)1.0); + } + Vectorized C10_ALWAYS_INLINE le(const Vectorized& other) const { + return (*this <= other) & Vectorized((T)1.0); + } + + template , int> = 0> + Vectorized C10_ALWAYS_INLINE abs() const { + return {vec_abs(_vec0), vec_abs(_vec1)}; + } + + template , int> = 0> + Vectorized C10_ALWAYS_INLINE abs() const { + return {_vec0, _vec1}; + } + + Vectorized C10_ALWAYS_INLINE neg() const { + return {-_vec0, -_vec1}; + } + + Vectorized isnan() const { + auto x = *this; + auto ret = (x == x); + return ret._not(); + } + + bool has_inf_nan() const { + for (const auto i : c10::irange(size() / 2)) { + if (_isnan(_vec0[i]) || _isinf(_vec0[i])) { + return true; + } + } + for (const auto i : c10::irange(size() / 2)) { + if (_isnan(_vec1[i]) || _isinf(_vec1[i])) { + return true; + } + } + return false; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized angle() const { + auto tmp = blendv( + Vectorized(0), Vectorized(c10::pi), *this < Vectorized(0)); + return blendv(tmp, *this, isnan()); + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized angle() const { + return blendv( + Vectorized(0), Vectorized(c10::pi), *this < Vectorized(0)); + } + + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return Vectorized{0}; + } + Vectorized conj() const { + return *this; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + int zero_mask() const { + auto cmp = (*this == Vectorized(0)); + constexpr auto mask_zero_bits = GetBpermZeroMask(); + ZSimdVectBinary result0 = + vec_bperm_u128((ZSimdVectBinary)cmp.vecb0(), mask_zero_bits); + ZSimdVectBinary result1 = + vec_bperm_u128((ZSimdVectBinary)cmp.vecb1(), mask_zero_bits); + return (result0[0] | (result1[0] << (size() / 2))); + } + + Vectorized C10_ALWAYS_INLINE floor() const { + return {vec_floor(_vec0), vec_floor(_vec1)}; + } + + Vectorized C10_ALWAYS_INLINE ceil() const { + return {vec_ceil(_vec0), vec_ceil(_vec1)}; + } + + Vectorized C10_ALWAYS_INLINE round() const { + return {vec_round(_vec0), vec_round(_vec1)}; + } + + Vectorized C10_ALWAYS_INLINE rint() const { + return {vec_rint(_vec0), vec_rint(_vec1)}; + } + + Vectorized C10_ALWAYS_INLINE trunc() const { + return {vec_trunc(_vec0), vec_trunc(_vec1)}; + } + + Vectorized C10_ALWAYS_INLINE frac() const { + return *this - trunc(); + } + + Vectorized C10_ALWAYS_INLINE sqrt() const { + return {vec_sqrt(_vec0), vec_sqrt(_vec1)}; + } + Vectorized C10_ALWAYS_INLINE reciprocal() const { + return Vectorized((T)1) / (*this); + } + Vectorized C10_ALWAYS_INLINE rsqrt() const { + return sqrt().reciprocal(); + } + + template , int> = 0> + inline Vectorized mapOrdinary(float (*const f)(float)) const { + float a00 = f(_vec0[0]); + float a01 = f(_vec0[1]); + float a02 = f(_vec0[2]); + float a03 = f(_vec0[3]); + float a10 = f(_vec1[0]); + float a11 = f(_vec1[1]); + float a12 = f(_vec1[2]); + float a13 = f(_vec1[3]); + return Vectorized{a00, a01, a02, a03, a10, a11, a12, a13}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + inline Vectorized mapOrdinary(double (*const f)(double)) const { + return Vectorized(f(_vec0[0]), f(_vec0[1]), f(_vec1[0]), f(_vec1[1])); + } + + template , int> = 0> + inline Vectorized mapOrdinary( + float (*const f)(float, float), + const Vectorized& b) const { + float a00 = f(_vec0[0], b._vec0[0]); + float a01 = f(_vec0[1], b._vec0[1]); + float a02 = f(_vec0[2], b._vec0[2]); + float a03 = f(_vec0[3], b._vec0[3]); + float a10 = f(_vec1[0], b._vec1[0]); + float a11 = f(_vec1[1], b._vec1[1]); + float a12 = f(_vec1[2], b._vec1[2]); + float a13 = f(_vec1[3], b._vec1[3]); + return Vectorized{a00, a01, a02, a03, a10, a11, a12, a13}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + inline Vectorized mapOrdinary( + double (*const f)(double, double), + const Vectorized& b) const { + return Vectorized( + f(_vec0[0], b._vec0[0]), + f(_vec0[1], b._vec0[1]), + f(_vec1[0], b._vec1[0]), + f(_vec1[1], b._vec1[1])); + } + + template < + typename FloatOp, + typename DoubleOp, + typename U = T, + std::enable_if_t, int> = 0> + inline Vectorized mapSleef(FloatOp f, DoubleOp d) const { + vtype a0 = f(_vec0); + vtype a1 = f(_vec1); + return Vectorized{a0, a1}; + } + + template < + typename FloatOp, + typename DoubleOp, + typename U = T, + std::enable_if_t, int> = 0> + inline Vectorized mapSleef(FloatOp f, DoubleOp d) const { + return Vectorized(d(_vec0), d(_vec1)); + } + + template < + typename FloatOp, + typename DoubleOp, + typename U = T, + std::enable_if_t, int> = 0> + inline Vectorized mapSleef(FloatOp f, DoubleOp d, const Vectorized& b) + const { + vtype a0 = f(_vec0, b._vec0); + vtype a1 = f(_vec1, b._vec1); + return Vectorized{a0, a1}; + } + + template < + typename FloatOp, + typename DoubleOp, + typename U = T, + std::enable_if_t, int> = 0> + inline Vectorized mapSleef(FloatOp f, DoubleOp d, const Vectorized& b) + const { + return Vectorized(d(_vec0, b._vec0), d(_vec1, b._vec1)); + } + + Vectorized acos() const { + return mapSleef(Sleef_acosf4_u10, Sleef_acosd2_u10); + } + Vectorized asin() const { + return mapSleef(Sleef_asinf4_u10, Sleef_asind2_u10); + } + Vectorized atan() const { + return mapSleef(Sleef_atanf4_u10, Sleef_atand2_u10); + } + Vectorized atanh() const { + return mapSleef(Sleef_atanhf4_u10, Sleef_atanhd2_u10); + } + + Vectorized erf() const { + return mapSleef(Sleef_erff4_u10, Sleef_erfd2_u10); + } + Vectorized erfc() const { + return mapSleef(Sleef_erfcf4_u15, Sleef_erfcd2_u15); + } + + Vectorized exp() const { + return mapSleef(Sleef_expf4_u10, Sleef_expd2_u10); + } + Vectorized exp2() const { + return mapSleef(Sleef_exp2f4_u10, Sleef_exp2d2_u10); + } + Vectorized expm1() const { + return mapSleef(Sleef_expm1f4_u10, Sleef_expm1d2_u10); + } + Vectorized exp_u20() const { + return exp(); + } + Vectorized fexp_u20() const { + return exp(); + } + + Vectorized log() const { + return mapSleef(Sleef_logf4_u10, Sleef_logd2_u10); + } + Vectorized log2() const { + return mapSleef(Sleef_log2f4_u10, Sleef_log2d2_u10); + } + Vectorized log10() const { + return mapSleef(Sleef_log10f4_u10, Sleef_log10d2_u10); + } + Vectorized log1p() const { + return mapSleef(Sleef_log1pf4_u10, Sleef_log1pd2_u10); + } + + Vectorized sin() const { + return mapSleef(Sleef_sinf4_u10, Sleef_sind2_u10); + } + // Sleef sinhf/coshf overflow for large float inputs where std::sinh/cosh + // return finite results, because Sleef uses float-range intermediates + // internally while the scalar C library uses double precision. + Vectorized sinh() const { + if constexpr (std::is_same_v) { + return mapOrdinary(std::sinh); + } else { + return mapSleef(Sleef_sinhf4_u10, Sleef_sinhd2_u10); + } + } + Vectorized cos() const { + return mapSleef(Sleef_cosf4_u10, Sleef_cosd2_u10); + } + Vectorized cosh() const { + if constexpr (std::is_same_v) { + return mapOrdinary(std::cosh); + } else { + return mapSleef(Sleef_coshf4_u10, Sleef_coshd2_u10); + } + } + + Vectorized tan() const { + return mapSleef(Sleef_tanf4_u10, Sleef_tand2_u10); + } + Vectorized tanh() const { + return mapSleef(Sleef_tanhf4_u10, Sleef_tanhd2_u10); + } + + Vectorized lgamma() const { + return mapSleef(Sleef_lgammaf4_u10, Sleef_lgammad2_u10); + } + + Vectorized atan2(const Vectorized& b) const { + return mapSleef(Sleef_atan2f4_u10, Sleef_atan2d2_u10, b); + } + Vectorized copysign(const Vectorized& sign) const { + return mapSleef(Sleef_copysignf4, Sleef_copysignd2, sign); + } + Vectorized fmod(const Vectorized& q) const { + return mapSleef(Sleef_fmodf4, Sleef_fmodd2, q); + } + + Vectorized hypot(const Vectorized& b) const { + return mapSleef(Sleef_hypotf4_u05, Sleef_hypotd2_u05, b); + } + + Vectorized pow(const Vectorized& b) const { + return mapSleef(Sleef_powf4_u10, Sleef_powd2_u10, b); + } + + Vectorized nextafter(const Vectorized& b) const { + return mapSleef(Sleef_nextafterf4, Sleef_nextafterd2, b); + } + + Vectorized erfinv() const { + return mapOrdinary(calc_erfinv); + } + + Vectorized digamma() const { + return mapOrdinary(calc_digamma); + } + + Vectorized igamma(const Vectorized& x) const { + return mapOrdinary(calc_igamma, x); + } + + Vectorized igammac(const Vectorized& x) const { + return mapOrdinary(calc_igammac, x); + } + + Vectorized i0() const { + return mapOrdinary(calc_i0); + } + + Vectorized i0e() const { + return mapOrdinary(calc_i0e); + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized minimum(const Vectorized& other) const { + return {vec_min(_vec0, other._vec0), vec_min(_vec1, other._vec1)}; + } + + /* Propagates NaN if either input is a NaN. */ + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized minimum(const Vectorized& other) const { + Vectorized tmp = { + vec_min(_vec0, other._vec0), vec_min(_vec1, other._vec1)}; + tmp = blendv(tmp, *this, isnan()); + return blendv(tmp, other, other.isnan()); + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized maximum(const Vectorized& other) const { + return {vec_max(_vec0, other._vec0), vec_max(_vec1, other._vec1)}; + } + + /* Propagates NaN if either input is a NaN. */ + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized maximum(const Vectorized& other) const { + Vectorized tmp = { + vec_max(_vec0, other._vec0), vec_max(_vec1, other._vec1)}; + tmp = blendv(tmp, *this, isnan()); + return blendv(tmp, other, other.isnan()); + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized clamp_min(const Vectorized& min) const { + return {vec_max(_vec0, min._vec0), vec_max(_vec1, min._vec1)}; + } + + /* Keeps NaN if actual value is NaN */ + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized clamp_min(const Vectorized& min) const { + Vectorized tmp = {vec_max(_vec0, min._vec0), vec_max(_vec1, min._vec1)}; + return blendv(tmp, *this, isnan()); + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized clamp_max(const Vectorized& max) const { + return {vec_min(_vec0, max._vec0), vec_min(_vec1, max._vec1)}; + } + + /* Keeps NaN if actual value is NaN */ + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized clamp_max(const Vectorized& max) const { + Vectorized tmp = {vec_min(_vec0, max._vec0), vec_min(_vec1, max._vec1)}; + return blendv(tmp, *this, isnan()); + } + + template , int> = 0> + Vectorized swapped() const { + auto swap_mask = GetSwapMaskFloat(); + vtype v0 = vec_perm(_vec0, _vec0, swap_mask); + vtype v1 = vec_perm(_vec1, _vec1, swap_mask); + return {v0, v1}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized swapped() const { + vtype v0 = {_vec0[1], _vec0[0]}; + vtype v1 = {_vec1[1], _vec1[0]}; + return {v0, v1}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + static Vectorized mergee(Vectorized& first, Vectorized& second) { + return { + vec_mergee(first._vec0, second._vec0), + vec_mergee(first._vec1, second._vec1)}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + static Vectorized mergeo(Vectorized& first, Vectorized& second) { + return { + vec_mergeo(first._vec0, second._vec0), + vec_mergeo(first._vec1, second._vec1)}; + } + + static Vectorized horizontal_add_perm( + Vectorized& first, + Vectorized& second) { + // we will simulate it differently with 6 instructions total + // lets permute second so that we can add it getting horizontal sums + auto first_perm = first.swapped(); // 2perm + auto second_perm = second.swapped(); // 2perm + // summ + auto first_ret = first + first_perm; // 2add + auto second_ret = second + second_perm; // 2 add + // now lets choose evens + return mergee(first_ret, second_ret); // 2 mergee's + } + + static Vectorized horizontal_sub_perm( + Vectorized& first, + Vectorized& second) { + // we will simulate it differently with 6 instructions total + // lets permute second so that we can add it getting horizontal sums + auto first_perm = first.swapped(); // 2perm + auto second_perm = second.swapped(); // 2perm + // summ + auto first_ret = first - first_perm; // 2sub + auto second_ret = second - second_perm; // 2 sub + // now lets choose evens + return mergee(first_ret, second_ret); // 2 mergee's + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized mergee() const { + return {vec_mergee(_vec0, _vec0), vec_mergee(_vec1, _vec1)}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized mergeo() const { + return {vec_mergeo(_vec0, _vec0), vec_mergeo(_vec1, _vec1)}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized to_vec_float_helper() const { + int32_t values[8] = { + _vec0[0], + _vec0[1], + _vec0[2], + _vec0[3], + _vec0[4], + _vec0[5], + _vec0[6], + _vec0[7], + }; + + return Vectorized{ + values[0], + values[1], + values[2], + values[3], + values[4], + values[5], + values[6], + values[7]}; + } + + template < + typename U = T, + std::enable_if_t, int> = 0> + Vectorized to_vec_uint8_helper() const { + // helper function for float to uint8_t conversion + uint8_t values[8] = { + static_cast(_vec0[0]), + static_cast(_vec0[1]), + static_cast(_vec0[2]), + static_cast(_vec0[3]), + static_cast(_vec1[0]), + static_cast(_vec1[1]), + static_cast(_vec1[2]), + static_cast(_vec1[3]), + }; + + return Vectorized{ + values[0], values[1], values[2], values[3], values[4], values[5], + values[6], values[7], 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, + }; + } +}; + +#define ZVECTOR_OPERATORS(typex) \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator+( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec0() + b.vec0(), a.vec1() + b.vec1()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator-( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec0() - b.vec0(), a.vec1() - b.vec1()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator*( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec0() * b.vec0(), a.vec1() * b.vec1()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator/( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec0() / b.vec0(), a.vec1() / b.vec1()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator&( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + (Vectorized::vtype)(a.vecb0() & b.vecb0()), \ + (Vectorized::vtype)(a.vecb1() & b.vecb1())}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator|( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + (Vectorized::vtype)(a.vecb0() | b.vecb0()), \ + (Vectorized::vtype)(a.vecb1() | b.vecb1())}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator^( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + (Vectorized::vtype)(a.vecb0() ^ b.vecb0()), \ + (Vectorized::vtype)(a.vecb1() ^ b.vecb1())}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator==( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + vec_cmpeq(a.vec0(), b.vec0()), vec_cmpeq(a.vec1(), b.vec1())}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator!=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + vec_cmpeq(a.vec0(), b.vec0()), vec_cmpeq(a.vec1(), b.vec1())} \ + ._not(); \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator>( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + vec_cmpgt(a.vec0(), b.vec0()), vec_cmpgt(a.vec1(), b.vec1())}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator>=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + vec_cmpge(a.vec0(), b.vec0()), vec_cmpge(a.vec1(), b.vec1())}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator<( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + vec_cmplt(a.vec0(), b.vec0()), vec_cmplt(a.vec1(), b.vec1())}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator<=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{ \ + vec_cmple(a.vec0(), b.vec0()), vec_cmple(a.vec1(), b.vec1())}; \ + } + +ZVECTOR_OPERATORS(float) +ZVECTOR_OPERATORS(double) +ZVECTOR_OPERATORS(int8_t) +ZVECTOR_OPERATORS(uint8_t) +ZVECTOR_OPERATORS(uint16_t) +ZVECTOR_OPERATORS(int16_t) +ZVECTOR_OPERATORS(int32_t) +ZVECTOR_OPERATORS(int64_t) + +#undef ZVECTOR_OPERATORS + +#define ZVECTOR_OPERATORS(typex) \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator<<( \ + const Vectorized& a, const Vectorized& b) { \ + constexpr Vectorized::ElementType max_shift = \ + sizeof(Vectorized::ElementType) * CHAR_BIT; \ + \ + Vectorized::ElementType a_array[Vectorized::size()]; \ + Vectorized::ElementType b_array[Vectorized::size()]; \ + Vectorized::ElementType c_array[Vectorized::size()]; \ + \ + a.store(a_array); \ + b.store(b_array); \ + \ + for (int i = 0; i != Vectorized::size(); i++) { \ + typex shift = b_array[i]; \ + if ((static_cast>(shift) < 0) || \ + (shift >= max_shift)) { \ + c_array[i] = 0; \ + } else { \ + c_array[i] = static_cast>(a_array[i]) \ + << shift; \ + } \ + } \ + \ + return Vectorized::loadu(c_array); \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator>>( \ + const Vectorized& a, const Vectorized& b) { \ + /* right shift value to retain sign bit for signed and no bits for \ + * unsigned */ \ + constexpr Vectorized::ElementType max_shift = \ + sizeof(typex) * CHAR_BIT - std::is_signed_v; \ + \ + Vectorized::ElementType a_array[Vectorized::size()]; \ + Vectorized::ElementType b_array[Vectorized::size()]; \ + Vectorized::ElementType c_array[Vectorized::size()]; \ + \ + a.store(a_array); \ + b.store(b_array); \ + \ + for (int i = 0; i != Vectorized::size(); i++) { \ + typex shift = b_array[i]; \ + if ((static_cast>(shift) < 0) || \ + (shift >= max_shift)) { \ + c_array[i] = a_array[i] >> max_shift; \ + } else { \ + c_array[i] = a_array[i] >> shift; \ + } \ + } \ + \ + return Vectorized::loadu(c_array); \ + } \ + \ + template <> \ + inline Vectorized operator~(const Vectorized& a) { \ + return a._not(); \ + } + +ZVECTOR_OPERATORS(int8_t) +ZVECTOR_OPERATORS(uint8_t) +ZVECTOR_OPERATORS(uint16_t) +ZVECTOR_OPERATORS(int16_t) +ZVECTOR_OPERATORS(int32_t) +ZVECTOR_OPERATORS(int64_t) + +#undef ZVECTOR_OPERATORS + +#define DEFINE_MAXMIN_FUNCS(operand_type) \ + template <> \ + Vectorized inline maximum( \ + const Vectorized& a, const Vectorized& b) { \ + return a.maximum(b); \ + } \ + template <> \ + Vectorized inline minimum( \ + const Vectorized& a, const Vectorized& b) { \ + return a.minimum(b); \ + } + +#define DEFINE_CLAMP_MAXMIN_FUNCS(typex) \ + DEFINE_MAXMIN_FUNCS(typex) \ + template <> \ + Vectorized C10_ALWAYS_INLINE clamp_min( \ + const Vectorized& a, const Vectorized& min) { \ + return a.clamp_min(min); \ + } \ + template <> \ + Vectorized C10_ALWAYS_INLINE clamp_max( \ + const Vectorized& a, const Vectorized& max) { \ + return a.clamp_max(max); \ + } \ + template <> \ + Vectorized C10_ALWAYS_INLINE clamp( \ + const Vectorized& a, \ + const Vectorized& min, \ + const Vectorized& max) { \ + return clamp_max(clamp_min(a, min), max); \ + } + +DEFINE_CLAMP_MAXMIN_FUNCS(int8_t) +DEFINE_CLAMP_MAXMIN_FUNCS(uint8_t) +DEFINE_CLAMP_MAXMIN_FUNCS(int16_t) +DEFINE_CLAMP_MAXMIN_FUNCS(int32_t) +DEFINE_CLAMP_MAXMIN_FUNCS(int64_t) +DEFINE_CLAMP_MAXMIN_FUNCS(float) +DEFINE_CLAMP_MAXMIN_FUNCS(double) + +namespace { /* unnamed namespace */ + +#if !defined(vec_float) || __ARCH__ < 13 +#warning \ + "float->int and int->float conversion is simulated. compile for z15 for improved performance" +inline ZSimdVect vec_int_flt(const ZSimdVect x) { + return ZSimdVect{float(x[0]), float(x[1]), float(x[2]), float(x[3])}; +} +inline ZSimdVect vec_flt_int(const ZSimdVect x) { + return ZSimdVect{int(x[0]), int(x[1]), int(x[2]), int(x[3])}; +} +#else +#define vec_int_flt vec_float +#define vec_flt_int vec_signed +#endif + +Vectorized zvec_convert_to_float(const Vectorized& x) { + return {vec_int_flt(x.vec0()), vec_int_flt(x.vec1())}; +} + +Vectorized zvec_convert_to_int(const Vectorized& x) { + return {vec_flt_int(x.vec0()), vec_flt_int(x.vec1())}; +} + +Vectorized zvec_convert_to_float(const Vectorized& x) { + return {vec_double(x.vec0()), vec_double(x.vec1())}; +} + +Vectorized zvec_convert_to_int(const Vectorized& x) { + return {vec_signed(x.vec0()), vec_signed(x.vec1())}; +} + +} /* unnamed namespace */ + +template +Vectorized cast_zvector(const Vectorized& x) { + using cast_type = typename Vectorized::vtype; + return Vectorized{(cast_type)x.vec0(), (cast_type)x.vec1()}; +} + +template <> +Vectorized C10_ALWAYS_INLINE fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return Vectorized{ + __builtin_s390_vfmasb(a.vec0(), b.vec0(), c.vec0()), + __builtin_s390_vfmasb(a.vec1(), b.vec1(), c.vec1())}; +} +template <> +Vectorized C10_ALWAYS_INLINE fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return Vectorized{ + __builtin_s390_vfmadb(a.vec0(), b.vec0(), c.vec0()), + __builtin_s390_vfmadb(a.vec1(), b.vec1(), c.vec1())}; +} +template <> +Vectorized C10_ALWAYS_INLINE fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return Vectorized{ + a.vec0() * b.vec0() + c.vec0(), a.vec1() * b.vec1() + c.vec1()}; +} +template <> +Vectorized C10_ALWAYS_INLINE fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return Vectorized{ + a.vec0() * b.vec0() + c.vec0(), a.vec1() * b.vec1() + c.vec1()}; +} +template <> +Vectorized C10_ALWAYS_INLINE fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return Vectorized{ + a.vec0() * b.vec0() + c.vec0(), a.vec1() * b.vec1() + c.vec1()}; +} + +template <> +Vectorized C10_ALWAYS_INLINE +convert_to_int_of_same_size(const Vectorized& src) { + return zvec_convert_to_int(src); +} + +template <> +Vectorized C10_ALWAYS_INLINE +convert_to_int_of_same_size(const Vectorized& src) { + return zvec_convert_to_int(src); +} + +template <> +inline void convert(const int32_t* src, float* dst, int64_t n) { + // int32_t and float have same size + int64_t i; + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + const int32_t* src_a = src + i; + float* dst_a = dst + i; + auto input_vec = Vectorized::loadu(src_a); + auto output_vec = zvec_convert_to_float(input_vec); + output_vec.store(dst_a); + } + + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +template <> +inline void convert(const int64_t* src, double* dst, int64_t n) { + int64_t i; + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + const int64_t* src_a = src + i; + double* dst_a = dst + i; + auto input_vec = Vectorized::loadu(src_a); + auto output_vec = zvec_convert_to_float(input_vec); + output_vec.store(dst_a); + } + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +#define DEFINE_REINTERPRET_CAST_FUNCS(Fst, Cst) \ + template <> \ + C10_ALWAYS_INLINE Vectorized cast( \ + const Vectorized& src) { \ + return cast_zvector(src); \ + } + +#define DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(Fst) \ + DEFINE_REINTERPRET_CAST_FUNCS(Fst, double) \ + DEFINE_REINTERPRET_CAST_FUNCS(Fst, float) \ + DEFINE_REINTERPRET_CAST_FUNCS(Fst, int64_t) \ + DEFINE_REINTERPRET_CAST_FUNCS(Fst, int32_t) \ + DEFINE_REINTERPRET_CAST_FUNCS(Fst, int16_t) + +DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(float) +DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(double) +DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(int64_t) +DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(int32_t) +DEFINE_REINTERPRET_CAST_TO_ALL_FUNCS(int16_t) + +#undef DEFINE_REINTERPRET_CAST_FUNCS + +template +struct unpack_type { + using type = T; +}; +template <> +struct unpack_type { + using type = int16_t; +}; +template <> +struct unpack_type { + using type = int16_t; +}; +template <> +struct unpack_type { + using type = int32_t; +}; + +template +struct pack_type { + using type = T; +}; +template <> +struct pack_type { + using type = int8_t; +}; +template <> +struct pack_type { + using type = int16_t; +}; + +namespace { /* unnamed namespace */ + +template ::type> +std::pair, Vectorized> unpack(const Vectorized& x) { + auto vec0 = vec_unpackh(x.vec0()); + auto vec1 = vec_unpackl(x.vec0()); + auto vec2 = vec_unpackh(x.vec1()); + auto vec3 = vec_unpackl(x.vec1()); + return {Vectorized{vec0, vec1}, Vectorized{vec2, vec3}}; +} + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-function") +template <> +std::pair, Vectorized> unpack( + const Vectorized& x) { + using typeX = typename Vectorized::vtype; + typeX vec0 = vec_unpackh(x.vec0()); + typeX vec1 = vec_unpackl(x.vec0()); + typeX vec2 = vec_unpackh(x.vec1()); + typeX vec3 = vec_unpackl(x.vec1()); + // auto mask = Vectorized(0xFF); + // vec0 = vec0 & mask; + // vec1 = vec1 & mask; + // vec2 = vec2 & mask; + // vec3 = vec3 & mask; + return { + cast_zvector(Vectorized{vec0, vec1}), + cast_zvector(Vectorized{vec2, vec3})}; +} +C10_DIAGNOSTIC_POP() + +template ::type> +Vectorized pack(const Vectorized& first, const Vectorized& second) { + auto vec0 = vec_packs(first.vec0(), first.vec1()); + auto vec1 = vec_packs(second.vec0(), second.vec1()); + return Vectorized{vec0, vec1}; +} + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-function") +template <> +Vectorized pack( + const Vectorized& first, + const Vectorized& second) { + auto vec0 = vec_packsu(first.vec0(), first.vec1()); + auto vec1 = vec_packsu(second.vec0(), second.vec1()); + return Vectorized{vec0, vec1}; +} +C10_DIAGNOSTIC_POP() + +} /* unnamed namespace */ + +//////////////////////////////////QUANT/////////////////////////////////////////// +template +struct is_vec_specialized_for< + T, + std::enable_if_t()>> + : std::bool_constant {}; + +template +struct Vectorized()>> { + public: + using value_type = typename T::underlying; + using vtype = ZSimdVect; + using vmaskType = ZSimdVectBinary; + using vinner_type = Vectorized; + using size_type = int; + + static constexpr size_type size() { + return VECTOR_WIDTH / sizeof(value_type); + } + + static constexpr int float_num_vecs() { + return size() / Vectorized::size(); + } + static constexpr int int_num_vecs() { + return float_num_vecs(); + } + using float_vec_return_type = std::array, float_num_vecs()>; + using int_vec_return_type = + std::array, int_num_vecs()>; + + private: + vinner_type _vec; + + public: + Vectorized() = default; + + explicit C10_ALWAYS_INLINE Vectorized(vinner_type v) : _vec{v} {} + Vectorized(const T& val) : _vec(val.val_) {} + + C10_ALWAYS_INLINE const vinner_type& vec() const { + return _vec; + } + + template + static Vectorized C10_ALWAYS_INLINE + loadu(const U* ptr, int count = size()) { + return Vectorized{vinner_type::loadu(ptr, count)}; + } + + template + void C10_ALWAYS_INLINE store(U* ptr, int count = size()) const { + _vec.store(ptr, count); + } + + Vectorized relu(Vectorized zero_point) const { + return Vectorized{_vec.maximum(zero_point._vec)}; + } + + Vectorized relu6(Vectorized zero_point, Vectorized q_six) const { + auto ret_max = _vec.maximum(zero_point._vec); + auto ret_min = ret_max.minimum(q_six._vec); + return Vectorized{ret_min}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 1, int> = 0> + int_vec_return_type widening_subtract(Vectorized b) const { + return {*this - b}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 1, int> = 0> + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { + auto float_val = zvec_convert_to_float(_vec); + return {fmadd(scale, float_val, scale_zp_premul)}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 1, int> = 0> + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { + auto float_val = zvec_convert_to_float(_vec); + return {(float_val - zero_point) * scale}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 1, int> = 0> + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + Vectorized vecf = rhs[0]; + vecf = vecf * Vectorized(inverse_scale); + vecf = vecf.rint() + Vectorized((float)(zero_point)); + auto veci = zvec_convert_to_int(vecf); + + return Vectorized{veci}; + } + + template < + typename U = T, + std::enable_if_t::int_num_vecs() == 1, int> = 0> + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + Vectorized vi = inp[0]; + auto vecf = zvec_convert_to_float(vi.vec()); + vecf = vecf * Vectorized(multiplier); + vecf = vecf.rint(); + auto veci = zvec_convert_to_int(vecf) + Vectorized(zero_point); + + return Vectorized{veci}; + } + + template < + typename U = T, + std::enable_if_t::int_num_vecs() == 4, int> = 0> + int_vec_return_type widening_subtract(Vectorized b) const { + auto ret16 = unpack(_vec); + auto ret16B = unpack(b.vec()); + auto ret32_0 = unpack(ret16.first); + auto ret32_1 = unpack(ret16.second); + auto ret32B_0 = unpack(ret16B.first); + auto ret32B_1 = unpack(ret16B.second); + + return { + Vectorized(ret32_0.first - ret32B_0.first), + Vectorized(ret32_0.second - ret32B_0.second), + Vectorized(ret32_1.first - ret32B_1.first), + Vectorized(ret32_1.second - ret32B_1.second)}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 4, int> = 0> + float_vec_return_type C10_ALWAYS_INLINE dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { + // unpacking unsigned as signed + auto ret16 = unpack(_vec); + auto ret32_0 = unpack(ret16.first); + auto ret32_1 = unpack(ret16.second); + + auto vecf_0 = zvec_convert_to_float(ret32_0.first); + auto vecf_1 = zvec_convert_to_float(ret32_0.second); + + auto vecf_2 = zvec_convert_to_float(ret32_1.first); + auto vecf_3 = zvec_convert_to_float(ret32_1.second); + return { + fmadd(scale, vecf_0, scale_zp_premul), + fmadd(scale, vecf_1, scale_zp_premul), + fmadd(scale, vecf_2, scale_zp_premul), + fmadd(scale, vecf_3, scale_zp_premul)}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 4, int> = 0> + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { + // unpacking unsigned as signed + auto ret16 = unpack(_vec); + auto ret32_0 = unpack(ret16.first); + auto ret32_1 = unpack(ret16.second); + + auto vecf_0 = zvec_convert_to_float(ret32_0.first); + auto vecf_1 = zvec_convert_to_float(ret32_0.second); + + auto vecf_2 = zvec_convert_to_float(ret32_1.first); + auto vecf_3 = zvec_convert_to_float(ret32_1.second); + + return { + (vecf_0 - zero_point) * scale, + (vecf_1 - zero_point) * scale, + (vecf_2 - zero_point) * scale, + (vecf_3 - zero_point) * scale}; + } + + template < + typename U = T, + std::enable_if_t::float_num_vecs() == 4, int> = 0> + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + auto vec_inverse = Vectorized(inverse_scale); + auto vec_zero_point = Vectorized((float)zero_point); + + auto vecf0 = rhs[0]; + auto vecf2 = rhs[1]; + auto vecf4 = rhs[2]; + auto vecf6 = rhs[3]; + + vecf0 = vecf0 * vec_inverse; + vecf2 = vecf2 * vec_inverse; + vecf4 = vecf4 * vec_inverse; + vecf6 = vecf6 * vec_inverse; + + vecf0 = vecf0.rint() + vec_zero_point; + vecf2 = vecf2.rint() + vec_zero_point; + vecf4 = vecf4.rint() + vec_zero_point; + vecf6 = vecf6.rint() + vec_zero_point; + + auto veci0 = zvec_convert_to_int(vecf0); + auto veci2 = zvec_convert_to_int(vecf2); + auto veci4 = zvec_convert_to_int(vecf4); + auto veci6 = zvec_convert_to_int(vecf6); + + auto vecshi0 = pack(veci0, veci2); + auto vecshi2 = pack(veci4, veci6); + auto ret = pack(vecshi0, vecshi2); + + return Vectorized{ret}; + } + + template < + typename U = T, + std::enable_if_t::int_num_vecs() == 4, int> = 0> + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + Vectorized vec_multiplier = Vectorized(multiplier); + Vectorized vec_zero_point = Vectorized(zero_point); + + Vectorized vi0 = inp[0]; + Vectorized vi1 = inp[1]; + Vectorized vi2 = inp[2]; + Vectorized vi3 = inp[3]; + + auto vecf0 = zvec_convert_to_float(vi0.vec()); + auto vecf2 = zvec_convert_to_float(vi1.vec()); + + auto vecf4 = zvec_convert_to_float(vi2.vec()); + auto vecf6 = zvec_convert_to_float(vi3.vec()); + + vecf0 = vecf0 * vec_multiplier; + vecf2 = vecf2 * vec_multiplier; + + vecf4 = vecf4 * vec_multiplier; + vecf6 = vecf6 * vec_multiplier; + + vecf0 = vecf0.rint(); + vecf2 = vecf2.rint(); + vecf4 = vecf4.rint(); + vecf6 = vecf6.rint(); + + auto veci0 = zvec_convert_to_int(vecf0); + auto veci2 = zvec_convert_to_int(vecf2); + auto veci4 = zvec_convert_to_int(vecf4); + auto veci6 = zvec_convert_to_int(vecf6); + + veci0 = veci0 + vec_zero_point; + veci2 = veci2 + vec_zero_point; + + veci4 = veci4 + vec_zero_point; + veci6 = veci6 + vec_zero_point; + + auto vecshi0 = pack(veci0, veci2); + auto vecshi2 = pack(veci4, veci6); + + auto ret = pack(vecshi0, vecshi2); + + return Vectorized{ret}; + } + + Vectorized C10_ALWAYS_INLINE eq(const Vectorized& other) const { + return Vectorized{_vec.eq(other._vec)}; + } + Vectorized C10_ALWAYS_INLINE ne(const Vectorized& other) const { + return Vectorized{_vec.ne(other._vec)}; + } + Vectorized C10_ALWAYS_INLINE gt(const Vectorized& other) const { + return Vectorized{_vec.gt(other._vec)}; + } + Vectorized C10_ALWAYS_INLINE ge(const Vectorized& other) const { + return Vectorized{_vec.ge(other._vec)}; + } + Vectorized C10_ALWAYS_INLINE lt(const Vectorized& other) const { + return Vectorized{_vec.lt(other._vec)}; + } + Vectorized C10_ALWAYS_INLINE le(const Vectorized& other) const { + return Vectorized{_vec.le(other._vec)}; + } + + Vectorized clamp_min(const Vectorized& min) const { + return Vectorized{_vec.clamp_min(min._vec)}; + } + + Vectorized clamp_max(const Vectorized& max) const { + return Vectorized{_vec.clamp_max(max._vec)}; + } + + Vectorized minimum(const Vectorized& other) const { + return Vectorized{_vec.minimum(other._vec)}; + } + + Vectorized maximum(const Vectorized& other) const { + return Vectorized{_vec.maximum(other._vec)}; + } +}; + +#define ZVECTOR_OPERATORS(typex) \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator+( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() + b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator-( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() - b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator*( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() * b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator/( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() / b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator&( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() & b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator|( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() | b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator^( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() ^ b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator==( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() == b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator!=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() != b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator>( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() > b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator>=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() >= b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator<( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() < b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator<=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() <= b.vec()}; \ + } + +ZVECTOR_OPERATORS(c10::qint32) +ZVECTOR_OPERATORS(c10::qint8) +ZVECTOR_OPERATORS(c10::quint8) + +#undef ZVECTOR_OPERATORS + +DEFINE_CLAMP_MAXMIN_FUNCS(c10::quint8) +DEFINE_CLAMP_MAXMIN_FUNCS(c10::qint8) +DEFINE_CLAMP_MAXMIN_FUNCS(c10::qint32) + +template +constexpr auto real_mask() { + return (ZSimdVect)ZSimdVectBinary{0xFFFFFFFF, 0, 0xFFFFFFFF, 0}; +} + +template <> +constexpr auto real_mask() { + return (ZSimdVect)ZSimdVectBinary{0xFFFFFFFFFFFFFFFF, 0}; +} + +template +constexpr auto image_mask() { + return (ZSimdVect)ZSimdVectBinary{0, 0xFFFFFFFF, 0, 0xFFFFFFFF}; +} + +template <> +constexpr auto image_mask() { + return (ZSimdVect)ZSimdVectBinary{0, 0xFFFFFFFFFFFFFFFF}; +} + +template +constexpr auto rsign_mask() { + return ZSimdVect{-0.f, 0.f, -0.f, 0.f}; +} + +template <> +constexpr auto rsign_mask() { + return ZSimdVect{-0.0, 0.f}; +} + +template +constexpr auto isign_mask() { + return ZSimdVect{0.0, -0.f, 0.0, -0.f}; +} + +template <> +constexpr auto isign_mask() { + return ZSimdVect{0.0, -0.0}; +} + +template +constexpr auto image_one() { + return ZSimdVect{0, 1.f, 0, 1.f}; +} + +template <> +constexpr auto image_one() { + return ZSimdVect{0.0, 1.0}; +} + +template +constexpr auto pi_half() { + return ZSimdVect{(float)(M_PI / 2.0), 0.f, (float)(M_PI / 2.0), 0.f}; +} + +template <> +constexpr auto pi_half() { + return ZSimdVect{M_PI / 2.0, 0.0}; +} + +template +constexpr auto image_half() { + return ZSimdVect{0, 0.5f, 0, 0.5f}; +} + +template <> +constexpr auto image_half() { + return ZSimdVect{0.0, 0.5}; +} + +template +constexpr U log2e_inv() { + return static_cast(1.4426950408889634); +} + +template +constexpr U log10e_inv() { + return static_cast(0.43429448190325176); +} + +template +struct is_vec_specialized_for< + T, + std::enable_if_t()>> + : std::bool_constant {}; + +template +struct Vectorized()>> { + public: + using underline_type = decltype(std::declval().imag()); + using value_type = T; + using vtype = ZSimdVect; + using vmaskType = ZSimdVectBinary; + using vinner_type = Vectorized; + using size_type = int; + using vinner_data = typename Vectorized::vinner_data; + + static constexpr size_type size() { + return VECTOR_WIDTH / sizeof(value_type); + } + + private: + vinner_type _vec; + + public: + Vectorized() = default; + + C10_ALWAYS_INLINE Vectorized(const vinner_data& v) + : _vec{v.first, v.second} {} + + template = 0> + C10_ALWAYS_INLINE Vectorized(T s1, T s2) + : _vec{s1.real(), s1.imag(), s2.real(), s2.imag()} {} + + template = 0> + C10_ALWAYS_INLINE Vectorized(T s1, T s2, T s3, T s4) + : _vec{ + s1.real(), + s1.imag(), + s2.real(), + s2.imag(), + s3.real(), + s3.imag(), + s4.real(), + s4.imag()} {} + + template = 0> + C10_ALWAYS_INLINE Vectorized(T s) : Vectorized(s, s) {} + + template = 0> + C10_ALWAYS_INLINE Vectorized(T s) : Vectorized(s, s, s, s) {} + + C10_ALWAYS_INLINE operator vinner_type() const { + return _vec; + } + + C10_ALWAYS_INLINE const vinner_type& vec() const { + return _vec; + } + + C10_ALWAYS_INLINE operator vinner_data() const { + return _vec.data(); + } + + C10_ALWAYS_INLINE vinner_data data() const { + return _vec.data(); + } + + template + static Vectorized C10_ALWAYS_INLINE + loadu(const U* ptr, int count = size()) { + return Vectorized{vinner_type::loadu(ptr, 2 * count)}; + } + + template + void C10_ALWAYS_INLINE store(U* ptr, int count = size()) const { + return _vec.store(ptr, 2 * count); + } + + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + // convert std::complex index mask to V index mask: xy -> xxyy + vinner_type vmask = mask.vec(); + auto mask_complex = vinner_type( + vec_mergeh(vmask.vec0(), vmask.vec0()), + vec_mergeh(vmask.vec1(), vmask.vec1())); + return Vectorized{vinner_type::blendv(a.vec(), b.vec(), mask_complex)}; + } + + template + static auto C10_ALWAYS_INLINE + blend(const Vectorized& a, const Vectorized& b) { + constexpr int mask_complex = maskForComplex(mask); + return Vectorized{ + vinner_type::template blend(a.vec(), b.vec())}; + } + + template + static std::enable_if_t> arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized(base, base + step); + } + + template + static std::enable_if_t> arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + value_type(2) * step, + base + value_type(3) * step); + } + + template + static inline std::enable_if_t<(Z >= C), Vectorized> set_inner( + const Vectorized& a, + const Vectorized& b, + size_t count) { + return b; + } + + template + static inline std::enable_if_t<(Z < C), Vectorized> set_inner( + const Vectorized& a, + const Vectorized& b, + size_t count) { + if (count == Z) + return blend(a, b); + else + return set_inner(a, b, count); + } + + static Vectorized set( + const Vectorized& a, + const Vectorized& b, + size_t count = size()) { + if (count == 0) + return a; + return set_inner<1, size()>(a, b, count); + } + + const T& operator[](int idx) const = delete; + T& operator[](int idx) = delete; + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + Vectorized mapOrdinary(T (*const f)(const T&)) const { + auto v0 = _vec.vec0(); + auto v1 = _vec.vec1(); + return Vectorized{ + f(T(v0[0], v0[1])), + f(T(v0[2], v0[3])), + f(T(v1[0], v1[1])), + f(T(v1[2], v1[3]))}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + Vectorized mapOrdinary(T (*const f)(const T&)) const { + auto v0 = _vec.vec0(); + auto v1 = _vec.vec1(); + return Vectorized{f(T(v0[0], v0[1])), f(T(v1[0], v1[1]))}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + Vectorized mapOrdinary(T (*const f)(T)) const { + auto v0 = _vec.vec0(); + auto v1 = _vec.vec1(); + return Vectorized{ + f(T(v0[0], v0[1])), + f(T(v0[2], v0[3])), + f(T(v1[0], v1[1])), + f(T(v1[2], v1[3]))}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + Vectorized mapOrdinary(T (*const f)(T)) const { + auto v0 = _vec.vec0(); + auto v1 = _vec.vec1(); + return Vectorized{f(T(v0[0], v0[1])), f(T(v1[0], v1[1]))}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + inline Vectorized mapOrdinary( + T (*const f)(const T&, const T&), + const Vectorized& b) const { + auto v0 = _vec.vec0(); + auto v1 = _vec.vec1(); + auto bvec = b.vec(); + auto b0 = bvec.vec0(); + auto b1 = bvec.vec1(); + T a00 = f(T(v0[0], v0[1]), T(b0[0], b0[1])); + T a01 = f(T(v0[2], v0[3]), T(b0[2], b0[3])); + T a02 = f(T(v1[0], v1[1]), T(b1[0], b1[1])); + T a03 = f(T(v1[2], v1[3]), T(b1[2], b1[3])); + return Vectorized{a00, a01, a02, a03}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + inline Vectorized mapOrdinary( + T (*const f)(const T&, const T&), + const Vectorized& b) const { + auto v0 = _vec.vec0(); + auto v1 = _vec.vec1(); + auto bvec = b.vec(); + auto b0 = bvec.vec0(); + auto b1 = bvec.vec1(); + U a00 = f(U(v0[0], v0[1]), U(b0[0], b0[1])); + U a01 = f(U(v1[0], v1[1]), U(b1[0], b1[1])); + return Vectorized{a00, a01}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + static typename Vectorized::vinner_type real_neg( + const typename Vectorized::vinner_type& a) { + const auto swap_mask = ZSimdVectBinary{ + 0, 1, 2, 3, 20, 21, 22, 23, 8, 9, 10, 11, 28, 29, 30, 31}; + + auto a_neg = a.neg(); + vtype v0 = vec_perm(a_neg.vec0(), a.vec0(), swap_mask); + vtype v1 = vec_perm(a_neg.vec1(), a.vec1(), swap_mask); + return {v0, v1}; + } + + template < + typename U = T, + std::enable_if_t>::value, int> = 0> + static typename Vectorized::vinner_type real_neg( + const typename Vectorized::vinner_type& a) { + auto a_neg = a.neg(); + vtype v0 = {a_neg.vec0()[0], a.vec0()[1]}; + vtype v1 = {a_neg.vec1()[0], a.vec1()[1]}; + return {v0, v1}; + } + + Vectorized angle2_() const { + auto b_a = _vec.swapped(); // b a + return Vectorized{_vec.atan2(b_a).swapped()}; + } + + Vectorized angle() const { + return angle2_().real(); + } + + Vectorized atan() const { + // atan(x) = i/2 * ln((i + z)/(i - z)) + auto ione = Vectorized{vinner_type(image_one())}; + auto sum = ione + *this; + auto sub = ione - *this; + auto ln = (sum / sub).log(); // ln((i + z)/(i - z)) + return ln * + Vectorized{vinner_type(image_half())}; // i/2*ln() + } + + Vectorized atanh() const { + return mapOrdinary(std::atanh); + } + + Vectorized asin() const { + // asin(x) + // = -i*ln(iz + sqrt(1 -z^2)) + // = -i*ln((ai - b) + sqrt(1 - (a + bi)*(a + bi))) + // = -i*ln((-b + ai) + sqrt(1 - (a**2 - b**2) - 2*abi)) +#if 1 + vinner_type cnj = conj().vec(); + vinner_type b_a = cnj.swapped(); + vinner_type ab = cnj * b_a; + vinner_type im = ab + ab; + vinner_type val_2 = _vec * _vec; + vinner_type val_2_swapped = val_2.swapped(); + vinner_type re = vinner_type::horizontal_sub_perm(val_2, val_2_swapped); + re = vinner_type(static_cast(1)) - re; + constexpr int blend_mask = + blend_choice(); // 0x0A for complex , 0xAA for complex + vinner_type blendx = vinner_type::template blend(re, im); + auto root = Vectorized(blendx).sqrt(); + auto ln = Vectorized(Vectorized(b_a) + root).log(); + return Vectorized(ln.vec().swapped()).conj(); +#else + return mapOrdinary(std::asin); +#endif + } + + Vectorized acos() const { + // acos(x) = pi/2 - asin(x) + return Vectorized(vinner_type(pi_half())) - asin(); + } + + Vectorized sin() const { + return mapOrdinary(std::sin); + } + Vectorized sinh() const { + return mapOrdinary(std::sinh); + } + Vectorized cos() const { + return mapOrdinary(std::cos); + } + Vectorized cosh() const { + return mapOrdinary(std::cosh); + } + Vectorized ceil() const { + return Vectorized{_vec.ceil()}; + } + Vectorized floor() const { + return Vectorized{_vec.floor()}; + } + Vectorized neg() const { + return Vectorized(_vec.neg()); + } + Vectorized round() const { + return Vectorized{_vec.round()}; + } + Vectorized tan() const { + return mapOrdinary(std::tan); + } + Vectorized tanh() const { + return mapOrdinary(std::tanh); + } + Vectorized trunc() const { + return Vectorized{_vec.trunc()}; + } + + Vectorized C10_ALWAYS_INLINE eq(const Vectorized& other) const { + auto eq = _vec.eq(other._vec); // compares real and imag individually + // If both real numbers and imag numbers are equal, then the complex numbers + // are equal + auto real = eq & vinner_type(real_mask()); + auto imag = (eq & vinner_type(image_mask())).swapped(); + return Vectorized{real & imag}; + } + Vectorized C10_ALWAYS_INLINE ne(const Vectorized& other) const { + auto ne = _vec.ne(other._vec); // compares real and imag individually + // If either real numbers or imag numbers are not equal, then the complex + // numbers are not equal + auto real = ne & vinner_type(real_mask()); + auto imag = (ne & vinner_type(image_mask())).swapped(); + return Vectorized{real | imag}; + } + + Vectorized real() const { + return Vectorized(_vec & vinner_type(real_mask())); + } + Vectorized imag_() const { + return Vectorized(_vec & vinner_type(image_mask())); + } + Vectorized imag() const { + return Vectorized{ + (_vec & vinner_type(image_mask())).swapped()}; + } + + Vectorized conj() const { + return Vectorized(_vec ^ vinner_type(isign_mask())); + } + + vinner_data abs_2_() const { + auto a = _vec * _vec; + a = a + a.swapped(); + return a.mergee().data(); + } + + static T abs_helper(const T& value) { + return T(std::abs(value)); + } + + Vectorized abs() const { + return mapOrdinary(abs_helper); + } + + Vectorized exp() const { + return mapOrdinary(std::exp); + } + + Vectorized exp2() const { + return mapOrdinary(exp2_impl); + } + + Vectorized expm1() const { + return mapOrdinary(std::expm1); + } + + Vectorized log() const { + return mapOrdinary(std::log); + } + + Vectorized log2() const { + // log2eB_inv + auto ret = log(); + return Vectorized{ret._vec * vinner_type(log2e_inv())}; + } + + Vectorized log10() const { + auto ret = log(); + return Vectorized{ret._vec * vinner_type(log10e_inv())}; + } + + Vectorized log1p() const { + return mapOrdinary(std::log1p); + } + + Vectorized sgn() const { + return mapOrdinary(at::native::sgn_impl); + } + + Vectorized pow(const Vectorized& exp) const { + return mapOrdinary(std::pow, exp); + } + + Vectorized sqrt() const { + return mapOrdinary(std::sqrt); + } + + Vectorized reciprocal() const { + // re + im*i = (a + bi) / (c + di) + // re = (ac + bd)/abs_2() = c/abs_2() + // im = (bc - ad)/abs_2() = d/abs_2() + vinner_type c_d = _vec ^ vinner_type(isign_mask()); + vinner_type abs = abs_2_(); + return Vectorized{c_d / abs}; + } + + Vectorized rsqrt() const { + return sqrt().reciprocal(); + } + + Vectorized lt(const Vectorized& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + + Vectorized le(const Vectorized& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + + Vectorized gt(const Vectorized& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + + Vectorized ge(const Vectorized& other) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } +}; + +#define ZVECTOR_OPERATORS(typex) \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator+( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() + b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator-( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() - b.vec()}; \ + } \ + \ + template <> \ + Vectorized inline operator*( \ + const Vectorized& a, const Vectorized& b) { \ + /* (a + bi) * (c + di) = (ac - bd) + (ad + bc)i */ \ + Vectorized::vinner_type bv = b.vec(); \ + \ + /* this is more z arch friendly than simulating horizontal from x86 */ \ + Vectorized::vinner_type vi = bv.mergeo(); \ + Vectorized::vinner_type vr = bv.mergee(); \ + vi = vi ^ \ + Vectorized::vinner_type( \ + rsign_mask::underline_type>()); \ + Vectorized::vinner_type ret = a.vec() * vr; \ + Vectorized::vinner_type vx_swapped = a.vec().swapped(); \ + ret = fmadd(vx_swapped, vi, ret); \ + \ + return Vectorized{ret}; \ + } \ + \ + template <> \ + Vectorized inline operator/( \ + const Vectorized& a, const Vectorized& b) { \ + /* Unfortunately, this breaks some tests */ \ + /* Implement it like it's done for avx2 */ \ + auto fabs_cd = b.vec().abs(); /* |c| |d| */ \ + auto fabs_dc = fabs_cd.swapped(); /* |d| |c| */ \ + auto scale = Vectorized::vinner_type{1.0} / \ + maximum(fabs_cd, fabs_dc); /* 1/sc 1/sc */ \ + auto a2 = a.vec() * scale; /* a/sc b/sc */ \ + auto b2 = b.vec() * scale; /* c/sc d/sc */ \ + auto acbd2 = a2 * b2; /* ac/sc^2 bd/sc^2 */ \ + \ + auto dc2 = b2.swapped(); /* d/sc c/sc */ \ + dc2 = Vectorized::real_neg(dc2); /* -d/|c,d| c/sc */ \ + auto adbc2 = a2 * dc2; /* -ad/sc^2 bc/sc^2 */ \ + auto sum1 = acbd2 + acbd2.swapped(); /* (ac+bd)/sc^2 (ac+bd)/sc^2 */ \ + auto sum2 = adbc2 + adbc2.swapped(); /* (bc-ad)/sc^2 (bc-ad)/sc^2 */ \ + auto res2 = Vectorized::vinner_type::mergee( \ + sum1, sum2); /* (ac+bd)/sc^2 (bc-ad)/sc^2 */ \ + \ + /* get the denominator */ \ + Vectorized::vinner_type denom2 = \ + Vectorized{b2}.abs_2_(); /* (c^2+d^2)/sc^2 (c^2+d^2)/sc^2 */ \ + res2 = res2 / denom2; \ + return Vectorized{res2}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator&( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() & b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator|( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() | b.vec()}; \ + } \ + \ + template <> \ + Vectorized C10_ALWAYS_INLINE operator^( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() ^ b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator==( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() == b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator!=( \ + const Vectorized& a, const Vectorized& b) { \ + return Vectorized{a.vec() != b.vec()}; \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator<( \ + const Vectorized& a, const Vectorized& b) { \ + TORCH_CHECK(false, "not supported for complex numbers"); \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator<=( \ + const Vectorized& a, const Vectorized& b) { \ + TORCH_CHECK(false, "not supported for complex numbers"); \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator>( \ + const Vectorized& a, const Vectorized& b) { \ + TORCH_CHECK(false, "not supported for complex numbers"); \ + } \ + \ + Vectorized C10_ALWAYS_INLINE operator>=( \ + const Vectorized& a, const Vectorized& b) { \ + TORCH_CHECK(false, "not supported for complex numbers"); \ + } + +ZVECTOR_OPERATORS(c10::complex) +ZVECTOR_OPERATORS(c10::complex) + +#undef ZVECTOR_OPERATORS + +template = 0> +std::pair, Vectorized> inline inner_interleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, a1, a2, a3} + // b = {b0, b1, b2, b3} + using vtype = typename Vectorized::vtype; + vtype ab00 = {a.vec0()[0], b.vec0()[0]}; + vtype ab11 = {a.vec0()[1], b.vec0()[1]}; + vtype ab2_00 = {a.vec1()[0], b.vec1()[0]}; + vtype ab2_11 = {a.vec1()[1], b.vec1()[1]}; + // return {a0, b0, a1, b1} + // {a2, b2, a3, b3} + return std::make_pair( + Vectorized{ab00, ab11}, Vectorized{ab2_00, ab2_11}); +} + +template = 0> +std::pair, Vectorized> inline inner_deinterleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, b0, a1, b1} + // b = {a2, b2, a3, b3} + using vtype = typename Vectorized::vtype; + vtype aa01 = {a.vec0()[0], a.vec1()[0]}; + vtype aa23 = {b.vec0()[0], b.vec1()[0]}; + + vtype bb_01 = {a.vec0()[1], a.vec1()[1]}; + vtype bb_23 = {b.vec0()[1], b.vec1()[1]}; + + // swap lanes: + // return {a0, a1, a2, a3} + // {b0, b1, b2, b3} + return std::make_pair(Vectorized{aa01, aa23}, Vectorized{bb_01, bb_23}); +} + +template = 0> +std::pair, Vectorized> inline inner_interleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, a1, a2, a3,, a4, a5, a6, a7} + // b = {b0, b1, b2, b3,, b4, b5, b6, b7} + using vtype = typename Vectorized::vtype; + vtype ab0011 = vec_mergeh(a.vec0(), b.vec0()); + vtype ab2233 = vec_mergel(a.vec0(), b.vec0()); + + vtype ab2_0011 = vec_mergeh(a.vec1(), b.vec1()); + vtype ab2_2233 = vec_mergel(a.vec1(), b.vec1()); + // group cols crossing lanes: + // return {a0, b0, a1, b1,, a2, b2, a3, b3} + // {a4, b4, a5, b5,, a6, b6, a7, b7} + + return std::make_pair( + Vectorized{ab0011, ab2233}, Vectorized{ab2_0011, ab2_2233}); +} + +template = 0> +std::pair, Vectorized> inline inner_deinterleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, b0, a1, b1,, a2, b2, a3, b3} + // b = {a4, b4, a5, b5,, a6, b6, a7, b7} + using vtype = typename Vectorized::vtype; + // {a0,a2,b0,b2} {a1,a3,b1,b3} + vtype a0a2b0b2 = vec_mergeh(a.vec0(), a.vec1()); + vtype a1a3b1b3 = vec_mergel(a.vec0(), a.vec1()); + + vtype aa0123 = vec_mergeh(a0a2b0b2, a1a3b1b3); + vtype bb0123 = vec_mergel(a0a2b0b2, a1a3b1b3); + + vtype a0a2b0b2_2 = vec_mergeh(b.vec0(), b.vec1()); + vtype a1a3b1b3_2 = vec_mergel(b.vec0(), b.vec1()); + + vtype aa0123_2 = vec_mergeh(a0a2b0b2_2, a1a3b1b3_2); + vtype bb0123_2 = vec_mergel(a0a2b0b2_2, a1a3b1b3_2); + + // it could be done with vec_perm ,too + // swap lanes: + // return {a0, a1, a2, a3,, a4, a5, a6, a7} + // {b0, b1, b2, b3,, b4, b5, b6, b7} + + return std::make_pair( + Vectorized{aa0123, aa0123_2}, Vectorized{bb0123, bb0123_2}); +} + +template <> +std::pair, Vectorized> inline interleave2( + const Vectorized& a, + const Vectorized& b) { + return inner_interleave2(a, b); +} + +template <> +std::pair, Vectorized> inline interleave2( + const Vectorized& a, + const Vectorized& b) { + return inner_interleave2(a, b); +} + +template <> +std::pair, Vectorized> inline interleave2( + const Vectorized& a, + const Vectorized& b) { + return inner_interleave2(a, b); +} + +template <> +std::pair, Vectorized> inline interleave2( + const Vectorized& a, + const Vectorized& b) { + return inner_interleave2(a, b); +} + +template <> +std::pair, Vectorized> inline deinterleave2( + const Vectorized& a, + const Vectorized& b) { + return inner_deinterleave2(a, b); +} + +template <> +std::pair, Vectorized> inline deinterleave2< + int32_t>(const Vectorized& a, const Vectorized& b) { + return inner_deinterleave2(a, b); +} + +template <> +std::pair, Vectorized> inline deinterleave2( + const Vectorized& a, + const Vectorized& b) { + return inner_deinterleave2(a, b); +} + +template <> +std::pair, Vectorized> inline deinterleave2< + int64_t>(const Vectorized& a, const Vectorized& b) { + return inner_deinterleave2(a, b); +} + +template +std::enable_if_t< + std::is_same_v, + at::vec::Vectorized< + float>> inline convert_int8_to_float(const Vectorized& src) { + // Note: this function only convert inputs number of elements equal to + // at::vec::Vectorized.size() Only handle first 64 bits + auto vec_int = src.to_vec_float_helper(); + + return zvec_convert_to_float(vec_int); +} + +template +std::enable_if_t< + std::is_same_v, + at::vec::Vectorized< + T>> inline convert_float_to_int8(const Vectorized& src) { + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + + auto vec_int = clamp( + zvec_convert_to_int(src), + Vectorized(min_val), + Vectorized(max_val)); + + return vec_int.to_vec_uint8_helper(); +} + +#undef DEFINE_CLAMP_MAXMIN_FUNCS +#undef DEFINE_MAXMIN_FUNCS +} // namespace CPU_CAPABILITY +} // namespace vec +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512.h new file mode 100644 index 0000000000000000000000000000000000000000..4961dbf8bdff992080645b35e6a910ad7ea03640 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512.h @@ -0,0 +1,380 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include + +// clang-format off +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// clang-format on + +#include +#include +#include +#include + +namespace at { +namespace vec { + +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CAST (AVX512) +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +inline Vectorized cast(const Vectorized& src) { + return _mm512_castpd_ps(src); +} + +template <> +inline Vectorized cast(const Vectorized& src) { + return _mm512_castps_pd(src); +} + +template <> +inline Vectorized cast(const Vectorized& src) { + return _mm512_castsi512_ps(src); +} + +template <> +inline Vectorized cast( + const Vectorized& src) { + return _mm512_castsi512_pd(src); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GATHER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +#ifndef _MSC_VER +// MSVC is not working well on complex function overload. +template +std::enable_if_t< + scale == 1 || scale == 2 || scale == 4 || scale == 8, + Vectorized< + double>> inline gather(const double* base_addr, const Vectorized& vindex) { + return _mm512_i64gather_pd(vindex, base_addr, scale); +} + +template +std::enable_if_t< + scale == 1 || scale == 2 || scale == 4 || scale == 8, + Vectorized< + float>> inline gather(const float* base_addr, const Vectorized& vindex) { + return _mm512_i32gather_ps(vindex, base_addr, scale); +} +#endif +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MASK GATHER ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +#ifndef _MSC_VER +// MSVC is not working well on complex function overload. +template +std:: + enable_if_t> inline mask_gather( + const Vectorized& src, + const double* base_addr, + const Vectorized& vindex, + Vectorized& mask) { + auto all_ones = _mm512_castsi512_pd(_mm512_set1_epi64(0xFFFFFFFFFFFFFFFF)); + auto mask_ = _mm512_cmp_pd_mask(all_ones, mask.values, _CMP_EQ_OQ); + return _mm512_mask_i64gather_pd(src, mask_, vindex, base_addr, scale); +} + +template +std:: + enable_if_t> inline mask_gather( + const Vectorized& src, + const float* base_addr, + const Vectorized& vindex, + Vectorized& mask) { + auto all_ones = _mm512_castsi512_ps(_mm512_set1_epi32(0xFFFFFFFF)); + auto mask_ = _mm512_cmp_ps_mask(all_ones, mask.values, _CMP_EQ_OQ); + return _mm512_mask_i32gather_ps(src, mask_, vindex, base_addr, scale); +} +#endif +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CONVERT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +Vectorized inline convert_to_int_of_same_size( + const Vectorized& src) { + return _mm512_cvtpd_epi64(src); +} + +template <> +Vectorized inline convert_to_int_of_same_size( + const Vectorized& src) { + return _mm512_cvttps_epi32(src); +} + +template <> +Vectorized inline convert_to_fp_of_same_size( + const Vectorized& src) { + return _mm512_cvtepi64_pd(src); +} + +template <> +Vectorized inline convert_to_fp_of_same_size( + const Vectorized& src) { + return _mm512_cvtepi32_ps(src); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTERLEAVE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +std::pair, Vectorized> inline interleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, a1, a3, a3, a4, a5, a6, a7} + // b = {b0, b1, b2, b3, b4, b5, b6, b7} + // group cols crossing lanes: + // return {a0, b0, a1, b1, a2, b2, a3, b3} + // {a4, b4, a5, b5, a6, b6, a7, b7} + __m512i idx1 = _mm512_set_epi64(11, 3, 10, 2, 9, 1, 8, 0); + __m512i idx2 = _mm512_set_epi64(15, 7, 14, 6, 13, 5, 12, 4); + return std::make_pair( + _mm512_mask_permutex2var_pd(a, 0xff, idx1, b), + _mm512_mask_permutex2var_pd(a, 0xff, idx2, b)); +} + +template <> +std::pair, Vectorized> inline interleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, + // a15} b = {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, + // b14, b15} + // + // return: + // {a0, b0, a1, b1, a2, b2, a3, b3, a4, b4, a5, b5, a6, b6, a7, b7} + // {a8, b8, a9, b9, a10, b10, a11, b11, a12, b12, a13, b13, a14, b14, a15, + // b15} + __m512i idx1 = + _mm512_set_epi32(23, 7, 22, 6, 21, 5, 20, 4, 19, 3, 18, 2, 17, 1, 16, 0); + __m512i idx2 = _mm512_set_epi32( + 31, 15, 30, 14, 29, 13, 28, 12, 27, 11, 26, 10, 25, 9, 24, 8); + return std::make_pair( + _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b), + _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b)); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DEINTERLEAVE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +std::pair, Vectorized> inline deinterleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, b0, a1, b1, a2, b2, a3, b3} + // b = {a4, b4, a5, b5, a6, b6, a7, b7} + // output: + // return {a0, a1, a2, a3, a4, a5, a6, a7} + // {b0, b1, b2, b3, b4, b5, b6, b7} + // The members of indices have been written in binary format for better + // understandability + __m512i idx1 = _mm512_set_epi64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i idx2 = _mm512_set_epi64(15, 13, 11, 9, 7, 5, 3, 1); + + return std::make_pair( + _mm512_mask_permutex2var_pd(a, 0xff, idx1, b), + _mm512_mask_permutex2var_pd(a, 0xff, idx2, b)); +} + +template <> +std::pair, Vectorized> inline deinterleave2( + const Vectorized& a, + const Vectorized& b) { + // inputs: + // a = {a0, b0, a1, b1, a2, b2, a3, b3, a4, b4, a5, b5, a6, b6, a7, b7} + // b = {a8, b8, a9, b9, a10, b10, a11, b11, a12, b12, a13, b13, a14, b14, + // a15, b15} + // output: + // return {a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, + // a15} + // {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, + // b15} + __m512i idx1 = _mm512_set_epi32( + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i idx2 = _mm512_set_epi32( + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + return std::make_pair( + _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b), + _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b)); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLIP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template <> +inline Vectorized flip(const Vectorized& v) { + const __m512i mask = + _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + return _mm512_permutexvar_ps(mask, v); +} + +template <> +inline Vectorized flip(const Vectorized& v) { + const __m512i mask = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); + return _mm512_permutexvar_pd(mask, v); +} + +template <> +inline Vectorized flip(const Vectorized& v) { + const __m512i mask = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); + return _mm512_permutexvar_epi64(mask, v); +} + +template <> +inline Vectorized flip(const Vectorized& v) { + const __m512i mask = + _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + return _mm512_permutexvar_epi32(mask, v); +} + +template <> +inline Vectorized flip(const Vectorized& v) { + const __m512i mask = _mm512_set_epi16( + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31); + return _mm512_permutexvar_epi16(mask, v); +} + +inline __m512i flip8(const __m512i& v) { + const __m512i mask1 = _mm512_set_epi8( + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15); + const __m512i mask2 = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); + auto reversed_vec = _mm512_shuffle_epi8(v, mask1); + return _mm512_permutexvar_epi64(mask2, reversed_vec); +} + +template <> +inline Vectorized flip(const Vectorized& v) { + return flip8(v); +} + +template <> +inline Vectorized flip(const Vectorized& v) { + return flip8(v); +} + +inline Vectorized operator&&( + const Vectorized& self, + const Vectorized& other) { + const __m512i* self_ = reinterpret_cast(self.as_bytes()); + const __m512i* other_ = reinterpret_cast(other.as_bytes()); + __m512i out = _mm512_and_si512(*self_, *other_); + Vectorized ret; + // We do not have a constructor that takes __m512i, so we need to memcpy + std::memcpy(ret, &out, ret.size() * sizeof(bool)); + return ret; +} + +#endif // defined(CPU_CAPABILITY_AVX512) + +} // namespace CPU_CAPABILITY +} // namespace vec +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h new file mode 100644 index 0000000000000000000000000000000000000000..f3181b601ed0a20fae28af1850ea0423c33c6474 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h @@ -0,0 +1,1942 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include + +#if defined(CPU_CAPABILITY_AVX512) +#define SLEEF_STATIC_LIBS +#include +#endif + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +#ifndef SLEEF_CONST +#if (defined(__GNUC__) || defined(__CLANG__)) && !defined(__INTEL_COMPILER) +#define SLEEF_CONST const +#else +#define SLEEF_CONST +#endif +#define SLEEF_CONST_OLD SLEEF_CONST +#else +#define SLEEF_CONST_OLD +#endif + +// bfloat16 conversion +static inline void cvtbf16_fp32(const __m256i& a, __m512& o) { + o = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(a), 16)); +} + +static inline void cvtbf16_fp32(const __m512i& a, __m512& o1, __m512& o2) { + __m256i lo = _mm512_extracti32x8_epi32(a, 0); + __m256i hi = _mm512_extracti32x8_epi32(a, 1); + cvtbf16_fp32(lo, o1); + cvtbf16_fp32(hi, o2); +} + +static inline __m256i cvtfp32_bf16(const __m512& src) { + __m512i value = _mm512_castps_si512(src); + __m512i nan = _mm512_set1_epi32(0xffff); + auto mask_value = _mm512_cmp_ps_mask(src, src, _CMP_ORD_Q); + __m512i ones = _mm512_set1_epi32(0x1); + __m512i vec_bias = _mm512_set1_epi32(0x7fff); + // uint32_t lsb = (input >> 16) & 1; + auto t_value = _mm512_and_si512(_mm512_srli_epi32(value, 16), ones); + // uint32_t rounding_bias = 0x7fff + lsb; + t_value = _mm512_add_epi32(t_value, vec_bias); + // input += rounding_bias; + t_value = _mm512_add_epi32(t_value, value); + // input = input >> 16; + t_value = _mm512_srli_epi32(t_value, 16); + // Check NaN before converting back to bf16 + t_value = _mm512_mask_blend_epi32(mask_value, nan, t_value); + return _mm512_cvtusepi32_epi16(t_value); +} + +static inline __m512i cvtfp32_bf16(const __m512& a, const __m512& b) { + __m512i lo = _mm512_castps_si512(a); + __m512i hi = _mm512_castps_si512(b); + __m512i nan = _mm512_set1_epi32(0xffff); + auto mask_lo = _mm512_cmp_ps_mask(a, a, _CMP_ORD_Q); + auto mask_hi = _mm512_cmp_ps_mask(b, b, _CMP_ORD_Q); + __m512i ones = _mm512_set1_epi32(0x1); + __m512i vec_bias = _mm512_set1_epi32(0x7fff); + // uint32_t lsb = (input >> 16) & 1; + auto t_lo = _mm512_and_si512(_mm512_srli_epi32(lo, 16), ones); + auto t_hi = _mm512_and_si512(_mm512_srli_epi32(hi, 16), ones); + // uint32_t rounding_bias = 0x7fff + lsb; + t_lo = _mm512_add_epi32(t_lo, vec_bias); + t_hi = _mm512_add_epi32(t_hi, vec_bias); + // input += rounding_bias; + t_lo = _mm512_add_epi32(t_lo, lo); + t_hi = _mm512_add_epi32(t_hi, hi); + // input = input >> 16; + t_lo = _mm512_srli_epi32(t_lo, 16); + t_hi = _mm512_srli_epi32(t_hi, 16); + // Check NaN before converting back to bf16 + t_lo = _mm512_mask_blend_epi32(mask_lo, nan, t_lo); + t_hi = _mm512_mask_blend_epi32(mask_hi, nan, t_hi); + + t_lo = _mm512_packus_epi32( + t_lo, t_hi); // t_hi[4-7] t_lo[4-7] t_hi[0-4] t_lo[0-4] + __m512i idx = _mm512_set_epi64(7, 5, 3, 1, 6, 4, 2, 0); + return _mm512_permutexvar_epi64(idx, t_lo); +} + +static inline __m512i merge_compare_result(const __m512& a, const __m512& b) { + __m512i lo = _mm512_castps_si512(a); + __m512i hi = _mm512_castps_si512(b); + lo = _mm512_srli_epi32(lo, 16); + hi = _mm512_srli_epi32(hi, 16); + auto out = _mm512_packus_epi32(lo, hi); + __m512i idx = _mm512_set_epi64(7, 5, 3, 1, 6, 4, 2, 0); + return _mm512_permutexvar_epi64(idx, out); +} + +// float16 conversion +static inline void cvtfp16_fp32(const __m256i& a, __m512& o) { + o = _mm512_cvtph_ps(a); +} + +static inline void cvtfp16_fp32(const __m512i& a, __m512& o1, __m512& o2) { + __m256i lo = _mm512_extracti32x8_epi32(a, 0); + __m256i hi = _mm512_extracti32x8_epi32(a, 1); + cvtfp16_fp32(lo, o1); + cvtfp16_fp32(hi, o2); +} + +static inline __m256i cvtfp32_fp16(const __m512& src) { + return _mm512_cvtps_ph(src, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); +} + +static inline __m512i cvtfp32_fp16(const __m512& a, const __m512& b) { + __m256i lo = + _mm512_cvtps_ph(a, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + __m256i hi = + _mm512_cvtps_ph(b, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + __m512 t_lo = _mm512_castsi512_ps(_mm512_castsi256_si512(lo)); + __m256 t_hi = _mm256_castsi256_ps(hi); + return _mm512_castps_si512(_mm512_insertf32x8(t_lo, t_hi, 1)); +} + +// dtype conversion between float16/bfloat16 and float32 +template < + typename T, + typename std::enable_if_t, int> = 0> +inline void cvt_to_fp32(const __m256i& a, __m512& o); +template <> +inline void cvt_to_fp32(const __m256i& a, __m512& o) { + cvtbf16_fp32(a, o); +} +template <> +inline void cvt_to_fp32(const __m256i& a, __m512& o) { + cvtfp16_fp32(a, o); +} + +template < + typename T, + typename std::enable_if_t, int> = 0> +inline void cvt_to_fp32(const __m512i& a, __m512& o1, __m512& o2); +template <> +inline void cvt_to_fp32(const __m512i& a, __m512& o1, __m512& o2) { + cvtbf16_fp32(a, o1, o2); +} +template <> +inline void cvt_to_fp32(const __m512i& a, __m512& o1, __m512& o2) { + cvtfp16_fp32(a, o1, o2); +} + +template < + typename T, + bool is_compare_op = false, + typename std::enable_if_t, int> = 0> +inline __m512i cvt_from_fp32(const __m512& a, const __m512& b); +template <> +inline __m512i cvt_from_fp32( + const __m512& a, + const __m512& b) { + return cvtfp32_bf16(a, b); +} +template <> +inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return merge_compare_result(a, b); +} +template <> +inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return cvtfp32_fp16(a, b); +} +template <> +inline __m512i cvt_from_fp32(const __m512& a, const __m512& b) { + return cvtfp32_fp16(a, b); +} + +template +class Vectorized16 { + static_assert( + is_reduced_floating_point_v, + "Support only float16 and bfloat16."); + + private: + __m512i values; + + public: + using value_type = uint16_t; + using size_type = int; + static constexpr size_type size() { + return 32; + } + Vectorized16() { + values = _mm512_setzero_si512(); + } + Vectorized16(__m512i v) : values(v) {} + Vectorized16(T val) { + value_type uw = val.x; + values = _mm512_set1_epi16(uw); + } + Vectorized16( + T val1, + T val2, + T val3, + T val4, + T val5, + T val6, + T val7, + T val8, + T val9, + T val10, + T val11, + T val12, + T val13, + T val14, + T val15, + T val16, + T val17, + T val18, + T val19, + T val20, + T val21, + T val22, + T val23, + T val24, + T val25, + T val26, + T val27, + T val28, + T val29, + T val30, + T val31, + T val32) { + values = _mm512_set_epi16( + val32.x, + val31.x, + val30.x, + val29.x, + val28.x, + val27.x, + val26.x, + val25.x, + val24.x, + val23.x, + val22.x, + val21.x, + val20.x, + val19.x, + val18.x, + val17.x, + val16.x, + val15.x, + val14.x, + val13.x, + val12.x, + val11.x, + val10.x, + val9.x, + val8.x, + val7.x, + val6.x, + val5.x, + val4.x, + val3.x, + val2.x, + val1.x); + } + operator __m512i() const { + return values; + } + T& operator[](int idx) = delete; + const T& operator[](int idx) const = delete; + int zero_mask() const { + // returns an integer mask where all zero elements are translated to 1-bit + // and others are translated to 0-bit + return _mm512_cmpeq_epi16_mask(values, _mm512_set1_epi16(0)); + } + static Vectorized loadu(const void* ptr, int16_t count = size()) { + if (count == size()) + return _mm512_loadu_si512(reinterpret_cast(ptr)); + + __mmask32 mask = (1ULL << count) - 1; + return _mm512_maskz_loadu_epi16(mask, ptr); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + __mmask32 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi16(ptr, mask, values); + } + } + template + static Vectorized blend(const Vectorized& a, const Vectorized& b) { + return _mm512_mask_blend_epi16(mask, a.values, b.values); + } + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto all_ones = _mm512_set1_epi16(0xFFFF); + auto mask_ = _mm512_cmp_epi16_mask(mask, all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi16(mask_, a.values, b.values); + } + template + static Vectorized arange( + T base = 0.f, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step, + base + 16 * step, + base + 17 * step, + base + 18 * step, + base + 19 * step, + base + 20 * step, + base + 21 * step, + base + 22 * step, + base + 23 * step, + base + 24 * step, + base + 25 * step, + base + 26 * step, + base + 27 * step, + base + 28 * step, + base + 29 * step, + base + 30 * step, + base + 31 * step); + } + static Vectorized set( + const Vectorized& a, + const Vectorized& b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + case 8: + return blend<255>(a, b); + case 9: + return blend<511>(a, b); + case 10: + return blend<1023>(a, b); + case 11: + return blend<2047>(a, b); + case 12: + return blend<4095>(a, b); + case 13: + return blend<8191>(a, b); + case 14: + return blend<16383>(a, b); + case 15: + return blend<32767>(a, b); + case 16: + return blend<65535>(a, b); + case 17: + return blend<131071>(a, b); + case 18: + return blend<262143>(a, b); + case 19: + return blend<524287>(a, b); + case 20: + return blend<1048575>(a, b); + case 21: + return blend<2097151>(a, b); + case 22: + return blend<4194303>(a, b); + case 23: + return blend<8388607>(a, b); + case 24: + return blend<16777215>(a, b); + case 25: + return blend<33554431>(a, b); + case 26: + return blend<67108863>(a, b); + case 27: + return blend<134217727>(a, b); + case 28: + return blend<268435455>(a, b); + case 29: + return blend<536870911>(a, b); + case 30: + return blend<1073741823>(a, b); + case 31: + return blend<2147483647>(a, b); + } + return b; + } +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wignored-qualifiers" + + Vectorized map(SLEEF_CONST __m512 (*SLEEF_CONST_OLD vop)(__m512)) const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + const auto o1 = vop(lo); + const auto o2 = vop(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized isnan() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + __mmask16 lo_mask, hi_mask; + __m512 zero = _mm512_set1_ps(0.0); + __m512i zeroi = _mm512_castps_si512(zero); + lo_mask = _mm512_cmp_ps_mask(lo, zero, _CMP_UNORD_Q); + lo = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zeroi, lo_mask, 0xFFFF'FFFF)); + hi_mask = _mm512_cmp_ps_mask(hi, zero, _CMP_UNORD_Q); + hi = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zeroi, hi_mask, 0xFFFF'FFFF)); + return merge_compare_result(lo, hi); + } +#pragma clang diagnostic pop + Vectorized abs() const { + return _mm512_andnot_si512(_mm512_set1_epi16(0x8000), values); + } + Vectorized angle() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto angle_lambda = [](__m512 values) { + const auto zero_vec = _mm512_set1_ps(0.f); + const auto nan_vec = _mm512_set1_ps(NAN); + const auto not_nan_mask = _mm512_cmp_ps_mask(values, values, _CMP_EQ_OQ); + const auto non_nan_mask_vec = _mm512_mask_set1_epi32( + _mm512_castps_si512(zero_vec), not_nan_mask, 0xFFFFFFFF); + const auto nan_mask = _mm512_cmp_ps_mask( + _mm512_castsi512_ps(non_nan_mask_vec), zero_vec, _CMP_EQ_OQ); + const auto pi = _mm512_set1_ps(c10::pi); + + const auto neg_mask = _mm512_cmp_ps_mask(values, zero_vec, _CMP_LT_OQ); + auto angle = _mm512_mask_blend_ps(neg_mask, zero_vec, pi); + angle = _mm512_mask_blend_ps(nan_mask, angle, nan_vec); + return angle; + }; + auto o1 = angle_lambda(lo); + auto o2 = angle_lambda(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_epi16(0); + } + Vectorized conj() const { + return *this; + } + Vectorized acos() const { + return map(Sleef_acosf16_u10); + } + Vectorized acosh() const { + return map(Sleef_acoshf16_u10); + } + Vectorized asin() const { + return map(Sleef_asinf16_u10); + } + Vectorized asinh() const { + return map(Sleef_asinhf16_u10); + } + Vectorized atan() const { + return map(Sleef_atanf16_u10); + } + Vectorized atanh() const { + return map(Sleef_atanhf16_u10); + } + Vectorized atan2(const Vectorized& b) const { + __m512 lo, hi; + __m512 b1, b2; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(b.values, b1, b2); + auto o1 = Sleef_atan2f16_u10(lo, b1); + auto o2 = Sleef_atan2f16_u10(hi, b2); + return cvt_from_fp32(o1, o2); + } + Vectorized copysign(const Vectorized& sign) const { + // copy sign bit (0x8000) from sign and remaining bits from values + __m512i mask_value = _mm512_set1_epi32(~0x80008000); + __m512i mask_signbit = _mm512_set1_epi32(0x80008000); + return Vectorized(_mm512_or_si512( + _mm512_and_si512(values, mask_value), + _mm512_and_si512(sign, mask_signbit))); + } + Vectorized erf() const { + return map(Sleef_erff16_u10); + } + Vectorized erfc() const { + return map(Sleef_erfcf16_u15); + } + Vectorized erfinv() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + for (int64_t i = 0; i < size() / 2; i++) { + tmp1[i] = calc_erfinv(tmp1[i]); + tmp2[i] = calc_erfinv(tmp2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized exp() const { + return map(Sleef_expf16_u10); + } + Vectorized exp2() const { + return map(Sleef_exp2f16_u10); + } + Vectorized expm1() const { + return map(Sleef_expm1f16_u10); + } + Vectorized fexp_u20() const { + return exp(); + } + Vectorized exp_u20() const { + return exp(); + } + Vectorized fmod(const Vectorized& q) const { + __m512 x_lo, x_hi; + cvt_to_fp32(values, x_lo, x_hi); + __m512 q_lo, q_hi; + cvtbf16_fp32(q.values, q_lo, q_hi); + auto o1 = Sleef_fmodf16(x_lo, q_lo); + auto o2 = Sleef_fmodf16(x_hi, q_hi); + return cvt_from_fp32(o1, o2); + } + Vectorized hypot(const Vectorized& b) const { + __m512 lo, hi; + __m512 b1, b2; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(b.values, b1, b2); + auto o1 = Sleef_hypotf16_u05(lo, b1); + auto o2 = Sleef_hypotf16_u05(hi, b2); + return cvt_from_fp32(o1, o2); + } + Vectorized i0() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + for (int64_t i = 0; i < size() / 2; i++) { + tmp1[i] = calc_i0(tmp1[i]); + tmp2[i] = calc_i0(tmp2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized i0e() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + constexpr auto sz = size(); + __at_align__ float tmp1[sz / 2], tmp2[sz / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + + for (auto i = decltype(sz){0}; i < sz / 2; i++) { + tmp1[i] = calc_i0e(tmp1[i]); + tmp2[i] = calc_i0e(tmp2[i]); + } + const auto o1 = _mm512_loadu_ps(tmp1); + const auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized digamma() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + constexpr auto sz = size(); + __at_align__ float tmp1[sz / 2], tmp2[sz / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + + for (auto i = decltype(sz){0}; i < sz / 2; i++) { + tmp1[i] = calc_digamma(tmp1[i]); + tmp2[i] = calc_digamma(tmp2[i]); + } + const auto o1 = _mm512_loadu_ps(tmp1); + const auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized igamma(const Vectorized& x) const { + __m512 lo, hi; + __m512 xlo, xhi; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(x.values, xlo, xhi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + __at_align__ float tmpx1[size() / 2], tmpx2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmpx1), xlo); + _mm512_storeu_ps(reinterpret_cast(tmpx2), xhi); + for (int64_t i = 0; i < size() / 2; ++i) { + tmp1[i] = calc_igamma(tmp1[i], tmpx1[i]); + tmp2[i] = calc_igamma(tmp2[i], tmpx2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + + Vectorized igammac(const Vectorized& x) const { + __m512 lo, hi; + __m512 xlo, xhi; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(x.values, xlo, xhi); + __at_align__ float tmp1[size() / 2], tmp2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmp1), lo); + _mm512_storeu_ps(reinterpret_cast(tmp2), hi); + __at_align__ float tmpx1[size() / 2], tmpx2[size() / 2]; + _mm512_storeu_ps(reinterpret_cast(tmpx1), xlo); + _mm512_storeu_ps(reinterpret_cast(tmpx2), xhi); + for (int64_t i = 0; i < size() / 2; ++i) { + tmp1[i] = calc_igammac(tmp1[i], tmpx1[i]); + tmp2[i] = calc_igammac(tmp2[i], tmpx2[i]); + } + auto o1 = _mm512_loadu_ps(tmp1); + auto o2 = _mm512_loadu_ps(tmp2); + return cvt_from_fp32(o1, o2); + } + Vectorized log() const { + return map(Sleef_logf16_u10); + } + Vectorized log2() const { + return map(Sleef_log2f16_u10); + } + Vectorized log10() const { + return map(Sleef_log10f16_u10); + } + Vectorized log1p() const { + return map(Sleef_log1pf16_u10); + } + Vectorized sin() const { + return map(Sleef_sinf16_u10); + } + Vectorized sinh() const { + return map(Sleef_sinhf16_u10); + } + Vectorized cos() const { + return map(Sleef_cosf16_u10); + } + Vectorized cosh() const { + return map(Sleef_coshf16_u10); + } + Vectorized ceil() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_ceil_ps(lo); + auto o2 = _mm512_ceil_ps(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized floor() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_floor_ps(lo); + auto o2 = _mm512_floor_ps(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized neg() const { + return _mm512_xor_si512(values, _mm512_set1_epi16(0x8000)); + } + Vectorized round() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_roundscale_ps( + lo, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + auto o2 = _mm512_roundscale_ps( + hi, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + return cvt_from_fp32(o1, o2); + } + Vectorized tan() const { + return map(Sleef_tanf16_u10); + } + Vectorized tanh() const { + return map(Sleef_tanhf16_u10); + } + Vectorized trunc() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = + _mm512_roundscale_ps(lo, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + auto o2 = + _mm512_roundscale_ps(hi, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + return cvt_from_fp32(o1, o2); + } + Vectorized lgamma() const { + return map(Sleef_lgammaf16_u10); + } + Vectorized sqrt() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto o1 = _mm512_sqrt_ps(lo); + auto o2 = _mm512_sqrt_ps(hi); + return cvt_from_fp32(o1, o2); + } + Vectorized reciprocal() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto ones = _mm512_set1_ps(1); + auto o1 = _mm512_div_ps(ones, lo); + auto o2 = _mm512_div_ps(ones, hi); + return cvt_from_fp32(o1, o2); + } + Vectorized rsqrt() const { + __m512 lo, hi; + cvt_to_fp32(values, lo, hi); + auto ones = _mm512_set1_ps(1); + auto o1 = _mm512_div_ps(ones, _mm512_sqrt_ps(lo)); + auto o2 = _mm512_div_ps(ones, _mm512_sqrt_ps(hi)); + return cvt_from_fp32(o1, o2); + } + Vectorized pow(const Vectorized& b) const { + __m512 lo, hi; + __m512 b1, b2; + cvt_to_fp32(values, lo, hi); + cvt_to_fp32(b.values, b1, b2); + auto o1 = Sleef_powf16_u10(lo, b1); + auto o2 = Sleef_powf16_u10(hi, b2); + return cvt_from_fp32(o1, o2); + } + + private: + template + Vectorized inline binary_compare(const VectorizedType& b, Op op) const { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvt_to_fp32(values, a_lo, a_hi); + cvt_to_fp32(b.values, b_lo, b_hi); + auto o1 = op(a_lo, b_lo); + auto o2 = op(a_hi, b_hi); + return cvt_from_fp32(o1, o2); + } + + public: + Vectorized inline operator>(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_GT_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator<(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_LT_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator>=(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_GE_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator<=(const Vectorized& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_LE_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator==(const Vectorized16& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_EQ_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + Vectorized inline operator!=(const Vectorized16& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_NEQ_UQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } +}; + +template +static inline Vectorized binary_op_as_fp32( + const Vectorized& a, + const Vectorized& b, + Op op) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvt_to_fp32(__m512i(a), a_lo, a_hi); + cvt_to_fp32(__m512i(b), b_lo, b_hi); + auto o1 = op(a_lo, b_lo); + auto o2 = op(a_hi, b_hi); + return cvt_from_fp32(o1, o2); +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized : public Vectorized16 { + public: + using Vectorized16::Vectorized16; + + using value_type = BFloat16; + + Vectorized frac() const; + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_add_ps(x, y); + }); +} +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_sub_ps(x, y); + }); +} +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_mul_ps(x, y); + }); +} +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_div_ps(x, y); + }); +} +Vectorized inline operator&( + const Vectorized& a, + const Vectorized& b) { + return _mm512_and_si512(a, b); +} +Vectorized inline operator|( + const Vectorized& a, + const Vectorized& b) { + return _mm512_or_si512(a, b); +} +Vectorized inline operator^( + const Vectorized& a, + const Vectorized& b) { + return _mm512_xor_si512(a, b); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +// frac. Implement this here so we can use subtraction +inline Vectorized Vectorized::frac() const { + return *this - this->trunc(); +} + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(b), b_lo, b_hi); + auto max_lo = _mm512_max_ps(a_lo, b_lo); + auto max_hi = _mm512_max_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps(_mm512_set1_epi32(nan_lo_mask)); + auto nan_hi = _mm512_castsi512_ps(_mm512_set1_epi32(nan_hi_mask)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(max_lo, nan_lo); + auto o2 = _mm512_or_ps(max_hi, nan_hi); + return cvtfp32_bf16(o1, o2); +} + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512i zero_vec = _mm512_set1_epi32(0); + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(b), b_lo, b_hi); + auto min_lo = _mm512_min_ps(a_lo, b_lo); + auto min_hi = _mm512_min_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, nan_lo_mask, 0xFFFFFFFF)); + auto nan_hi = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, nan_hi_mask, 0xFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(min_lo, nan_lo); + auto o2 = _mm512_or_ps(min_hi, nan_hi); + return cvtfp32_bf16(o1, o2); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min, + const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + __m512 max_lo, max_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(min), min_lo, min_hi); + cvtbf16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, _mm512_max_ps(min_lo, a_lo)); + auto o2 = _mm512_min_ps(max_hi, _mm512_max_ps(min_hi, a_hi)); + return cvtfp32_bf16(o1, o2); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 max_lo, max_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, a_lo); + auto o2 = _mm512_min_ps(max_hi, a_hi); + return cvtfp32_bf16(o1, o2); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(min), min_lo, min_hi); + auto o1 = _mm512_max_ps(min_lo, a_lo); + auto o2 = _mm512_max_ps(min_hi, a_hi); + return cvtfp32_bf16(o1, o2); +} + +template <> +inline void convert(const BFloat16* src, BFloat16* dst, int64_t n) { + int64_t i; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + auto vsrc = + _mm512_loadu_si512(reinterpret_cast<__m512i*>((void*)(src + i))); + _mm512_storeu_si512(reinterpret_cast<__m512i*>((void*)(dst + i)), vsrc); + } +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = src[i]; + } +} + +template <> +inline void convert(const float* src, BFloat16* dst, int64_t n) { + int64_t i; + for (i = 0; i + Vectorized::size() <= n; + i += Vectorized::size()) { + __m512 a = _mm512_loadu_ps(&src[i]); + __m512 b = _mm512_loadu_ps(&src[i + 16]); + + __m512i bf = cvtfp32_bf16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +inline void convert(const double* src, BFloat16* dst, int64_t n) { + auto load_float = [](const double* src) -> __m512 { + // Load one float vector from an array of doubles + __m256 a = _mm512_cvtpd_ps(_mm512_loadu_pd(src)); + __m256 b = _mm512_cvtpd_ps(_mm512_loadu_pd(src + 8)); + return _mm512_insertf32x8(_mm512_castps256_ps512(a), b, 1); + }; + + int64_t i; + for (i = 0; i + Vectorized::size() <= n; + i += Vectorized::size()) { + __m512 a = load_float(&src[i]); + __m512 b = load_float(&src[i + 16]); + + __m512i bf = cvtfp32_bf16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +Vectorized inline fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512 c_lo, c_hi; + cvtbf16_fp32(__m512i(a), a_lo, a_hi); + cvtbf16_fp32(__m512i(b), b_lo, b_hi); + cvtbf16_fp32(__m512i(c), c_lo, c_hi); + auto o1 = _mm512_fmadd_ps(a_lo, b_lo, c_lo); + auto o2 = _mm512_fmadd_ps(a_hi, b_hi, c_hi); + return cvtfp32_bf16(o1, o2); +} + +static inline void _transpose_mxn_half_16_16(__m256i t[], __m512i u[]) { + __m512i r[8]; + // a0a1 a2a3 a4a5 a6a7 a8a9 a10a11 a12a13 a14a15 e0e1 e2e3 e4e5 e6e7 e8e9 + // e10e11 e12e13 e14e15 b0-b15 f0-f15 c0-c15 g0-g15 d0-d15 h0-h15 i0-i15 + // m0-m15 j0-j15 n0-n15 k0-k15 o0-o15 l0-l15 p0-p15 +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 4; i++) { + r[i] = _mm512_inserti64x4(_mm512_castsi256_si512(t[i]), t[i + 4], 0x01); + r[i + 4] = + _mm512_inserti64x4(_mm512_castsi256_si512(t[i + 8]), t[i + 12], 0x01); + } + + // u0: a0a1 b0b1 a2a3 b2b3 a8a9 b8b9 a10a11 b10b11 e0e1 f0f1 e2e3 f2f3 e8e9 + // f8f9 e10e11 f10f11 u1: a4a5 b4b5 a6a7 b6b7 a12a13 b12b13 a14a15 b14b15 e4e5 + // f4f5 e6e7 f6f7 e12e13 f12f13 e14e15 f14f15 u2: c0c1 d0d1 c2c3 d2d3 c8c9 + // d8d9 c10c11 d10d11 g0g1 h0h1 g2g3 h2h3 g8g9 h8h9 g10g11 h10h11 u3: c4c5 + // d4b5 c6c7 d6b7 c12c13 d12d13 c14c15 d14d15 g4g5 h4h5 g6g7 h6h7 g12g13 + // h12h13 g14g15 h14h15 i j m n k l o p +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 8; i += 2) { + u[i] = _mm512_unpacklo_epi32(r[i], r[i + 1]); + u[i + 1] = _mm512_unpackhi_epi32(r[i], r[i + 1]); + } + + // r0: a0a1 b0b1 c0c1 d0d1 a8a9 b8b9 c8c9 d8d9 e0e1 f0f1 g0g1 h0h1 e8e9 f8f9 + // g8g9 h8h9 r1: a2a3 b2b3 c2c3 d2d3 a10a11 b10b11 c10c11 d10d11 e2e3 f2f3 + // g2g3 h2h3 e10e11 f10f11 g10g11 h10h11 r2: a4a5 b4b5 c4c5 d4b5 a12a13 b12b13 + // c12c13 d12d13 r3: a6a7 b6b7 c6c7 d6b7 a14a15 b14b15 c14c15 d14d15 r4: i j k + // l m n o p + r[0] = _mm512_unpacklo_epi64(u[0], u[2]); + r[1] = _mm512_unpackhi_epi64(u[0], u[2]); + r[2] = _mm512_unpacklo_epi64(u[1], u[3]); + r[3] = _mm512_unpackhi_epi64(u[1], u[3]); + r[4] = _mm512_unpacklo_epi64(u[4], u[6]); + r[5] = _mm512_unpackhi_epi64(u[4], u[6]); + r[6] = _mm512_unpacklo_epi64(u[5], u[7]); + r[7] = _mm512_unpackhi_epi64(u[5], u[7]); + + __m512i const1 = _mm512_set_epi32( + 0x00370035, + 0x00330031, + 0x00270025, + 0x00230021, + 0x00170015, + 0x00130011, + 0x00070005, + 0x00030001, + 0x00360034, + 0x00320030, + 0x00260024, + 0x00220020, + 0x00160014, + 0x00120010, + 0x00060004, + 0x00020000); + __m512i const2 = _mm512_set_epi32( + 0x003f003d, + 0x003b0039, + 0x002f002d, + 0x002b0029, + 0x001f001d, + 0x001b0019, + 0x000f000d, + 0x000b0009, + 0x003e003c, + 0x003a0038, + 0x002e002c, + 0x002a0028, + 0x001e001c, + 0x001a0018, + 0x000e000c, + 0x000a0008); + // merge values from two regs + // 0-- 1-- + // 8-- 9-- + // 2-- 3-- + // 10-- 11-- + // 4-- 5-- + // 12-- 13-- + // 6-- 7-- + // 14-- 15-- +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 4; i++) { + u[i] = _mm512_permutex2var_epi16(r[i], const1, r[i + 4]); + u[i + 4] = _mm512_permutex2var_epi16(r[i], const2, r[i + 4]); + } +} + +// TODO(Leslie): Add the AVX2 Version of transpose_mxn for BFloat16 and Float16 +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#L1483-L1607 +template <> +inline void transpose_mxn( + const BFloat16* src, + int64_t ld_src, + BFloat16* dst, + int64_t ld_dst) { + __m256i t[16]; + // load from src to registers + // a: a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 + // b: b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 + // c: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 + // d: d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 + // e: e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12 e13 e14 e15 + // f: f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 + // g: g0 g1 g2 g3 g4 g5 g6 g7 g8 g9 g10 g11 g12 g13 g14 g15 + // h: h0 h1 h2 h3 h4 h5 h6 h7 h8 h9 h10 h11 h12 h13 h14 h15 + // i: i0 i1 i2 i3 i4 i5 i6 i7 i8 i9 i10 i11 i12 i13 i14 i15 + // j: j0 j1 j2 j3 j4 j5 j6 j7 j8 j9 j10 j11 j12 j13 j14 j15 + // k: k0 k1 k2 k3 k4 k5 k6 k7 k8 k9 k10 k11 k12 k13 k14 k15 + // l: l0 l1 l2 l3 l4 l5 l6 l7 l8 l9 l10 l11 l12 l13 l14 l15 + // m: m0 m1 m2 m3 m4 m5 m6 m7 m8 m9 m10 m11 m12 m13 m14 m15 + // n: n0 n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 + // o: o0 o1 o2 o3 o4 o5 o6 o7 o8 o9 o10 o11 o12 o13 o14 o15 + // p: p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; i++) { + t[i] = + _mm256_loadu_si256(reinterpret_cast(src + i * ld_src)); + } + + __m512i u[8]; + _transpose_mxn_half_16_16(t, u); + +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; i++) { + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x0)); + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2 + 1) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x01)); + } +} + +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#L1483-L1607 +template <> +inline void transpose_mxn( + const Half* src, + int64_t ld_src, + Half* dst, + int64_t ld_dst) { + __m256i t[16]; + // load from src to registers + // Same matrix indices as above transpose_mxn +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; i++) { + t[i] = + _mm256_loadu_si256(reinterpret_cast(src + i * ld_src)); + } + + __m512i u[8]; + _transpose_mxn_half_16_16(t, u); + +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; i++) { + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x0)); + _mm256_storeu_si256( + reinterpret_cast<__m256i*>(dst + (i * 2 + 1) * ld_dst), + _mm512_extracti32x8_epi32(u[i], 0x01)); + } +} + +static inline void _transpose_mxn_half_32_32(__m512i r[], __m512i d[]) { + // t[0]: 0 32 1 33 2 34 3 35 8 40 9 41 10 42 11 43 16 ... 59 + // t[1]: 4 36 5 37 6 38 7 39 12 44 13 45 14 46 15 47 20 ... 63 + // t[2]: 64 96 65 97 66 98 67 99 72 104 73 105 74 106 75 ... 123 + // t[3]: 68 100 69 101 70 102 71 103 76 108 77 109 78 110 79 111 84 ... 127 + // t[4]: 128 160 129 161 130 162 131 163 136 168 137 169 138 170 139 171 144 + // ... 187 t[5]: 132 164 133 165 134 166 135 167 140 172 141 173 142 174 143 + // 175 148 ... 191 t[6]: 192 224 193 225 194 226 195 227 200 232 201 233 202 + // 234 203 235 208 ... 251 t[7]: 196 228 197 229 198 230 199 231 204 236 205 + // 237 206 238 207 239 212 ... 255 t[8]: 256 288 257 289 258 290 259 291 264 + // 296 265 297 266 298 267 299 272 ... 315 t[9]: 260 292 261 293 262 294 263 + // 295 268 300 269 301 270 302 271 303 276 ... 319 t[10]: 320 352 321 353 322 + // 354 323 355 328 360 329 361 330 362 331 363 336 ... 379 t[11]: 324 356 325 + // 357 326 358 327 359 332 364 333 365 334 366 335 367 340 ... 383 t[12]: 384 + // 416 385 417 386 418 387 419 392 424 393 425 394 426 395 427 400 ... 443 + // t[13]: 388 420 389 421 390 422 391 423 396 428 397 429 398 430 399 431 404 + // ... 447 t[14]: 448 480 449 481 450 482 451 483 456 488 457 489 458 490 459 + // 491 464 ... 507 t[15]: 452 484 453 485 454 486 455 487 460 492 461 493 462 + // 494 463 495 468 ... 511 t[16]: 512 544 513 545 514 546 515 547 520 552 521 + // 553 522 554 523 555 528 ... 571 + // ... + // t[31]: 964 996 965 997 966 998 967 999 972 1004 973 1005 974 1006 975 1007 + // 980 ... 1023 +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; ++i) { + d[i * 2] = _mm512_unpacklo_epi16(r[i * 2], r[i * 2 + 1]); + d[i * 2 + 1] = _mm512_unpackhi_epi16(r[i * 2], r[i * 2 + 1]); + } + + // t[0]: 0 32 64 96 1 33 65 97 8 40 72 104 9 41 73 105 16 ... 121 + // t[1]: 2 34 66 98 3 35 67 99 10 42 74 106 11 43 75 107 18 ... 123 + // t[2]: 4 36 68 100 5 37 69 101 12 44 76 108 13 45 77 109 20 ... 125 + // t[3]: 6 38 70 102 7 39 71 103 14 46 78 110 15 47 79 111 22 ... 127 + // t[4]: 128 160 192 224 129 161 193 225 136 168 200 232 137 169 201 233 144 + // ... 249 t[5]: 130 162 194 226 131 163 195 227 138 170 202 234 139 171 203 + // 235 146 ... 251 t[6]: 132 164 196 228 133 165 197 229 140 172 204 236 141 + // 173 205 237 148 ... 253 t[7]: 134 166 198 230 135 167 199 231 142 174 206 + // 238 143 175 207 239 150 ... 255 t[8]: 256 288 320 352 257 289 321 353 264 + // 296 328 360 265 297 329 361 272 ... 377 t[9]: 258 290 322 354 259 291 323 + // 355 266 298 330 362 267 299 331 363 274 ... 379 t[10]: 260 292 324 356 261 + // 293 325 357 268 300 332 364 269 301 333 365 276 ... 381 t[11]: 262 294 326 + // 358 263 295 327 359 270 302 334 366 271 303 335 367 278 ... 383 t[12]: 384 + // 416 448 480 385 417 449 481 392 424 456 488 393 425 457 489 400 ... 505 + // t[13]: 386 418 450 482 387 419 451 483 394 426 458 490 395 427 459 491 402 + // ... 507 t[14]: 388 420 452 484 389 421 453 485 396 428 460 492 397 429 461 + // 493 404 ... 509 t[15]: 390 422 454 486 391 423 455 487 398 430 462 494 399 + // 431 463 495 406 ... 511 t[16]: 512 544 576 608 513 545 577 609 520 552 584 + // 616 521 553 585 617 528 ... 633 + // ... + // t[31]: 902 934 966 998 903 935 967 999 910 942 974 1006 911 943 975 1007 + // 918 ... 1023 +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; ++i) { + r[i * 4] = _mm512_unpacklo_epi32(d[i * 4], d[i * 4 + 2]); + r[i * 4 + 1] = _mm512_unpackhi_epi32(d[i * 4], d[i * 4 + 2]); + r[i * 4 + 2] = _mm512_unpacklo_epi32(d[i * 4 + 1], d[i * 4 + 3]); + r[i * 4 + 3] = _mm512_unpackhi_epi32(d[i * 4 + 1], d[i * 4 + 3]); + } + + // t[0]: 0 32 64 96 128 160 192 224 8 40 72 104 136 168 200 232 16 ... 248 + // t[1]: 1 33 65 97 129 161 193 225 9 41 73 105 137 169 201 233 17 ... 249 + // t[2]: 2 34 66 98 130 162 194 226 10 42 74 106 138 170 202 234 18 ... 250 + // t[3]: 3 35 67 99 131 163 195 227 11 43 75 107 139 171 203 235 19 ... 251 + // t[4]: 4 36 68 100 132 164 196 228 12 44 76 108 140 172 204 236 20 ... 252 + // t[5]: 5 37 69 101 133 165 197 229 13 45 77 109 141 173 205 237 21 ... 253 + // t[6]: 6 38 70 102 134 166 198 230 14 46 78 110 142 174 206 238 22 ... 254 + // t[7]: 7 39 71 103 135 167 199 231 15 47 79 111 143 175 207 239 23 ... 255 + // t[8]: 256 288 320 352 384 416 448 480 264 296 328 360 392 424 456 488 272 + // ... 504 t[9]: 257 289 321 353 385 417 449 481 265 297 329 361 393 425 457 + // 489 273 ... 505 t[10]: 258 290 322 354 386 418 450 482 266 298 330 362 394 + // 426 458 490 274 ... 506 t[11]: 259 291 323 355 387 419 451 483 267 299 331 + // 363 395 427 459 491 275 ... 507 t[12]: 260 292 324 356 388 420 452 484 268 + // 300 332 364 396 428 460 492 276 ... 508 t[13]: 261 293 325 357 389 421 453 + // 485 269 301 333 365 397 429 461 493 277 ... 509 t[14]: 262 294 326 358 390 + // 422 454 486 270 302 334 366 398 430 462 494 278 ... 510 t[15]: 263 295 327 + // 359 391 423 455 487 271 303 335 367 399 431 463 495 279 ... 511 t[16]: 512 + // 544 576 608 640 672 704 736 520 552 584 616 648 680 712 744 528 ... 760 + // ... + // t[31]: 775 807 839 871 903 935 967 999 783 815 847 879 911 943 975 1007 791 + // ... 1023 +#ifndef __msvc_cl__ +#pragma unroll(4) +#endif + for (int i = 0; i < 4; ++i) { + d[i * 8] = _mm512_unpacklo_epi64(r[i * 8], r[i * 8 + 4]); + d[i * 8 + 1] = _mm512_unpackhi_epi64(r[i * 8], r[i * 8 + 4]); + d[i * 8 + 2] = _mm512_unpacklo_epi64(r[i * 8 + 1], r[i * 8 + 5]); + d[i * 8 + 3] = _mm512_unpackhi_epi64(r[i * 8 + 1], r[i * 8 + 5]); + d[i * 8 + 4] = _mm512_unpacklo_epi64(r[i * 8 + 2], r[i * 8 + 6]); + d[i * 8 + 5] = _mm512_unpackhi_epi64(r[i * 8 + 2], r[i * 8 + 6]); + d[i * 8 + 6] = _mm512_unpacklo_epi64(r[i * 8 + 3], r[i * 8 + 7]); + d[i * 8 + 7] = _mm512_unpackhi_epi64(r[i * 8 + 3], r[i * 8 + 7]); + } + + // t[0]: 0 32 64 96 128 160 192 224 256 288 320 352 384 416 448 480 16 ... 496 + // t[1]: 1 33 65 97 129 161 193 225 257 289 321 353 385 417 449 481 17 ... 497 + // t[2]: 2 34 66 98 130 162 194 226 258 290 322 354 386 418 450 482 18 ... 498 + // t[3]: 3 35 67 99 131 163 195 227 259 291 323 355 387 419 451 483 19 ... 499 + // t[4]: 4 36 68 100 132 164 196 228 260 292 324 356 388 420 452 484 20 ... + // 500 t[5]: 5 37 69 101 133 165 197 229 261 293 325 357 389 421 453 485 21 + // ... 501 t[6]: 6 38 70 102 134 166 198 230 262 294 326 358 390 422 454 486 + // 22 ... 502 t[7]: 7 39 71 103 135 167 199 231 263 295 327 359 391 423 455 + // 487 23 ... 503 t[8]: 8 40 72 104 136 168 200 232 264 296 328 360 392 424 + // 456 488 24 ... 504 t[9]: 9 41 73 105 137 169 201 233 265 297 329 361 393 + // 425 457 489 25 ... 505 t[10]: 10 42 74 106 138 170 202 234 266 298 330 362 + // 394 426 458 490 26 ... 506 t[11]: 11 43 75 107 139 171 203 235 267 299 331 + // 363 395 427 459 491 27 ... 507 t[12]: 12 44 76 108 140 172 204 236 268 300 + // 332 364 396 428 460 492 28 ... 508 t[13]: 13 45 77 109 141 173 205 237 269 + // 301 333 365 397 429 461 493 29 ... 509 t[14]: 14 46 78 110 142 174 206 238 + // 270 302 334 366 398 430 462 494 30 ... 510 t[15]: 15 47 79 111 143 175 207 + // 239 271 303 335 367 399 431 463 495 31 ... 511 t[16]: 512 544 576 608 640 + // 672 704 736 768 800 832 864 896 928 960 992 528 ... 1008 + // ... + // t[31]: 527 559 591 623 655 687 719 751 783 815 847 879 911 943 975 1007 543 + // ... 1023 + __m512i const1 = _mm512_set_epi64( + 0x000000000000000d, + 0x000000000000000c, + 0x0000000000000005, + 0x0000000000000004, + 0x0000000000000009, + 0x0000000000000008, + 0x0000000000000001, + 0x0000000000000000); + __m512i const2 = _mm512_set_epi64( + 0x000000000000000f, + 0x000000000000000e, + 0x0000000000000007, + 0x0000000000000006, + 0x000000000000000b, + 0x000000000000000a, + 0x0000000000000003, + 0x0000000000000002); +#ifndef __msvc_cl__ +#pragma unroll(8) +#endif + for (int i = 0; i < 8; ++i) { + r[i] = _mm512_permutex2var_epi64(d[i], /*idx*/ const1, d[i + 8]); + r[i + 8] = _mm512_permutex2var_epi64(d[i], /*idx*/ const2, d[i + 8]); + r[i + 16] = _mm512_permutex2var_epi64(d[i + 16], /*idx*/ const1, d[i + 24]); + r[i + 24] = _mm512_permutex2var_epi64(d[i + 16], /*idx*/ const2, d[i + 24]); + } + + // t[0]: 0 32 64 96 128 160 192 224 256 288 320 352 384 416 448 480 512 544 + // ... 992 t[1]: 1 33 65 97 129 161 193 225 257 289 321 353 385 417 449 481 + // 513 545 ... 993 t[2]: 2 34 66 98 130 162 194 226 258 290 322 354 386 418 + // 450 482 514 546 ... 994 t[3]: 3 35 67 99 131 163 195 227 259 291 323 355 + // 387 419 451 483 515 547 ... 995 t[4]: 4 36 68 100 132 164 196 228 260 292 + // 324 356 388 420 452 484 516 548 ... 996 t[5]: 5 37 69 101 133 165 197 229 + // 261 293 325 357 389 421 453 485 517 549 ... 997 t[6]: 6 38 70 102 134 166 + // 198 230 262 294 326 358 390 422 454 486 518 550 ... 998 t[7]: 7 39 71 103 + // 135 167 199 231 263 295 327 359 391 423 455 487 519 551 ... 999 t[8]: 8 40 + // 72 104 136 168 200 232 264 296 328 360 392 424 456 488 520 552 ... 1000 + // t[9]: 9 41 73 105 137 169 201 233 265 297 329 361 393 425 457 489 521 553 + // ... 1001 t[10]: 10 42 74 106 138 170 202 234 266 298 330 362 394 426 458 + // 490 522 554 ... 1002 t[11]: 11 43 75 107 139 171 203 235 267 299 331 363 + // 395 427 459 491 523 555 ... 1003 t[12]: 12 44 76 108 140 172 204 236 268 + // 300 332 364 396 428 460 492 524 556 ... 1004 t[13]: 13 45 77 109 141 173 + // 205 237 269 301 333 365 397 429 461 493 525 557 ... 1005 t[14]: 14 46 78 + // 110 142 174 206 238 270 302 334 366 398 430 462 494 526 558 ... 1006 t[15]: + // 15 47 79 111 143 175 207 239 271 303 335 367 399 431 463 495 527 559 ... + // 1007 t[16]: 16 48 80 112 144 176 208 240 272 304 336 368 400 432 464 496 + // 528 560 ... 1008 + // ... + // t[31]: 31 63 95 127 159 191 223 255 287 319 351 383 415 447 479 511 543 575 + // ... 1023 + __m512i const3 = _mm512_set_epi64( + 0x000000000000000b, + 0x000000000000000a, + 0x0000000000000009, + 0x0000000000000008, + 0x0000000000000003, + 0x0000000000000002, + 0x0000000000000001, + 0x0000000000000000); + __m512i const4 = _mm512_set_epi64( + 0x000000000000000f, + 0x000000000000000e, + 0x000000000000000d, + 0x000000000000000c, + 0x0000000000000007, + 0x0000000000000006, + 0x0000000000000005, + 0x0000000000000004); +#ifndef __msvc_cl__ +#pragma unroll(16) +#endif + for (int i = 0; i < 16; ++i) { + d[i] = _mm512_permutex2var_epi64(r[i], /*idx*/ const3, r[i + 16]); + d[i + 16] = _mm512_permutex2var_epi64(r[i], /*idx*/ const4, r[i + 16]); + } +} + +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#LL19C6-L19C6 +template <> +inline void transpose_mxn( + const BFloat16* src, + int64_t ld_src, + BFloat16* dst, + int64_t ld_dst, + int M, + int N) { + // load from src + TORCH_CHECK( + M <= 32 && N <= 32, "transpose_mxn expects M, N <= 32."); + __m512i r[32]; + int i; + if (N == 32) { + for (i = 0; i < M; ++i) { + r[i] = _mm512_loadu_si512(&src[i * ld_src]); + } + } else { + __mmask32 src_mask = (1 << N) - 1; + for (i = 0; i < M; ++i) { + r[i] = _mm512_maskz_loadu_epi16(src_mask, &src[i * ld_src]); + } + } + for (; i < 32; ++i) { + r[i] = _mm512_setzero_si512(); + } + + __m512i d[32]; + _transpose_mxn_half_32_32(r, d); + + // store to dst + if (M == 32) { + for (i = 0; i < N; ++i) { + _mm512_storeu_si512(&dst[i * ld_dst], d[i]); + } + } else { + __mmask32 dst_mask = (1 << M) - 1; + for (i = 0; i < N; ++i) { + _mm512_mask_storeu_epi16(&dst[i * ld_dst], dst_mask, d[i]); + } + } +} + +template < + typename T, + int M, + int N, + typename std::enable_if_t< + std::is_same_v && + ((M <= 32 && M != 16) || (N <= 32 && N != 16)), + int> = 0> +inline void transpose_mxn( + const BFloat16* src, + int64_t ld_src, + BFloat16* dst, + int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} + +template <> +inline void transpose_mxn( + const Half* src, + int64_t ld_src, + Half* dst, + int64_t ld_dst, + int M, + int N) { + TORCH_CHECK(M <= 32 && N <= 32, "transpose_mxn expects M, N <= 32."); + // load from src + __m512i r[32]; + int i; + if (N == 32) { + for (i = 0; i < M; ++i) { + r[i] = _mm512_loadu_si512(&src[i * ld_src]); + } + } else { + __mmask32 src_mask = (1 << N) - 1; + for (i = 0; i < M; ++i) { + r[i] = _mm512_maskz_loadu_epi16(src_mask, &src[i * ld_src]); + } + } + for (; i < 32; ++i) { + r[i] = _mm512_setzero_si512(); + } + + __m512i d[32]; + _transpose_mxn_half_32_32(r, d); + + // store to dst + if (M == 32) { + for (i = 0; i < N; ++i) { + _mm512_storeu_si512(&dst[i * ld_dst], d[i]); + } + } else { + __mmask32 dst_mask = (1 << M) - 1; + for (i = 0; i < N; ++i) { + _mm512_mask_storeu_epi16(&dst[i * ld_dst], dst_mask, d[i]); + } + } +} + +template < + typename T, + int M, + int N, + typename std::enable_if_t< + std::is_same_v && + ((M <= 32 && M != 16) || (N <= 32 && N != 16)), + int> = 0> +inline void transpose_mxn( + const Half* src, + int64_t ld_src, + Half* dst, + int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized : public Vectorized16 { + public: + using Vectorized16::Vectorized16; + + using value_type = Half; + + Vectorized frac() const; + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_add_ps(x, y); + }); +} +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_sub_ps(x, y); + }); +} +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_mul_ps(x, y); + }); +} +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return binary_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_div_ps(x, y); + }); +} + +Vectorized inline operator&( + const Vectorized& a, + const Vectorized& b) { + return _mm512_and_si512(a, b); +} +Vectorized inline operator|( + const Vectorized& a, + const Vectorized& b) { + return _mm512_or_si512(a, b); +} +Vectorized inline operator^( + const Vectorized& a, + const Vectorized& b) { + return _mm512_xor_si512(a, b); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +// frac. Implement this here so we can use subtraction +inline Vectorized Vectorized::frac() const { + return *this - this->trunc(); +} + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(b), b_lo, b_hi); + auto max_lo = _mm512_max_ps(a_lo, b_lo); + auto max_hi = _mm512_max_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps(_mm512_set1_epi32(nan_lo_mask)); + auto nan_hi = _mm512_castsi512_ps(_mm512_set1_epi32(nan_hi_mask)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(max_lo, nan_lo); + auto o2 = _mm512_or_ps(max_hi, nan_hi); + return cvtfp32_fp16(o1, o2); +} + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512i zero_vec = _mm512_set1_epi32(0); + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(b), b_lo, b_hi); + auto min_lo = _mm512_min_ps(a_lo, b_lo); + auto min_hi = _mm512_min_ps(a_hi, b_hi); + auto nan_lo_mask = _mm512_cmp_ps_mask(a_lo, b_lo, _CMP_UNORD_Q); + auto nan_hi_mask = _mm512_cmp_ps_mask(a_hi, b_hi, _CMP_UNORD_Q); + auto nan_lo = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, nan_lo_mask, 0xFFFFFFFF)); + auto nan_hi = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, nan_hi_mask, 0xFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + auto o1 = _mm512_or_ps(min_lo, nan_lo); + auto o2 = _mm512_or_ps(min_hi, nan_hi); + return cvtfp32_fp16(o1, o2); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min, + const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + __m512 max_lo, max_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(min), min_lo, min_hi); + cvtfp16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, _mm512_max_ps(min_lo, a_lo)); + auto o2 = _mm512_min_ps(max_hi, _mm512_max_ps(min_hi, a_hi)); + return cvtfp32_fp16(o1, o2); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max) { + __m512 a_lo, a_hi; + __m512 max_lo, max_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(max), max_lo, max_hi); + auto o1 = _mm512_min_ps(max_lo, a_lo); + auto o2 = _mm512_min_ps(max_hi, a_hi); + return cvtfp32_fp16(o1, o2); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min) { + __m512 a_lo, a_hi; + __m512 min_lo, min_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(min), min_lo, min_hi); + auto o1 = _mm512_max_ps(min_lo, a_lo); + auto o2 = _mm512_max_ps(min_hi, a_hi); + return cvtfp32_fp16(o1, o2); +} + +template <> +inline void convert(const Half* src, Half* dst, int64_t n) { + int64_t i; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + auto vsrc = + _mm512_loadu_si512(reinterpret_cast<__m512i*>((void*)(src + i))); + _mm512_storeu_si512(reinterpret_cast<__m512i*>((void*)(dst + i)), vsrc); + } +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = src[i]; + } +} + +template <> +inline void convert(const float* src, Half* dst, int64_t n) { + int64_t i; + for (i = 0; i + Vectorized::size() <= n; + i += Vectorized::size()) { + __m512 a = _mm512_loadu_ps(&src[i]); + __m512 b = _mm512_loadu_ps(&src[i + 16]); + + __m512i bf = cvtfp32_fp16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +inline void convert(const double* src, Half* dst, int64_t n) { + auto load_float = [](const double* src) -> __m512 { + // Load one float vector from an array of doubles + __m256 a = _mm512_cvtpd_ps(_mm512_loadu_pd(src)); + __m256 b = _mm512_cvtpd_ps(_mm512_loadu_pd(src + 8)); + return _mm512_insertf32x8(_mm512_castps256_ps512(a), b, 1); + }; + + int64_t i; + for (i = 0; i + Vectorized::size() <= n; + i += Vectorized::size()) { + __m512 a = load_float(&src[i]); + __m512 b = load_float(&src[i + 16]); + + __m512i bf = cvtfp32_fp16(a, b); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(&dst[i]), bf); + } + for (; i < n; i++) { + dst[i] = c10::convert(src[i]); + } +} + +template <> +Vectorized inline fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + __m512 a_lo, a_hi; + __m512 b_lo, b_hi; + __m512 c_lo, c_hi; + cvtfp16_fp32(__m512i(a), a_lo, a_hi); + cvtfp16_fp32(__m512i(b), b_lo, b_hi); + cvtfp16_fp32(__m512i(c), c_lo, c_hi); + auto o1 = _mm512_fmadd_ps(a_lo, b_lo, c_lo); + auto o2 = _mm512_fmadd_ps(a_hi, b_hi, c_hi); + return cvtfp32_fp16(o1, o2); +} + +#define CONVERT_VECTORIZED_INIT(type, name) \ + inline std::tuple, Vectorized> \ + convert_##name##_float(const Vectorized& a) { \ + __m512 o1, o2; \ + cvt_to_fp32(__m512i(a), o1, o2); \ + return std::make_tuple(o1, o2); \ + } \ + \ + inline Vectorized convert_float_##name( \ + const Vectorized& a, const Vectorized& b) { \ + return cvt_from_fp32(__m512(a), __m512(b)); \ + } +CONVERT_VECTORIZED_INIT(BFloat16, bfloat16) +CONVERT_VECTORIZED_INIT(Half, half) + +#else // defined(CPU_CAPABILITY_AVX512) + +#define CONVERT_NON_VECTORIZED_INIT(type, name) \ + inline std::tuple, Vectorized> \ + convert_##name##_float(const Vectorized& a) { \ + constexpr int64_t K = Vectorized::size(); \ + __at_align__ float arr[K]; \ + __at_align__ type arr2[K]; \ + a.store(arr2); \ + for (const auto k : c10::irange(K)) { \ + arr[k] = c10::convert(arr2[k]); \ + } \ + return std::make_tuple( \ + Vectorized::loadu(arr), \ + Vectorized::loadu(arr + Vectorized::size())); \ + } \ + \ + inline Vectorized convert_float_##name( \ + const Vectorized& a, const Vectorized& b) { \ + constexpr int64_t K = Vectorized::size(); \ + __at_align__ float arr[K]; \ + __at_align__ type arr2[K]; \ + a.store(arr); \ + b.store(arr + Vectorized::size()); \ + for (const auto k : c10::irange(K)) { \ + arr2[k] = c10::convert(arr[k]); \ + } \ + return Vectorized::loadu(arr2); \ + } +CONVERT_NON_VECTORIZED_INIT(BFloat16, bfloat16) +CONVERT_NON_VECTORIZED_INIT(Half, half) + +#endif // defined(CPU_CAPABILITY_AVX512) + +#if defined(CPU_CAPABILITY_AVX512) +#define LOAD_FP32_VECTORIZED_INIT(type, name) \ + inline void load_fp32_from_##name( \ + const type* data, Vectorized& out) { \ + auto values = _mm256_loadu_si256(reinterpret_cast(data)); \ + __m512 out_values; \ + cvt_to_fp32(values, out_values); \ + out = out_values; \ + } \ + \ + inline void load_fp32_from_##name( \ + const type* data, Vectorized& out1, Vectorized& out2) { \ + auto vec = Vectorized::loadu(data); \ + __m512 out1_values, out2_values; \ + cvt_to_fp32(vec, out1_values, out2_values); \ + out1 = out1_values; \ + out2 = out2_values; \ + } +LOAD_FP32_VECTORIZED_INIT(BFloat16, bf16) +LOAD_FP32_VECTORIZED_INIT(Half, fp16) + +#else // defined(CPU_CAPABILITY_AVX512) +#define LOAD_FP32_NON_VECTORIZED_INIT(type, name) \ + inline void load_fp32_from_##name( \ + const type* data, Vectorized& out) { \ + __at_align__ float values[Vectorized::size()]; \ + for (const auto k : c10::irange(Vectorized::size())) { \ + values[k] = data[k]; \ + } \ + out = Vectorized::loadu(values); \ + } \ + \ + inline void load_fp32_from_##name( \ + const type* data, Vectorized& out1, Vectorized& out2) { \ + load_fp32_from_##name(data, out1); \ + data += Vectorized::size(); \ + load_fp32_from_##name(data, out2); \ + } +LOAD_FP32_NON_VECTORIZED_INIT(BFloat16, bf16) +LOAD_FP32_NON_VECTORIZED_INIT(Half, fp16) + +#endif +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_complex_double.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_complex_double.h new file mode 100644 index 0000000000000000000000000000000000000000..3bf4b0f629bd8e0e0baaf9a995f06f700d5c3e55 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_complex_double.h @@ -0,0 +1,653 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#include +#if defined(CPU_CAPABILITY_AVX512) +#define SLEEF_STATIC_LIBS +#include +#endif + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +template <> +struct is_vec_specialized_for> : std::bool_constant { +}; + +template <> +class Vectorized> { + private: + __m512d values; + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + + public: + using value_type = c10::complex; + using size_type = int; + static constexpr size_type size() { + return 4; + } + Vectorized() { + values = _mm512_setzero_pd(); + } + Vectorized(__m512d v) : values(v) {} + Vectorized(c10::complex val) { + double real_value = val.real(); + double imag_value = val.imag(); + values = _mm512_setr_pd( + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value); + } + Vectorized( + c10::complex val1, + c10::complex val2, + c10::complex val3, + c10::complex val4) { + values = _mm512_setr_pd( + val1.real(), + val1.imag(), + val2.real(), + val2.imag(), + val3.real(), + val3.imag(), + val4.real(), + val4.imag()); + } + operator __m512d() const { + return values; + } + template + static Vectorized> blend( + const Vectorized>& a, + const Vectorized>& b) { + // convert c10::complex index mask to V index mask: xy -> xxyy + // NOLINTNEXTLINE(clang-diagnostic-warning) + switch (mask) { + case 0: + return a; + case 1: + return _mm512_mask_blend_pd( + 0x03, a.values, b.values); // b0000 0001 = b0000 0011 + case 2: + return _mm512_mask_blend_pd( + 0x0C, a.values, b.values); // b0000 0010 = b0000 1100 + case 3: + return _mm512_mask_blend_pd( + 0x0F, a.values, b.values); // b0000 0011 = b0000 1111 + case 4: + return _mm512_mask_blend_pd( + 0x30, a.values, b.values); // b0000 0100 = b0011 0000 + case 5: + return _mm512_mask_blend_pd( + 0x33, a.values, b.values); // b0000 0101 = b0011 0011 + case 6: + return _mm512_mask_blend_pd( + 0x3C, a.values, b.values); // b0000 0110 = b0011 1100 + case 7: + return _mm512_mask_blend_pd( + 0x3F, a.values, b.values); // b0000 0111 = b0011 1111 + case 8: + return _mm512_mask_blend_pd( + 0xC0, a.values, b.values); // b0000 1000 = b1100 0000 + case 9: + return _mm512_mask_blend_pd( + 0xC3, a.values, b.values); // b0000 1001 = b1100 0011 + case 10: + return _mm512_mask_blend_pd( + 0xCC, a.values, b.values); // b0000 1010 = b1100 1100 + case 11: + return _mm512_mask_blend_pd( + 0xCF, a.values, b.values); // b0000 1011 = b1100 1111 + case 12: + return _mm512_mask_blend_pd( + 0xF0, a.values, b.values); // b0000 1100 = b1111 0000 + case 13: + return _mm512_mask_blend_pd( + 0xF3, a.values, b.values); // b0000 1101 = b1111 0011 + case 14: + return _mm512_mask_blend_pd( + 0xFC, a.values, b.values); // b0000 1110 = b1111 1100 + case 15: + return _mm512_mask_blend_pd( + 0xFF, a.values, b.values); // b0000 1111 = b1111 1111 + } + return b; + } + static Vectorized> blendv( + const Vectorized>& a, + const Vectorized>& b, + const Vectorized>& mask) { + // convert c10::complex index mask to V index mask: xy -> xxyy + auto mask_ = _mm512_unpacklo_pd(mask.values, mask.values); + auto all_ones = _mm512_set1_epi64(0xFFFFFFFFFFFFFFFF); + auto mmask = _mm512_cmp_epi64_mask( + _mm512_castpd_si512(mask_), all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_pd(mmask, a.values, b.values); + } + template + static Vectorized> arange( + c10::complex base = 0., + step_t step = static_cast(1)) { + return Vectorized>( + base, + base + c10::complex(1) * step, + base + c10::complex(2) * step, + base + c10::complex(3) * step); + } + static Vectorized> set( + const Vectorized>& a, + const Vectorized>& b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + } + return b; + } + static Vectorized> loadu( + const void* ptr, + int64_t count = size()) { + if (count == size()) + return _mm512_loadu_pd(reinterpret_cast(ptr)); + + // Zero tail past `count`. + __at_align__ double tmp_values[2 * size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(c10::complex)); + return _mm512_load_pd(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_pd(reinterpret_cast(ptr), values); + } else if (count > 0) { + double tmp_values[2 * size()]; + _mm512_storeu_pd(reinterpret_cast(tmp_values), values); + std::memcpy( + ptr, + tmp_values, + std::min(count, size()) * sizeof(c10::complex)); + } + } + const c10::complex& operator[](int idx) const = delete; + c10::complex& operator[](int idx) = delete; + Vectorized> map( + c10::complex (*const f)(const c10::complex&)) const { + __at_align__ c10::complex tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = f(tmp[i]); + } + return loadu(tmp); + } + // AVX512 doesn't have horizontal add & horizontal sub instructions. + // TODO: hadd_pd() & hsub_pd() may have scope for improvement. + static inline __m512d hadd_pd(__m512d a, __m512d b) { + __m512i idx1 = _mm512_set_epi64(14, 6, 12, 4, 10, 2, 8, 0); + __m512i idx2 = _mm512_set_epi64(15, 7, 13, 5, 11, 3, 9, 1); + return _mm512_add_pd( + _mm512_mask_permutex2var_pd(a, 0xff, idx1, b), + _mm512_mask_permutex2var_pd(a, 0xff, idx2, b)); + } + static inline __m512d hsub_pd(__m512d a, __m512d b) { + __m512i idx1 = _mm512_set_epi64(14, 6, 12, 4, 10, 2, 8, 0); + __m512i idx2 = _mm512_set_epi64(15, 7, 13, 5, 11, 3, 9, 1); + return _mm512_sub_pd( + _mm512_mask_permutex2var_pd(a, 0xff, idx1, b), + _mm512_mask_permutex2var_pd(a, 0xff, idx2, b)); + } + __m512d abs_2_() const { + auto val_2 = _mm512_mul_pd(values, values); // a*a b*b + return hadd_pd(val_2, val_2); // a*a+b*b a*a+b*b + } + __m512d abs_() const { + auto real = _mm512_movedup_pd(values); // real real + // movehdup_pd does not exist... + auto imag = _mm512_permute_pd(values, 0xff); // imag imag + return Sleef_hypotd8_u05(real, imag); // abs abs + } + Vectorized> abs() const { + const __m512d real_mask = _mm512_castsi512_pd(_mm512_setr_epi64( + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000)); + return _mm512_and_pd(abs_(), real_mask); // abs 0 + } + __m512d angle_() const { + // angle = atan2(b/a) + auto b_a = _mm512_permute_pd(values, 0x55); // b a + return Sleef_atan2d8_u10(values, b_a); // 90-angle angle + } + Vectorized> angle() const { + const __m512d real_mask = _mm512_castsi512_pd(_mm512_setr_epi64( + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000)); + auto angle = _mm512_permute_pd(angle_(), 0x55); // angle 90-angle + return _mm512_and_pd(angle, real_mask); // angle 0 + } + Vectorized> sgn() const { + auto abs = abs_(); + auto zero = _mm512_setzero_pd(); + auto mask = _mm512_cmp_pd_mask(abs, zero, _CMP_EQ_OQ); + auto div = _mm512_div_pd(values, abs); + return _mm512_mask_blend_pd(mask, div, zero); + } + __m512d real_() const { + const __m512d real_mask = _mm512_castsi512_pd(_mm512_setr_epi64( + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000)); + return _mm512_and_pd(values, real_mask); + } + Vectorized> real() const { + return real_(); + } + __m512d imag_() const { + const __m512d imag_mask = _mm512_castsi512_pd(_mm512_setr_epi64( + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF, + 0x0000000000000000, + 0xFFFFFFFFFFFFFFFF)); + return _mm512_and_pd(values, imag_mask); + } + Vectorized> imag() const { + return _mm512_permute_pd(imag_(), 0x55); // b a + } + __m512d conj_() const { + const __m512d sign_mask = + _mm512_setr_pd(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0); + return _mm512_xor_pd(values, sign_mask); // a -b + } + Vectorized> conj() const { + return conj_(); + } + Vectorized> log() const { + // Most trigonomic ops use the log() op to improve complex number + // performance. + return map(std::log); + } + Vectorized> log2() const { + const __m512d log2_ = _mm512_set1_pd(std::log(2)); + return _mm512_div_pd(log(), log2_); + } + Vectorized> log10() const { + const __m512d log10_ = _mm512_set1_pd(std::log(10)); + return _mm512_div_pd(log(), log10_); + } + Vectorized> log1p() const { + return map(std::log1p); + } + Vectorized> asin() const { + // TODO: The vectorized implementation requires special handling for the + // case where real number/imag number is 0/Inf/NaN. + // // asin(x) + // // = -i*ln(iz + sqrt(1 -z^2)) + // // = -i*ln((ai - b) + sqrt(1 - (a + bi)*(a + bi))) + // // = -i*ln((-b + ai) + sqrt(1 - (a**2 - b**2) - 2*abi)) + // const __m512d one = _mm512_set1_pd(1); + + // auto conj = conj_(); + // auto b_a = _mm512_permute_pd(conj, 0x55); //-b a + // auto ab = _mm512_mul_pd(conj, b_a); //-ab + // -ab auto im = _mm512_add_pd(ab, ab); //-2ab -2ab + + // auto val_2 = _mm512_mul_pd(values, values); // a*a + // b*b auto re = hsub_pd(val_2, _mm512_permute_pd(val_2, 0x55)); // a*a-b*b + // b*b-a*a re = _mm512_sub_pd(one, re); + + // auto root = Vectorized(_mm512_mask_blend_pd(0xAA, re, im)).sqrt(); + // //sqrt(re + i*im) auto ln = Vectorized(_mm512_add_pd(b_a, root)).log(); + // //ln(iz + sqrt()) return Vectorized(_mm512_permute_pd(ln.values, + // 0x55)).conj(); //-i*ln() + return map(std::asin); + } + Vectorized> acos() const { + // acos(x) = pi/2 - asin(x) + constexpr auto pi_2d = c10::pi / 2; + const __m512d pi_2 = + _mm512_setr_pd(pi_2d, 0.0, pi_2d, 0.0, pi_2d, 0.0, pi_2d, 0.0); + return _mm512_sub_pd(pi_2, asin()); + } + Vectorized> atan() const; + Vectorized> atanh() const { + return map(std::atanh); + } + Vectorized> exp() const { + // TODO: The vectorized implementation requires special handling for the + // case where real number/imag number is 0/Inf/NaN. + // //exp(a + bi) + // // = exp(a)*(cos(b) + sin(b)i) + // auto exp = Sleef_expd8_u10(values); //exp(a) exp(b) exp = + // _mm512_mask_blend_pd(0xAA, exp, _mm512_permute_pd(exp, 0x55)); //exp(a) + // exp(a) + + // auto sin_cos = Sleef_sincosd8_u10(values); //[sin(a), cos(a)] [sin(b), + // cos(b)] auto cos_sin = _mm512_mask_blend_pd(0xAA, + // _mm512_permute_pd(sin_cos.y, 0x55), + // sin_cos.x); //cos(b) + // sin(b) + // return _mm512_mul_pd(exp, cos_sin); + return map(std::exp); + } + Vectorized> exp2() const { + // Use identity 2**x = exp(log(2) * x) + const __m512d ln_2 = _mm512_set1_pd(c10::ln_2); + Vectorized> scaled_values = + _mm512_mul_pd(values, ln_2); + return scaled_values.exp(); + } + Vectorized> expm1() const { + return map(std::expm1); + } + Vectorized> sin() const { + return map(std::sin); + } + Vectorized> sinh() const { + return map(std::sinh); + } + Vectorized> cos() const { + return map(std::cos); + } + Vectorized> cosh() const { + return map(std::cosh); + } + Vectorized> ceil() const { + return _mm512_ceil_pd(values); + } + Vectorized> floor() const { + return _mm512_floor_pd(values); + } + Vectorized> neg() const { + auto zero = _mm512_setzero_pd(); + return _mm512_sub_pd(zero, values); + } + Vectorized> round() const { + return _mm512_roundscale_pd( + values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + } + Vectorized> tan() const { + return map(std::tan); + } + Vectorized> tanh() const { + return map(std::tanh); + } + Vectorized> trunc() const { + return _mm512_roundscale_pd( + values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + } + Vectorized> sqrt() const { + return map(std::sqrt); + } + Vectorized> reciprocal() const; + Vectorized> rsqrt() const { + return sqrt().reciprocal(); + } + Vectorized> pow( + const Vectorized>& exp) const { + __at_align__ c10::complex x_tmp[size()]; + __at_align__ c10::complex y_tmp[size()]; + store(x_tmp); + exp.store(y_tmp); + for (const auto i : c10::irange(size())) { + x_tmp[i] = std::pow(x_tmp[i], y_tmp[i]); + } + return loadu(x_tmp); + } + // Comparison using the _CMP_**_OQ predicate. + // `O`: get false if an operand is NaN + // `Q`: do not raise if an operand is NaN + Vectorized> operator==( + const Vectorized>& other) const { + auto mask = _mm512_cmp_pd_mask(values, other.values, _CMP_EQ_OQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF)); + } + Vectorized> operator!=( + const Vectorized>& other) const { + auto mask = _mm512_cmp_pd_mask(values, other.values, _CMP_NEQ_UQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF)); + } + Vectorized> operator<( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator<=( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator>( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator>=( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + + Vectorized> eq( + const Vectorized>& other) const; + Vectorized> ne( + const Vectorized>& other) const; +}; + +template <> +Vectorized> inline operator+( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_add_pd(a, b); +} + +template <> +Vectorized> inline operator-( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_sub_pd(a, b); +} + +template <> +Vectorized> inline operator*( + const Vectorized>& a, + const Vectorized>& b) { + //(a + bi) * (c + di) = (ac - bd) + (ad + bc)i + const __m512d sign_mask = + _mm512_setr_pd(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, -0.0); + auto ac_bd = _mm512_mul_pd(a, b); // ac bd + + auto d_c = _mm512_permute_pd(b, 0x55); // d c + d_c = _mm512_xor_pd(sign_mask, d_c); // d -c + auto ad_bc = _mm512_mul_pd(a, d_c); // ad -bc + + auto ret = Vectorized>::hsub_pd( + ac_bd, ad_bc); // ac - bd ad + bc + return ret; +} + +template <> +Vectorized> inline operator/( + const Vectorized>& a, + const Vectorized>& b) { + // TODO: The vectorized implementation requires special handling for the case + // where real number/imag number is 0/Inf/NaN. + // //re + im*i = (a + bi) / (c + di) + // auto mask = _mm512_set1_pd(-0.f); + // auto fabs_cd = _mm512_andnot_pd(mask, b); // |c| |d| + // auto fabs_dc = _mm512_permute_pd(fabs_cd, 0x55); // |d| |c| + // auto scale = _mm512_rcp14_pd(_mm512_max_pd(fabs_cd, fabs_dc)); // 1/sc + // 1/sc auto a2 = _mm512_mul_pd(a, scale); // a/sc b/sc auto b2 = + // _mm512_mul_pd(b, scale); // c/sc d/sc auto acbd2 = + // _mm512_mul_pd(a2, b2); + + // const __m512d sign_mask = _mm512_setr_pd(-0.0, 0.0, -0.0, 0.0, -0.0, 0.0, + // -0.0, 0.0); auto dc2 = _mm512_permute_pd(b2, 0x55); // d/sc c/sc + // dc2 = _mm512_xor_pd(sign_mask, dc2); // -d/|c,d| c/sc + // auto adbc2 = _mm512_mul_pd(a2, dc2); //-ad/sc^2 bc/sc^2 + // auto res2 = Vectorized>::hadd_pd(acbd2, adbc2); + // //(ac+bd)/sc^2 (bc-ad)/sc^2 + + // // get the denominator + // auto denom2 = Vectorized>(b2).abs_2_(); // + // (c^2+d^2)/sc^2 (c^2+d^2)/sc^2 res2 = _mm512_div_pd(res2, denom2); return + // res2; + __at_align__ c10::complex + tmp1[Vectorized>::size()]; + __at_align__ c10::complex + tmp2[Vectorized>::size()]; + __at_align__ c10::complex + out[Vectorized>::size()]; + a.store(tmp1); + b.store(tmp2); + for (const auto i : c10::irange(Vectorized>::size())) { + out[i] = tmp1[i] / tmp2[i]; + } + return _mm512_loadu_pd(reinterpret_cast(out)); +} + +// reciprocal. Implement this here so we can use multiplication. +inline Vectorized> Vectorized< + c10::complex>::reciprocal() const { + // TODO: The vectorized implementation requires special handling for the case + // where real number/imag number is 0/Inf/NaN. + // //re + im*i = (a + bi) / (c + di) + // //re = (ac + bd)/abs_2() = c/abs_2() + // //im = (bc - ad)/abs_2() = d/abs_2() + // const __m512d sign_mask = _mm512_setr_pd(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, + // 0.0, -0.0); auto c_d = _mm512_xor_pd(sign_mask, values); //c -d + // return _mm512_div_pd(c_d, abs_2_()); + __at_align__ c10::complex tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = c10::complex(1) / tmp[i]; + } + return loadu(tmp); +} + +inline Vectorized> Vectorized>::atan() + const { + // TODO: The vectorized implementation requires special handling for the case + // where real number/imag number is 0/Inf/NaN. + // // atan(x) = i/2 * ln((i + z)/(i - z)) + // const __m512d i = _mm512_setr_pd(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0); + // const Vectorized i_half = _mm512_setr_pd(0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, + // 0.5); + + // auto sum = Vectorized(_mm512_add_pd(i, values)); // a + // 1+b auto sub = Vectorized(_mm512_sub_pd(i, values)); // -a 1-b auto + // ln = (sum/sub).log(); // ln((i + + // z)/(i - z)) return i_half*ln; // i/2*ln() + return map(std::atan); +} + +template <> +Vectorized> inline maximum( + const Vectorized>& a, + const Vectorized>& b) { + auto zero_vec = _mm512_set1_epi64(0); + auto abs_a = a.abs_2_(); + auto abs_b = b.abs_2_(); + auto mask = _mm512_cmp_pd_mask(abs_a, abs_b, _CMP_LT_OQ); + auto max = _mm512_mask_blend_pd(mask, a, b); + // Exploit the fact that all-ones is a NaN. + auto isnan_mask = _mm512_cmp_pd_mask(abs_a, abs_b, _CMP_UNORD_Q); + auto isnan = _mm512_mask_set1_epi64(zero_vec, isnan_mask, 0xFFFFFFFFFFFFFFFF); + return _mm512_or_pd(max, _mm512_castsi512_pd(isnan)); +} + +template <> +Vectorized> inline minimum( + const Vectorized>& a, + const Vectorized>& b) { + auto zero_vec = _mm512_set1_epi64(0); + auto abs_a = a.abs_2_(); + auto abs_b = b.abs_2_(); + auto mask = _mm512_cmp_pd_mask(abs_a, abs_b, _CMP_GT_OQ); + auto min = _mm512_mask_blend_pd(mask, a, b); + // Exploit the fact that all-ones is a NaN. + auto isnan_mask = _mm512_cmp_pd_mask(abs_a, abs_b, _CMP_UNORD_Q); + auto isnan = _mm512_mask_set1_epi64(zero_vec, isnan_mask, 0xFFFFFFFFFFFFFFFF); + return _mm512_or_pd(min, _mm512_castsi512_pd(isnan)); +} + +template <> +Vectorized> inline operator&( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_and_pd(a, b); +} + +template <> +Vectorized> inline operator|( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_or_pd(a, b); +} + +template <> +Vectorized> inline operator^( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_xor_pd(a, b); +} + +inline Vectorized> Vectorized>::eq( + const Vectorized>& other) const { + auto eq = (*this == other); // compares real and imag individually + // If both real numbers and imag numbers are equal, then the complex numbers + // are equal + return (eq.real() & eq.imag()) & + Vectorized>(_mm512_set1_pd(1.0)); +} + +inline Vectorized> Vectorized>::ne( + const Vectorized>& other) const { + auto ne = (*this != other); // compares real and imag individually + // If either real numbers or imag numbers are not equal, then the complex + // numbers are not equal + return (ne.real() | ne.imag()) & + Vectorized>(_mm512_set1_pd(1.0)); +} + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_complex_float.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_complex_float.h new file mode 100644 index 0000000000000000000000000000000000000000..a28e778cad97a0658e5e6497078290919905bf13 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_complex_float.h @@ -0,0 +1,1221 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#include +#if defined(CPU_CAPABILITY_AVX512) +#define SLEEF_STATIC_LIBS +#include +#endif + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +template <> +struct is_vec_specialized_for> : std::bool_constant { +}; + +template <> +class Vectorized> { + private: + __m512 values; + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + + public: + using value_type = c10::complex; + using size_type = int; + static constexpr size_type size() { + return 8; + } + Vectorized() { + values = _mm512_setzero_ps(); + } + Vectorized(__m512 v) : values(v) {} + Vectorized(c10::complex val) { + float real_value = val.real(); + float imag_value = val.imag(); + values = _mm512_setr_ps( + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value, + real_value, + imag_value); + } + Vectorized( + c10::complex val1, + c10::complex val2, + c10::complex val3, + c10::complex val4, + c10::complex val5, + c10::complex val6, + c10::complex val7, + c10::complex val8) { + values = _mm512_setr_ps( + val1.real(), + val1.imag(), + val2.real(), + val2.imag(), + val3.real(), + val3.imag(), + val4.real(), + val4.imag(), + val5.real(), + val5.imag(), + val6.real(), + val6.imag(), + val7.real(), + val7.imag(), + val8.real(), + val8.imag()); + } + operator __m512() const { + return values; + } + template + static Vectorized> blend( + const Vectorized>& a, + const Vectorized>& b) { + // convert c10::complex index mask to V index mask: xy -> xxyy + static_assert(mask > -1 && mask < 256, "Unexpected mask value"); + // The compiler would hopefully convert this switch condition + // into a jump table + switch (mask) { + case 0: + return a; + case 1: + return _mm512_mask_blend_ps(0x03, a.values, b.values); + case 2: + return _mm512_mask_blend_ps(0x0C, a.values, b.values); + case 3: + return _mm512_mask_blend_ps(0x0F, a.values, b.values); + case 4: + return _mm512_mask_blend_ps(0x30, a.values, b.values); + case 5: + return _mm512_mask_blend_ps(0x33, a.values, b.values); + case 6: + return _mm512_mask_blend_ps(0x3C, a.values, b.values); + case 7: + return _mm512_mask_blend_ps(0x3F, a.values, b.values); + case 8: + return _mm512_mask_blend_ps(0xC0, a.values, b.values); + case 9: + return _mm512_mask_blend_ps(0xC3, a.values, b.values); + case 10: + return _mm512_mask_blend_ps(0xCC, a.values, b.values); + case 11: + return _mm512_mask_blend_ps(0xCF, a.values, b.values); + case 12: + return _mm512_mask_blend_ps(0xF0, a.values, b.values); + case 13: + return _mm512_mask_blend_ps(0xF3, a.values, b.values); + case 14: + return _mm512_mask_blend_ps(0xFC, a.values, b.values); + case 15: + return _mm512_mask_blend_ps(0xFF, a.values, b.values); + case 16: + return _mm512_mask_blend_ps(0x300, a.values, b.values); + case 17: + return _mm512_mask_blend_ps(0x303, a.values, b.values); + case 18: + return _mm512_mask_blend_ps(0x30C, a.values, b.values); + case 19: + return _mm512_mask_blend_ps(0x30F, a.values, b.values); + case 20: + return _mm512_mask_blend_ps(0x330, a.values, b.values); + case 21: + return _mm512_mask_blend_ps(0x333, a.values, b.values); + case 22: + return _mm512_mask_blend_ps(0x33C, a.values, b.values); + case 23: + return _mm512_mask_blend_ps(0x33F, a.values, b.values); + case 24: + return _mm512_mask_blend_ps(0x3C0, a.values, b.values); + case 25: + return _mm512_mask_blend_ps(0x3C3, a.values, b.values); + case 26: + return _mm512_mask_blend_ps(0x3CC, a.values, b.values); + case 27: + return _mm512_mask_blend_ps(0x3CF, a.values, b.values); + case 28: + return _mm512_mask_blend_ps(0x3F0, a.values, b.values); + case 29: + return _mm512_mask_blend_ps(0x3F3, a.values, b.values); + case 30: + return _mm512_mask_blend_ps(0x3FC, a.values, b.values); + case 31: + return _mm512_mask_blend_ps(0x3FF, a.values, b.values); + case 32: + return _mm512_mask_blend_ps(0xC00, a.values, b.values); + case 33: + return _mm512_mask_blend_ps(0xC03, a.values, b.values); + case 34: + return _mm512_mask_blend_ps(0xC0C, a.values, b.values); + case 35: + return _mm512_mask_blend_ps(0xC0F, a.values, b.values); + case 36: + return _mm512_mask_blend_ps(0xC30, a.values, b.values); + case 37: + return _mm512_mask_blend_ps(0xC33, a.values, b.values); + case 38: + return _mm512_mask_blend_ps(0xC3C, a.values, b.values); + case 39: + return _mm512_mask_blend_ps(0xC3F, a.values, b.values); + case 40: + return _mm512_mask_blend_ps(0xCC0, a.values, b.values); + case 41: + return _mm512_mask_blend_ps(0xCC3, a.values, b.values); + case 42: + return _mm512_mask_blend_ps(0xCCC, a.values, b.values); + case 43: + return _mm512_mask_blend_ps(0xCCF, a.values, b.values); + case 44: + return _mm512_mask_blend_ps(0xCF0, a.values, b.values); + case 45: + return _mm512_mask_blend_ps(0xCF3, a.values, b.values); + case 46: + return _mm512_mask_blend_ps(0xCFC, a.values, b.values); + case 47: + return _mm512_mask_blend_ps(0xCFF, a.values, b.values); + case 48: + return _mm512_mask_blend_ps(0xF00, a.values, b.values); + case 49: + return _mm512_mask_blend_ps(0xF03, a.values, b.values); + case 50: + return _mm512_mask_blend_ps(0xF0C, a.values, b.values); + case 51: + return _mm512_mask_blend_ps(0xF0F, a.values, b.values); + case 52: + return _mm512_mask_blend_ps(0xF30, a.values, b.values); + case 53: + return _mm512_mask_blend_ps(0xF33, a.values, b.values); + case 54: + return _mm512_mask_blend_ps(0xF3C, a.values, b.values); + case 55: + return _mm512_mask_blend_ps(0xF3F, a.values, b.values); + case 56: + return _mm512_mask_blend_ps(0xFC0, a.values, b.values); + case 57: + return _mm512_mask_blend_ps(0xFC3, a.values, b.values); + case 58: + return _mm512_mask_blend_ps(0xFCC, a.values, b.values); + case 59: + return _mm512_mask_blend_ps(0xFCF, a.values, b.values); + case 60: + return _mm512_mask_blend_ps(0xFF0, a.values, b.values); + case 61: + return _mm512_mask_blend_ps(0xFF3, a.values, b.values); + case 62: + return _mm512_mask_blend_ps(0xFFC, a.values, b.values); + case 63: + return _mm512_mask_blend_ps(0xFFF, a.values, b.values); + case 64: + return _mm512_mask_blend_ps(0x3000, a.values, b.values); + case 65: + return _mm512_mask_blend_ps(0x3003, a.values, b.values); + case 66: + return _mm512_mask_blend_ps(0x300C, a.values, b.values); + case 67: + return _mm512_mask_blend_ps(0x300F, a.values, b.values); + case 68: + return _mm512_mask_blend_ps(0x3030, a.values, b.values); + case 69: + return _mm512_mask_blend_ps(0x3033, a.values, b.values); + case 70: + return _mm512_mask_blend_ps(0x303C, a.values, b.values); + case 71: + return _mm512_mask_blend_ps(0x303F, a.values, b.values); + case 72: + return _mm512_mask_blend_ps(0x30C0, a.values, b.values); + case 73: + return _mm512_mask_blend_ps(0X30C3, a.values, b.values); + case 74: + return _mm512_mask_blend_ps(0x30CC, a.values, b.values); + case 75: + return _mm512_mask_blend_ps(0x30CF, a.values, b.values); + case 76: + return _mm512_mask_blend_ps(0x30F0, a.values, b.values); + case 77: + return _mm512_mask_blend_ps(0x30F3, a.values, b.values); + case 78: + return _mm512_mask_blend_ps(0x30FC, a.values, b.values); + case 79: + return _mm512_mask_blend_ps(0x30FF, a.values, b.values); + case 80: + return _mm512_mask_blend_ps(0x3300, a.values, b.values); + case 81: + return _mm512_mask_blend_ps(0X3303, a.values, b.values); + case 82: + return _mm512_mask_blend_ps(0x330C, a.values, b.values); + case 83: + return _mm512_mask_blend_ps(0x330F, a.values, b.values); + case 84: + return _mm512_mask_blend_ps(0x3330, a.values, b.values); + case 85: + return _mm512_mask_blend_ps(0x3333, a.values, b.values); + case 86: + return _mm512_mask_blend_ps(0x333C, a.values, b.values); + case 87: + return _mm512_mask_blend_ps(0X333F, a.values, b.values); + case 88: + return _mm512_mask_blend_ps(0x33C0, a.values, b.values); + case 89: + return _mm512_mask_blend_ps(0x33C3, a.values, b.values); + case 90: + return _mm512_mask_blend_ps(0x33CC, a.values, b.values); + case 91: + return _mm512_mask_blend_ps(0x33CF, a.values, b.values); + case 92: + return _mm512_mask_blend_ps(0x33F0, a.values, b.values); + case 93: + return _mm512_mask_blend_ps(0x33F3, a.values, b.values); + case 94: + return _mm512_mask_blend_ps(0x33FC, a.values, b.values); + case 95: + return _mm512_mask_blend_ps(0x33FF, a.values, b.values); + case 96: + return _mm512_mask_blend_ps(0X3C00, a.values, b.values); + case 97: + return _mm512_mask_blend_ps(0x3C03, a.values, b.values); + case 98: + return _mm512_mask_blend_ps(0x3C0C, a.values, b.values); + case 99: + return _mm512_mask_blend_ps(0x3C0F, a.values, b.values); + case 100: + return _mm512_mask_blend_ps(0x3C30, a.values, b.values); + case 101: + return _mm512_mask_blend_ps(0x3C33, a.values, b.values); + case 102: + return _mm512_mask_blend_ps(0x3C3C, a.values, b.values); + case 103: + return _mm512_mask_blend_ps(0x3C3F, a.values, b.values); + case 104: + return _mm512_mask_blend_ps(0x3CC0, a.values, b.values); + case 105: + return _mm512_mask_blend_ps(0x3CC3, a.values, b.values); + case 106: + return _mm512_mask_blend_ps(0x3CCC, a.values, b.values); + case 107: + return _mm512_mask_blend_ps(0x3CCF, a.values, b.values); + case 108: + return _mm512_mask_blend_ps(0x3CF0, a.values, b.values); + case 109: + return _mm512_mask_blend_ps(0x3CF3, a.values, b.values); + case 110: + return _mm512_mask_blend_ps(0x3CFC, a.values, b.values); + case 111: + return _mm512_mask_blend_ps(0x3CFF, a.values, b.values); + case 112: + return _mm512_mask_blend_ps(0x3F00, a.values, b.values); + case 113: + return _mm512_mask_blend_ps(0x3F03, a.values, b.values); + case 114: + return _mm512_mask_blend_ps(0x3F0C, a.values, b.values); + case 115: + return _mm512_mask_blend_ps(0x3F0F, a.values, b.values); + case 116: + return _mm512_mask_blend_ps(0x3F30, a.values, b.values); + case 117: + return _mm512_mask_blend_ps(0x3F33, a.values, b.values); + case 118: + return _mm512_mask_blend_ps(0x3F3C, a.values, b.values); + case 119: + return _mm512_mask_blend_ps(0x3F3F, a.values, b.values); + case 120: + return _mm512_mask_blend_ps(0x3FC0, a.values, b.values); + case 121: + return _mm512_mask_blend_ps(0x3FC3, a.values, b.values); + case 122: + return _mm512_mask_blend_ps(0x3FCC, a.values, b.values); + case 123: + return _mm512_mask_blend_ps(0x3FCF, a.values, b.values); + case 124: + return _mm512_mask_blend_ps(0x3FF0, a.values, b.values); + case 125: + return _mm512_mask_blend_ps(0x3FF3, a.values, b.values); + case 126: + return _mm512_mask_blend_ps(0x3FFC, a.values, b.values); + case 127: + return _mm512_mask_blend_ps(0x3FFF, a.values, b.values); + case 128: + return _mm512_mask_blend_ps(0xC000, a.values, b.values); + case 129: + return _mm512_mask_blend_ps(0xC003, a.values, b.values); + case 130: + return _mm512_mask_blend_ps(0xC00C, a.values, b.values); + case 131: + return _mm512_mask_blend_ps(0xC00F, a.values, b.values); + case 132: + return _mm512_mask_blend_ps(0xC030, a.values, b.values); + case 133: + return _mm512_mask_blend_ps(0xC033, a.values, b.values); + case 134: + return _mm512_mask_blend_ps(0xC03C, a.values, b.values); + case 135: + return _mm512_mask_blend_ps(0xC03F, a.values, b.values); + case 136: + return _mm512_mask_blend_ps(0xC0C0, a.values, b.values); + case 137: + return _mm512_mask_blend_ps(0xC0C3, a.values, b.values); + case 138: + return _mm512_mask_blend_ps(0xC0CC, a.values, b.values); + case 139: + return _mm512_mask_blend_ps(0xC0CF, a.values, b.values); + case 140: + return _mm512_mask_blend_ps(0xC0F0, a.values, b.values); + case 141: + return _mm512_mask_blend_ps(0xC0F3, a.values, b.values); + case 142: + return _mm512_mask_blend_ps(0xC0FC, a.values, b.values); + case 143: + return _mm512_mask_blend_ps(0xC0FF, a.values, b.values); + case 144: + return _mm512_mask_blend_ps(0xC300, a.values, b.values); + case 145: + return _mm512_mask_blend_ps(0xC303, a.values, b.values); + case 146: + return _mm512_mask_blend_ps(0xC30C, a.values, b.values); + case 147: + return _mm512_mask_blend_ps(0xC30F, a.values, b.values); + case 148: + return _mm512_mask_blend_ps(0xC330, a.values, b.values); + case 149: + return _mm512_mask_blend_ps(0xC333, a.values, b.values); + case 150: + return _mm512_mask_blend_ps(0xC33C, a.values, b.values); + case 151: + return _mm512_mask_blend_ps(0xC33F, a.values, b.values); + case 152: + return _mm512_mask_blend_ps(0xC3C0, a.values, b.values); + case 153: + return _mm512_mask_blend_ps(0xC3C3, a.values, b.values); + case 154: + return _mm512_mask_blend_ps(0xC3CC, a.values, b.values); + case 155: + return _mm512_mask_blend_ps(0xC3CF, a.values, b.values); + case 156: + return _mm512_mask_blend_ps(0xC3F0, a.values, b.values); + case 157: + return _mm512_mask_blend_ps(0xC3F3, a.values, b.values); + case 158: + return _mm512_mask_blend_ps(0xC3FC, a.values, b.values); + case 159: + return _mm512_mask_blend_ps(0xC3FF, a.values, b.values); + case 160: + return _mm512_mask_blend_ps(0xCC00, a.values, b.values); + case 161: + return _mm512_mask_blend_ps(0xCC03, a.values, b.values); + case 162: + return _mm512_mask_blend_ps(0xCC0C, a.values, b.values); + case 163: + return _mm512_mask_blend_ps(0xCC0F, a.values, b.values); + case 164: + return _mm512_mask_blend_ps(0xCC30, a.values, b.values); + case 165: + return _mm512_mask_blend_ps(0xCC33, a.values, b.values); + case 166: + return _mm512_mask_blend_ps(0xCC3C, a.values, b.values); + case 167: + return _mm512_mask_blend_ps(0xCC3F, a.values, b.values); + case 168: + return _mm512_mask_blend_ps(0xCCC0, a.values, b.values); + case 169: + return _mm512_mask_blend_ps(0xCCC3, a.values, b.values); + case 170: + return _mm512_mask_blend_ps(0xCCCC, a.values, b.values); + case 171: + return _mm512_mask_blend_ps(0xCCCF, a.values, b.values); + case 172: + return _mm512_mask_blend_ps(0xCCF0, a.values, b.values); + case 173: + return _mm512_mask_blend_ps(0xCCF3, a.values, b.values); + case 174: + return _mm512_mask_blend_ps(0xCCFC, a.values, b.values); + case 175: + return _mm512_mask_blend_ps(0xCCFF, a.values, b.values); + case 176: + return _mm512_mask_blend_ps(0xCF00, a.values, b.values); + case 177: + return _mm512_mask_blend_ps(0xCF03, a.values, b.values); + case 178: + return _mm512_mask_blend_ps(0xCF0C, a.values, b.values); + case 179: + return _mm512_mask_blend_ps(0xCF0F, a.values, b.values); + case 180: + return _mm512_mask_blend_ps(0xCF30, a.values, b.values); + case 181: + return _mm512_mask_blend_ps(0xCF33, a.values, b.values); + case 182: + return _mm512_mask_blend_ps(0xCF3C, a.values, b.values); + case 183: + return _mm512_mask_blend_ps(0xCF3F, a.values, b.values); + case 184: + return _mm512_mask_blend_ps(0xCFC0, a.values, b.values); + case 185: + return _mm512_mask_blend_ps(0xCFC3, a.values, b.values); + case 186: + return _mm512_mask_blend_ps(0xCFCC, a.values, b.values); + case 187: + return _mm512_mask_blend_ps(0xCFCF, a.values, b.values); + case 188: + return _mm512_mask_blend_ps(0xCFF0, a.values, b.values); + case 189: + return _mm512_mask_blend_ps(0xCFF3, a.values, b.values); + case 190: + return _mm512_mask_blend_ps(0xCFFC, a.values, b.values); + case 191: + return _mm512_mask_blend_ps(0xCFFF, a.values, b.values); + case 192: + return _mm512_mask_blend_ps(0xF000, a.values, b.values); + case 193: + return _mm512_mask_blend_ps(0xF003, a.values, b.values); + case 194: + return _mm512_mask_blend_ps(0xF00C, a.values, b.values); + case 195: + return _mm512_mask_blend_ps(0xF00F, a.values, b.values); + case 196: + return _mm512_mask_blend_ps(0xF030, a.values, b.values); + case 197: + return _mm512_mask_blend_ps(0xF033, a.values, b.values); + case 198: + return _mm512_mask_blend_ps(0xF03C, a.values, b.values); + case 199: + return _mm512_mask_blend_ps(0xF03F, a.values, b.values); + case 200: + return _mm512_mask_blend_ps(0XF0C0, a.values, b.values); + case 201: + return _mm512_mask_blend_ps(0xF0C3, a.values, b.values); + case 202: + return _mm512_mask_blend_ps(0xF0CC, a.values, b.values); + case 203: + return _mm512_mask_blend_ps(0xF0CF, a.values, b.values); + case 204: + return _mm512_mask_blend_ps(0xF0F0, a.values, b.values); + case 205: + return _mm512_mask_blend_ps(0xF0F3, a.values, b.values); + case 206: + return _mm512_mask_blend_ps(0xF0FC, a.values, b.values); + case 207: + return _mm512_mask_blend_ps(0xF0FF, a.values, b.values); + case 208: + return _mm512_mask_blend_ps(0XF300, a.values, b.values); + case 209: + return _mm512_mask_blend_ps(0xF303, a.values, b.values); + case 210: + return _mm512_mask_blend_ps(0xF30C, a.values, b.values); + case 211: + return _mm512_mask_blend_ps(0xF30F, a.values, b.values); + case 212: + return _mm512_mask_blend_ps(0xF330, a.values, b.values); + case 213: + return _mm512_mask_blend_ps(0xF333, a.values, b.values); + case 214: + return _mm512_mask_blend_ps(0XF33C, a.values, b.values); + case 215: + return _mm512_mask_blend_ps(0xF33F, a.values, b.values); + case 216: + return _mm512_mask_blend_ps(0xF3C0, a.values, b.values); + case 217: + return _mm512_mask_blend_ps(0xF3C3, a.values, b.values); + case 218: + return _mm512_mask_blend_ps(0xF3CC, a.values, b.values); + case 219: + return _mm512_mask_blend_ps(0xF3CF, a.values, b.values); + case 220: + return _mm512_mask_blend_ps(0xF3F0, a.values, b.values); + case 221: + return _mm512_mask_blend_ps(0xF3F3, a.values, b.values); + case 222: + return _mm512_mask_blend_ps(0xF3FC, a.values, b.values); + case 223: + return _mm512_mask_blend_ps(0XF3FF, a.values, b.values); + case 224: + return _mm512_mask_blend_ps(0xFC00, a.values, b.values); + case 225: + return _mm512_mask_blend_ps(0xFC03, a.values, b.values); + case 226: + return _mm512_mask_blend_ps(0xFC0C, a.values, b.values); + case 227: + return _mm512_mask_blend_ps(0xFC0F, a.values, b.values); + case 228: + return _mm512_mask_blend_ps(0xFC30, a.values, b.values); + case 229: + return _mm512_mask_blend_ps(0xFC33, a.values, b.values); + case 230: + return _mm512_mask_blend_ps(0xFC3C, a.values, b.values); + case 231: + return _mm512_mask_blend_ps(0xFC3F, a.values, b.values); + case 232: + return _mm512_mask_blend_ps(0xFCC0, a.values, b.values); + case 233: + return _mm512_mask_blend_ps(0xFCC3, a.values, b.values); + case 234: + return _mm512_mask_blend_ps(0xFCCC, a.values, b.values); + case 235: + return _mm512_mask_blend_ps(0xFCCF, a.values, b.values); + case 236: + return _mm512_mask_blend_ps(0xFCF0, a.values, b.values); + case 237: + return _mm512_mask_blend_ps(0xFCF3, a.values, b.values); + case 238: + return _mm512_mask_blend_ps(0xFCFC, a.values, b.values); + case 239: + return _mm512_mask_blend_ps(0xFCFF, a.values, b.values); + case 240: + return _mm512_mask_blend_ps(0xFF00, a.values, b.values); + case 241: + return _mm512_mask_blend_ps(0xFF03, a.values, b.values); + case 242: + return _mm512_mask_blend_ps(0xFF0C, a.values, b.values); + case 243: + return _mm512_mask_blend_ps(0xFF0F, a.values, b.values); + case 244: + return _mm512_mask_blend_ps(0xFF30, a.values, b.values); + case 245: + return _mm512_mask_blend_ps(0xFF33, a.values, b.values); + case 246: + return _mm512_mask_blend_ps(0xFF3C, a.values, b.values); + case 247: + return _mm512_mask_blend_ps(0xFF3F, a.values, b.values); + case 248: + return _mm512_mask_blend_ps(0xFFC0, a.values, b.values); + case 249: + return _mm512_mask_blend_ps(0xFFC3, a.values, b.values); + case 250: + return _mm512_mask_blend_ps(0xFFCC, a.values, b.values); + case 251: + return _mm512_mask_blend_ps(0xFFCF, a.values, b.values); + case 252: + return _mm512_mask_blend_ps(0xFFF0, a.values, b.values); + case 253: + return _mm512_mask_blend_ps(0xFFF3, a.values, b.values); + case 254: + return _mm512_mask_blend_ps(0xFFFC, a.values, b.values); + default: + break; + } + return b; + } + static Vectorized> blendv( + const Vectorized>& a, + const Vectorized>& b, + const Vectorized>& mask) { + // convert c10::complex index mask to V index mask: xy -> xxyy + auto mask_ = _mm512_unpacklo_ps(mask.values, mask.values); + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + auto mmask = _mm512_cmp_epi32_mask( + _mm512_castps_si512(mask_), all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_ps(mmask, a.values, b.values); + } + template + static Vectorized> arange( + c10::complex base = 0., + step_t step = static_cast(1)) { + return Vectorized>( + base, + base + step, + base + c10::complex(2) * step, + base + c10::complex(3) * step, + base + c10::complex(4) * step, + base + c10::complex(5) * step, + base + c10::complex(6) * step, + base + c10::complex(7) * step); + } + static Vectorized> set( + const Vectorized>& a, + const Vectorized>& b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + } + return b; + } + static Vectorized> loadu( + const void* ptr, + int64_t count = size()) { + if (count == size()) + return _mm512_loadu_ps(reinterpret_cast(ptr)); + + // Zero tail past `count`. + __at_align__ float tmp_values[2 * size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(c10::complex)); + return _mm512_load_ps(tmp_values); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_ps(reinterpret_cast(ptr), values); + } else if (count > 0) { + float tmp_values[2 * size()]; + _mm512_storeu_ps(reinterpret_cast(tmp_values), values); + std::memcpy( + ptr, + tmp_values, + std::min(count, size()) * sizeof(c10::complex)); + } + } + // AVX512 doesn't have horizontal add & horizontal sub instructions. + // TODO: hadd_pd() & hsub_pd() may have scope for improvement. + static inline __m512 hadd_ps(__m512 a, __m512 b) { + __m512i idx1 = _mm512_set_epi32( + 30, 14, 28, 12, 26, 10, 24, 8, 22, 6, 20, 4, 18, 2, 16, 0); + __m512i idx2 = _mm512_set_epi32( + 31, 15, 29, 13, 27, 11, 25, 9, 23, 7, 21, 5, 19, 3, 17, 1); + return _mm512_add_ps( + _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b), + _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b)); + } + static inline __m512 hsub_ps(__m512 a, __m512 b) { + __m512i idx1 = _mm512_set_epi32( + 30, 14, 28, 12, 26, 10, 24, 8, 22, 6, 20, 4, 18, 2, 16, 0); + __m512i idx2 = _mm512_set_epi32( + 31, 15, 29, 13, 27, 11, 25, 9, 23, 7, 21, 5, 19, 3, 17, 1); + return _mm512_sub_ps( + _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b), + _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b)); + } + const c10::complex& operator[](int idx) const = delete; + c10::complex& operator[](int idx) = delete; + Vectorized> map( + c10::complex (*const f)(const c10::complex&)) const { + __at_align__ c10::complex tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = f(tmp[i]); + } + return loadu(tmp); + } + __m512 abs_2_() const { + auto val_2 = _mm512_mul_ps(values, values); // a*a b*b + auto ret = hadd_ps(val_2, val_2); // a*a+b*b a*a+b*b + return ret; + } + __m512 abs_() const { + auto real = _mm512_moveldup_ps(values); // real real + auto imag = _mm512_movehdup_ps(values); // imag imag + return Sleef_hypotf16_u05(real, imag); // abs abs + } + Vectorized> abs() const { + const __m512 real_mask = _mm512_castsi512_ps(_mm512_setr_epi32( + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000)); + return _mm512_and_ps(abs_(), real_mask); // abs 0 + } + __m512 angle_() const { + // angle = atan2(b/a) + auto b_a = _mm512_permute_ps(values, 0xB1); // b a + return Sleef_atan2f16_u10(values, b_a); // 90-angle angle + } + Vectorized> angle() const { + const __m512 real_mask = _mm512_castsi512_ps(_mm512_setr_epi32( + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000)); + auto angle = _mm512_permute_ps(angle_(), 0xB1); // angle 90-angle + return _mm512_and_ps(angle, real_mask); // angle 0 + } + Vectorized> sgn() const { + auto abs = abs_(); + auto zero = _mm512_setzero_ps(); + auto mask = _mm512_cmp_ps_mask(abs, zero, _CMP_EQ_OQ); + auto div = _mm512_div_ps(values, abs); + return _mm512_mask_blend_ps(mask, div, zero); + } + __m512 real_() const { + const __m512 real_mask = _mm512_castsi512_ps(_mm512_setr_epi32( + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000)); + return _mm512_and_ps(values, real_mask); + } + Vectorized> real() const { + return real_(); + } + __m512 imag_() const { + const __m512 imag_mask = _mm512_castsi512_ps(_mm512_setr_epi32( + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF, + 0x00000000, + 0xFFFFFFFF)); + return _mm512_and_ps(values, imag_mask); + } + Vectorized> imag() const { + return _mm512_permute_ps(imag_(), 0xB1); // b a + } + __m512 conj_() const { + const __m512 sign_mask = _mm512_setr_ps( + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0); + return _mm512_xor_ps(values, sign_mask); // a -b + } + Vectorized> conj() const { + return conj_(); + } + Vectorized> log() const { + // Most trigonomic ops use the log() op to improve complex number + // performance. + return map(std::log); + } + Vectorized> log2() const { + const __m512 log2_ = _mm512_set1_ps(std::log(2)); + return _mm512_div_ps(log(), log2_); + } + Vectorized> log10() const { + const __m512 log10_ = _mm512_set1_ps(std::log(10)); + return _mm512_div_ps(log(), log10_); + } + Vectorized> log1p() const { + return map(std::log1p); + } + Vectorized> asin() const { + // TODO: The vectorized implementation requires special handling for the + // case where real number/imag number is 0/Inf/NaN. + // // asin(x) + // // = -i*ln(iz + sqrt(1 -z^2)) + // // = -i*ln((ai - b) + sqrt(1 - (a + bi)*(a + bi))) + // // = -i*ln((-b + ai) + sqrt(1 - (a**2 - b**2) - 2*abi)) + // const __m512 one = _mm512_set1_ps(1); + + // auto conj = conj_(); + // auto b_a = _mm512_permute_ps(conj, 0xB1); //-b a + // auto ab = _mm512_mul_ps(conj, b_a); //-ab + // -ab auto im = _mm512_add_ps(ab, ab); //-2ab -2ab + + // auto val_2 = _mm512_mul_ps(values, values); // a*a + // b*b auto re = hsub_ps(val_2, _mm512_permute_ps(val_2, 0xB1)); // a*a-b*b + // b*b-a*a re = _mm512_sub_ps(one, re); + + // auto root = Vectorized(_mm512_mask_blend_ps(0xAAAA, re, im)).sqrt(); + // //sqrt(re + i*im) auto ln = Vectorized(_mm512_add_ps(b_a, root)).log(); + // //ln(iz + sqrt()) return Vectorized(_mm512_permute_ps(ln.values, + // 0xB1)).conj(); //-i*ln() + return map(std::asin); + } + Vectorized> acos() const { + return map(std::acos); + } + Vectorized> atan() const; + Vectorized> atanh() const { + return map(std::atanh); + } + Vectorized> exp() const { + // TODO: The vectorized implementation requires special handling for the + // case where real number/imag number is 0/Inf/NaN. + // //exp(a + bi) + // // = exp(a)*(cos(b) + sin(b)i) + // auto exp = Sleef_expf16_u10(values); //exp(a) exp(b) exp = + // _mm512_mask_blend_ps(0xAAAA, exp, _mm512_permute_ps(exp, 0xB1)); //exp(a) + // exp(a) + + // auto sin_cos = Sleef_sincosf16_u10(values); //[sin(a), cos(a)] [sin(b), + // cos(b)] auto cos_sin = _mm512_mask_blend_ps(0xAAAA, + // _mm512_permute_ps(sin_cos.y, 0xB1), + // sin_cos.x); //cos(b) + // sin(b) + // return _mm512_mul_ps(exp, cos_sin); + return map(std::exp); + } + Vectorized> exp2() const { + // Use identity 2**x = exp(log(2) * x) + const __m512 ln_2 = _mm512_set1_ps(c10::ln_2); + Vectorized> scaled_values = _mm512_mul_ps(values, ln_2); + return scaled_values.exp(); + } + Vectorized> expm1() const { + return map(std::expm1); + } + Vectorized> sin() const { + return map(std::sin); + } + Vectorized> sinh() const { + return map(std::sinh); + } + Vectorized> cos() const { + return map(std::cos); + } + Vectorized> cosh() const { + return map(std::cosh); + } + Vectorized> ceil() const { + return _mm512_ceil_ps(values); + } + Vectorized> floor() const { + return _mm512_floor_ps(values); + } + Vectorized> neg() const { + auto zero = _mm512_setzero_ps(); + return _mm512_sub_ps(zero, values); + } + Vectorized> round() const { + return _mm512_roundscale_ps( + values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + } + Vectorized> tan() const { + return map(std::tan); + } + Vectorized> tanh() const { + return map(std::tanh); + } + Vectorized> trunc() const { + return _mm512_roundscale_ps( + values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + } + Vectorized> sqrt() const { + return map(std::sqrt); + } + Vectorized> reciprocal() const; + Vectorized> rsqrt() const { + return sqrt().reciprocal(); + } + Vectorized> pow( + const Vectorized>& exp) const { + __at_align__ c10::complex x_tmp[size()]; + __at_align__ c10::complex y_tmp[size()]; + store(x_tmp); + exp.store(y_tmp); + for (const auto i : c10::irange(size())) { + x_tmp[i] = std::pow(x_tmp[i], y_tmp[i]); + } + return loadu(x_tmp); + } + // Comparison using the _CMP_**_OQ predicate. + // `O`: get false if an operand is NaN + // `Q`: do not raise if an operand is NaN + Vectorized> operator==( + const Vectorized>& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_EQ_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF)); + } + Vectorized> operator!=( + const Vectorized>& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_NEQ_UQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF)); + } + Vectorized> operator<( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator<=( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator>( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + Vectorized> operator>=( + const Vectorized>& other [[maybe_unused]]) const { + TORCH_CHECK(false, "not supported for complex numbers"); + } + + Vectorized> eq( + const Vectorized>& other) const; + Vectorized> ne( + const Vectorized>& other) const; +}; + +template <> +Vectorized> inline operator+( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_add_ps(a, b); +} + +template <> +Vectorized> inline operator-( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_sub_ps(a, b); +} + +template <> +Vectorized> inline operator*( + const Vectorized>& a, + const Vectorized>& b) { + //(a + bi) * (c + di) = (ac - bd) + (ad + bc)i + const __m512 sign_mask = _mm512_setr_ps( + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0, + 0.0, + -0.0); + auto ac_bd = _mm512_mul_ps(a, b); // ac bd + + auto d_c = _mm512_permute_ps(b, 0xB1); // d c + d_c = _mm512_xor_ps(sign_mask, d_c); // d -c + auto ad_bc = _mm512_mul_ps(a, d_c); // ad -bc + + auto ret = Vectorized>::hsub_ps( + ac_bd, ad_bc); // ac - bd ad + bc + return ret; +} + +template <> +Vectorized> inline operator/( + const Vectorized>& a, + const Vectorized>& b) { + // TODO: The vectorized implementation requires special handling for the case + // where real number/imag number is 0/Inf/NaN. + // //re + im*i = (a + bi) / (c + di) + // auto mask = _mm512_set1_ps(-0.f); + // auto fabs_cd = _mm512_andnot_ps(mask, b); // |c| |d| + // auto fabs_dc = _mm512_permute_ps(fabs_cd, 0xB1); // |d| |c| + // auto scale = _mm512_rcp14_ps(_mm512_max_ps(fabs_cd, fabs_dc)); // 1/sc + // 1/sc auto a2 = _mm512_mul_ps(a, scale); // a/sc b/sc auto b2 = + // _mm512_mul_ps(b, scale); // c/sc d/sc auto acbd2 = + // _mm512_mul_ps(a2, b2); + + // const __m512 sign_mask = _mm512_setr_ps(-0.0, 0.0, -0.0, 0.0, -0.0, 0.0, + // -0.0, 0.0, + // -0.0, 0.0, -0.0, 0.0, -0.0, 0.0, + // -0.0, 0.0); + // auto dc2 = _mm512_permute_ps(b2, 0xB1); // d/sc c/sc + // dc2 = _mm512_xor_ps(sign_mask, dc2); // -d/|c,d| c/sc + // auto adbc2 = _mm512_mul_ps(a2, dc2); //-ad/sc^2 bc/sc^2 + // auto res2 = Vectorized>::hadd_ps(acbd2, adbc2); + // //(ac+bd)/sc^2 (bc-ad)/sc^2 + + // // get the denominator + // auto denom2 = Vectorized>(b2).abs_2_(); // + // (c^2+d^2)/sc^2 (c^2+d^2)/sc^2 res2 = _mm512_div_ps(res2, denom2); return + // res2; + __at_align__ c10::complex + tmp1[Vectorized>::size()]; + __at_align__ c10::complex + tmp2[Vectorized>::size()]; + __at_align__ c10::complex out[Vectorized>::size()]; + a.store(tmp1); + b.store(tmp2); + for (const auto i : c10::irange(Vectorized>::size())) { + out[i] = tmp1[i] / tmp2[i]; + } + return _mm512_loadu_ps(reinterpret_cast(out)); +} + +// reciprocal. Implement this here so we can use multiplication. +inline Vectorized> Vectorized< + c10::complex>::reciprocal() const { + // TODO: The vectorized implementation requires special handling for the case + // where real number/imag number is 0/Inf/NaN. + // //re + im*i = (a + bi) / (c + di) + // //re = (ac + bd)/abs_2() = c/abs_2() + // //im = (bc - ad)/abs_2() = d/abs_2() + // const __m512 sign_mask = _mm512_setr_ps(0.0, -0.0, 0.0, -0.0, 0.0, -0.0, + // 0.0, -0.0, + // 0.0, -0.0, 0.0, -0.0, 0.0, -0.0, + // 0.0, -0.0); + // auto c_d = _mm512_xor_ps(sign_mask, values); //c -d + // return _mm512_div_ps(c_d, abs_2_()); + __at_align__ c10::complex tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = c10::complex(1) / tmp[i]; + } + return loadu(tmp); +} + +inline Vectorized> Vectorized>::atan() + const { + // TODO: The vectorized implementation requires special handling for the case + // where real number/imag number is 0/Inf/NaN. + // // atan(x) = i/2 * ln((i + z)/(i - z)) + // const __m512 i = _mm512_setr_ps(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, + // 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0); + // const Vectorized i_half = _mm512_setr_ps(0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, + // 0.5, + // 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, + // 0.5); + + // auto sum = Vectorized(_mm512_add_ps(i, values)); // a + // 1+b auto sub = Vectorized(_mm512_sub_ps(i, values)); // -a 1-b auto + // ln = (sum/sub).log(); // ln((i + + // z)/(i - z)) return i_half*ln; // i/2*ln() + return map(std::atan); +} + +template <> +Vectorized> inline maximum( + const Vectorized>& a, + const Vectorized>& b) { + auto zero_vector = _mm512_set1_epi32(0); + auto abs_a = a.abs_2_(); + auto abs_b = b.abs_2_(); + auto mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_LT_OQ); + auto max = _mm512_mask_blend_ps(mask, a, b); + // Exploit the fact that all-ones is a NaN. + auto isnan_mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_UNORD_Q); + auto isnan = _mm512_mask_set1_epi32(zero_vector, isnan_mask, 0xFFFFFFFF); + return _mm512_or_ps(max, _mm512_castsi512_ps(isnan)); +} + +template <> +Vectorized> inline minimum( + const Vectorized>& a, + const Vectorized>& b) { + auto zero_vector = _mm512_set1_epi32(0); + auto abs_a = a.abs_2_(); + auto abs_b = b.abs_2_(); + auto mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_GT_OQ); + auto min = _mm512_mask_blend_ps(mask, a, b); + // Exploit the fact that all-ones is a NaN. + auto isnan_mask = _mm512_cmp_ps_mask(abs_a, abs_b, _CMP_UNORD_Q); + auto isnan = _mm512_mask_set1_epi32(zero_vector, isnan_mask, 0xFFFFFFFF); + return _mm512_or_ps(min, _mm512_castsi512_ps(isnan)); +} + +template <> +Vectorized> inline operator&( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_and_ps(a, b); +} + +template <> +Vectorized> inline operator|( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_or_ps(a, b); +} + +template <> +Vectorized> inline operator^( + const Vectorized>& a, + const Vectorized>& b) { + return _mm512_xor_ps(a, b); +} + +inline Vectorized> Vectorized>::eq( + const Vectorized>& other) const { + auto eq = (*this == other); // compares real and imag individually + // If both real numbers and imag numbers are equal, then the complex numbers + // are equal + return (eq.real() & eq.imag()) & + Vectorized>(_mm512_set1_ps(1.0f)); +} + +inline Vectorized> Vectorized>::ne( + const Vectorized>& other) const { + auto ne = (*this != other); // compares real and imag individually + // If either real numbers or imag numbers are not equal, then the complex + // numbers are not equal + return (ne.real() | ne.imag()) & + Vectorized>(_mm512_set1_ps(1.0f)); +} + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_convert.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_convert.h new file mode 100644 index 0000000000000000000000000000000000000000..d06e291d1414976e807320cee488eb3063414f01 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_convert.h @@ -0,0 +1,400 @@ +#pragma once + +#include +#include +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + VectorizedN result; + __m512 value; + cvtbf16_fp32(_mm512_castsi512_si256(src[0]), value); + result[0] = value; + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply(const VectorizedN& src) { + VectorizedN result; + __m512 value; + cvtfp16_fp32(_mm512_castsi512_si256(src[0]), value); + result[0] = value; + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + VectorizedN result; + result[0] = _mm512_castsi256_si512(cvtfp32_bf16(src[0])); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + VectorizedN result; + result[0] = convert_float_bfloat16(src[0], src[1]); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + VectorizedN result; + std::tie(result[0], result[1]) = convert_bfloat16_float(src[0]); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply(const VectorizedN& src) { + VectorizedN result; + result[0] = _mm512_castsi256_si512(cvtfp32_fp16(src[0])); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply(const VectorizedN& src) { + VectorizedN result; + result[0] = convert_float_half(src[0], src[1]); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply(const VectorizedN& src) { + VectorizedN result; + std::tie(result[0], result[1]) = convert_half_float(src[0]); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto low = _mm512_cvtepi64_ps(src[0]); + auto high = _mm512_cvtepi64_ps(src[1]); + return Vectorized( + _mm512_insertf32x8(_mm512_castps256_ps512(low), high, 1)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + at::vec::VectorizedN result; + result[0] = _mm512_cvt_roundps_epi64( + _mm512_castps512_ps256(src[0]), _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC); + result[1] = _mm512_cvt_roundps_epi64( + _mm512_extractf32x8_ps(src[0], 1), + _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto low = _mm512_cvtepi64_epi32(src[0]); + auto high = _mm512_cvtepi64_epi32(src[1]); + return Vectorized( + _mm512_inserti32x8(_mm512_castsi256_si512(low), high, 1)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + at::vec::VectorizedN result; + result[0] = _mm512_cvtepi32_epi64(_mm512_castsi512_si256(src[0])); + result[1] = _mm512_cvtepi32_epi64(_mm512_extracti32x8_epi32(src[0], 1)); + return result; + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto src128 = _mm512_castsi512_si128(src[0]); + return Vectorized(_mm512_cvtepi8_epi32(src128)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto src128 = _mm512_castsi512_si128(src[0]); + return Vectorized(_mm512_cvtepu8_epi32(src128)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + return Vectorized(_mm512_cvttps_epi32(src[0])); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + return Vectorized(_mm512_cvtepi32_ps(src[0])); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto src256 = _mm512_castsi512_si256(src[0]); + return Vectorized(_mm512_cvtepu8_epi16(src256)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto src128 = _mm512_cvtepi32_epi8(src[0]); + return Vectorized(_mm512_castsi128_si512(src128)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + auto src256 = _mm512_cvtepi16_epi8(src[0]); + return Vectorized(_mm512_castsi256_si512(src256)); + } +}; + +template +struct VecConvert< + dst_t, + 1, + src_t, + 1, + typename std::enable_if_t< + (is_reduced_floating_point_v && is_8bit_integer_v) || + (is_reduced_floating_point_v && is_8bit_integer_v), + void>> { + static inline VectorizedN apply(const VectorizedN& src) { + VectorizedN tmp_fp32 = VecConvert::apply(src); + return VecConvert::apply(tmp_fp32); + } +}; + +template +struct VecRoundConvert< + dst_t, + 1, + float, + 2, + typename std::enable_if_t, void>> { + static inline VectorizedN apply(const VectorizedN& src) { + at::vec::Vectorized vec1 = + round_convert_float_to_int8(src[0]); + at::vec::Vectorized vec2 = + round_convert_float_to_int8(src[1]); + __m128i vec2_lo = _mm512_castsi512_si128(vec2); + __m512i out = _mm512_inserti32x4(vec1, vec2_lo, 1); + return VectorizedN(at::vec::Vectorized(out)); + } +}; + +template +struct VecConvert< + dst_t, + 1, + float, + 2, + typename std::enable_if_t, void>> { + static inline VectorizedN apply(const VectorizedN& src) { + at::vec::Vectorized vec1 = convert_float_to_int8(src[0]); + at::vec::Vectorized vec2 = convert_float_to_int8(src[1]); + __m128 lane2 = _mm512_castps512_ps128(_mm512_castsi512_ps(vec2)); + __m512 result = _mm512_insertf32x4( + _mm512_castsi512_ps(vec1), + lane2, + 1); // Insert lane2 into the second 128-bit lane + return at::vec::Vectorized(_mm512_castps_si512(result)); + } +}; + +template +struct VecConvert< + dst_t, + 1, + float, + 1, + typename std::enable_if_t, void>> { + static inline VectorizedN apply(const VectorizedN& src) { + return convert_float_to_int8(src[0]); + } +}; + +template +struct VecRoundConvert< + dst_t, + 1, + float, + 1, + typename std::enable_if_t, void>> { + static inline VectorizedN apply(const VectorizedN& src) { + return round_convert_float_to_int8(src[0]); + } +}; + +template +struct VecConvert< + float, + 2, + src_t, + 1, + typename std::enable_if_t, void>> { + static inline VectorizedN apply(const VectorizedN& src) { + __m512i src2 = + _mm512_castsi128_si512(_mm_castps_si128(_mm512_extractf32x4_ps( + _mm512_castsi512_ps(src[0]), 1) // Extract the second 128-bit lane + )); + return VectorizedN( + convert_int8_to_float(src[0]), + convert_int8_to_float(src2)); + } +}; + +template +struct VecConvert< + float, + 1, + src_t, + 1, + typename std::enable_if_t, void>> { + static inline VectorizedN apply(const VectorizedN& src) { + return convert_int8_to_float(src[0]); + } +}; + +template +struct VecConvert< + dst_t, + 1, + int64_t, + 2, + std::enable_if_t< + std::is_same_v || std::is_same_v>> { + static inline VectorizedN apply( + const VectorizedN& src) { + return VecConvert::apply( + VecConvert::apply(src)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src_n) { + at::vec::Vectorized src = src_n[0]; + __m128i res128 = cvtfp32_fp8e4m3(src); + return at::vec::Vectorized(_mm512_castsi128_si512(res128)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src_n) { + // cvt first 16x8 bits from Float8_e4m3fn to float + at::vec::Vectorized src = src_n[0]; + __m512 result; + cvtfp8e4m3_fp32(_mm512_castsi512_si128(src), result); + return at::vec::Vectorized(result); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src_n) { + at::vec::Vectorized src = src_n[0]; + __m128i res128 = cvtfp32_fp8e5m2(src); + return at::vec::Vectorized(_mm512_castsi128_si512(res128)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src_n) { + // cvt first 16x8 bits from Float8_e5m2 to float + at::vec::Vectorized src = src_n[0]; + __m512 result; + cvtfp8e5m2_fp32(_mm512_castsi512_si128(src), result); + return at::vec::Vectorized(result); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src_n) { + at::vec::Vectorized src = src_n[0]; + __m512i values = src; + __m512 result0, result1; + cvtfp8e4m3_fp32(_mm512_castsi512_si128(values), result0); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(values, 1), result1); + return VectorizedN( + at::vec::Vectorized(result0), + at::vec::Vectorized(result1)); + } +}; + +template <> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src_n) { + at::vec::Vectorized src0 = src_n[0]; + at::vec::Vectorized src1 = src_n[1]; + __m128i lane0 = cvtfp32_fp8e4m3(src0); + __m128i lane1 = cvtfp32_fp8e4m3(src1); + __m512i result = _mm512_setzero_si512(); + result = _mm512_inserti32x4(result, lane0, 0); + result = _mm512_inserti32x4(result, lane1, 1); + return at::vec::Vectorized(result); + } +}; + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_double.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_double.h new file mode 100644 index 0000000000000000000000000000000000000000..9e6b465c52d5dcbcbbfbfc9c7ef4f063a74b503c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_double.h @@ -0,0 +1,566 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#if (defined(CPU_CAPABILITY_AVX512)) +#define SLEEF_STATIC_LIBS +#include +#endif + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized { + private: + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + + public: + // values needs to be public for compilation with clang + // as vec512.h uses it + __m512d values; + using value_type = double; + using size_type = int; + static constexpr size_type size() { + return 8; + } + Vectorized() { + values = _mm512_setzero_pd(); + } + Vectorized(__m512d v) : values(v) {} + Vectorized(double val) { + values = _mm512_set1_pd(val); + } + Vectorized( + double val1, + double val2, + double val3, + double val4, + double val5, + double val6, + double val7, + double val8) { + values = _mm512_setr_pd(val1, val2, val3, val4, val5, val6, val7, val8); + } + operator __m512d() const { + return values; + } + template + static Vectorized blend( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mask_blend_pd(mask, a.values, b.values); + } + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto all_ones = _mm512_set1_epi64(0xFFFFFFFFFFFFFFFF); + auto mmask = _mm512_cmp_epi64_mask( + _mm512_castpd_si512(mask.values), all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_pd(mmask, a.values, b.values); + } + template + static Vectorized arange( + double base = 0., + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step); + } + static Vectorized set( + const Vectorized& a, + const Vectorized& b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr, int64_t count = size()) { + if (count == size()) + return _mm512_loadu_pd(reinterpret_cast(ptr)); + + __mmask8 mask = (1ULL << count) - 1; + return _mm512_maskz_loadu_pd(mask, ptr); + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_pd(reinterpret_cast(ptr), values); + } else if (count > 0) { + __mmask8 mask = (1ULL << count) - 1; + _mm512_mask_storeu_pd(reinterpret_cast(ptr), mask, values); + } + } + const double& operator[](int idx) const = delete; + double& operator[](int idx) = delete; + int zero_mask() const { + // returns an integer mask where all zero elements are translated to 1-bit + // and others are translated to 0-bit + __mmask8 cmp = _mm512_cmp_pd_mask(values, _mm512_set1_pd(0.0), _CMP_EQ_OQ); + return static_cast(cmp); + } + Vectorized isnan() const { + auto cmp_mask = + _mm512_cmp_pd_mask(values, _mm512_set1_pd(0.0), _CMP_UNORD_Q); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + bool has_inf_nan() const { + __m512d self_sub = _mm512_sub_pd(values, values); + return (_mm512_movepi8_mask(_mm512_castpd_si512(self_sub)) & + 0x7777777777777777) != 0; + } + Vectorized map(double (*const f)(double)) const { + __at_align__ double tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = f(tmp[i]); + } + return loadu(tmp); + } + Vectorized abs() const { + auto mask = _mm512_set1_pd(-0.f); + return _mm512_andnot_pd(mask, values); + } + Vectorized angle() const { + const auto zero_vec = _mm512_castsi512_pd(zero_vector); + const auto nan_vec = _mm512_set1_pd(NAN); + const auto not_nan_mask = _mm512_cmp_pd_mask(values, values, _CMP_EQ_OQ); + const auto not_nan = + _mm512_mask_set1_epi64(zero_vector, not_nan_mask, 0xFFFFFFFFFFFFFFFF); + const auto nan_mask = + _mm512_cmp_pd_mask(_mm512_castsi512_pd(not_nan), zero_vec, _CMP_EQ_OQ); + const auto pi = _mm512_set1_pd(c10::pi); + + const auto neg_mask = _mm512_cmp_pd_mask(values, zero_vec, _CMP_LT_OQ); + auto angle = _mm512_mask_blend_pd(neg_mask, zero_vec, pi); + angle = _mm512_mask_blend_pd(nan_mask, angle, nan_vec); + return angle; + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_pd(0); + } + Vectorized conj() const { + return *this; + } + Vectorized acos() const { + return Vectorized(Sleef_acosd8_u10(values)); + } + Vectorized acosh() const { + return Vectorized(Sleef_acoshd8_u10(values)); + } + Vectorized asin() const { + return Vectorized(Sleef_asind8_u10(values)); + } + Vectorized asinh() const { + return Vectorized(Sleef_asinhd8_u10(values)); + } + Vectorized atan() const { + return Vectorized(Sleef_atand8_u10(values)); + } + Vectorized atanh() const { + return Vectorized(Sleef_atanhd8_u10(values)); + } + Vectorized atan2(const Vectorized& b) const { + return Vectorized(Sleef_atan2d8_u10(values, b)); + } + Vectorized copysign(const Vectorized& sign) const { + return Vectorized(Sleef_copysignd8(values, sign)); + } + Vectorized erf() const { + return Vectorized(Sleef_erfd8_u10(values)); + } + Vectorized erfc() const { + return Vectorized(Sleef_erfcd8_u15(values)); + } + Vectorized erfinv() const { + return map(calc_erfinv); + } + Vectorized exp() const { + return Vectorized(Sleef_expd8_u10(values)); + } + Vectorized exp2() const { + return Vectorized(Sleef_exp2d8_u10(values)); + } + Vectorized expm1() const { + return Vectorized(Sleef_expm1d8_u10(values)); + } + Vectorized exp_u20() const { + return exp(); + } + Vectorized fexp_u20() const { + return exp(); + } + Vectorized fmod(const Vectorized& q) const { + return Vectorized(Sleef_fmodd8(values, q)); + } + Vectorized hypot(const Vectorized& b) const { + return Vectorized(Sleef_hypotd8_u05(values, b)); + } + Vectorized i0() const { + return map(calc_i0); + } + Vectorized i0e() const { + return map(calc_i0e); + } + Vectorized digamma() const { + return map(calc_digamma); + } + Vectorized igamma(const Vectorized& x) const { + __at_align__ double tmp[size()]; + __at_align__ double tmp_x[size()]; + store(tmp); + x.store(tmp_x); + for (const auto i : c10::irange(size())) { + tmp[i] = calc_igamma(tmp[i], tmp_x[i]); + } + return loadu(tmp); + } + Vectorized igammac(const Vectorized& x) const { + __at_align__ double tmp[size()]; + __at_align__ double tmp_x[size()]; + store(tmp); + x.store(tmp_x); + for (const auto i : c10::irange(size())) { + tmp[i] = calc_igammac(tmp[i], tmp_x[i]); + } + return loadu(tmp); + } + Vectorized log() const { + return Vectorized(Sleef_logd8_u10(values)); + } + Vectorized log2() const { + return Vectorized(Sleef_log2d8_u10(values)); + } + Vectorized log10() const { + return Vectorized(Sleef_log10d8_u10(values)); + } + Vectorized log1p() const { + return Vectorized(Sleef_log1pd8_u10(values)); + } + Vectorized sin() const { + return Vectorized(Sleef_sind8_u10(values)); + } + Vectorized sinh() const { + return Vectorized(Sleef_sinhd8_u10(values)); + } + Vectorized cos() const { + return Vectorized(Sleef_cosd8_u10(values)); + } + Vectorized cosh() const { + return Vectorized(Sleef_coshd8_u10(values)); + } + Vectorized ceil() const { + return _mm512_ceil_pd(values); + } + Vectorized floor() const { + return _mm512_floor_pd(values); + } + Vectorized frac() const; + Vectorized neg() const { + return _mm512_xor_pd(_mm512_set1_pd(-0.), values); + } + Vectorized nextafter(const Vectorized& b) const { + return Vectorized(Sleef_nextafterd8(values, b)); + } + Vectorized round() const { + return _mm512_roundscale_pd( + values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + } + Vectorized tan() const { + return Vectorized(Sleef_tand8_u10(values)); + } + Vectorized tanh() const { + return Vectorized(Sleef_tanhd8_u10(values)); + } + Vectorized trunc() const { + return _mm512_roundscale_pd( + values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + } + Vectorized lgamma() const { + return Vectorized(Sleef_lgammad8_u10(values)); + } + Vectorized sqrt() const { + return _mm512_sqrt_pd(values); + } + Vectorized reciprocal() const { + return _mm512_div_pd(_mm512_set1_pd(1), values); + } + Vectorized rsqrt() const { + return _mm512_div_pd(_mm512_set1_pd(1), _mm512_sqrt_pd(values)); + } + Vectorized pow(const Vectorized& b) const { + return Vectorized(Sleef_powd8_u10(values, b)); + } + // Comparison using the _CMP_**_OQ predicate. + // `O`: get false if an operand is NaN + // `Q`: do not raise if an operand is NaN + Vectorized operator==(const Vectorized& other) const { + auto cmp_mask = _mm512_cmp_pd_mask(values, other.values, _CMP_EQ_OQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + + Vectorized operator!=(const Vectorized& other) const { + auto cmp_mask = _mm512_cmp_pd_mask(values, other.values, _CMP_NEQ_UQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + + Vectorized operator<(const Vectorized& other) const { + auto cmp_mask = _mm512_cmp_pd_mask(values, other.values, _CMP_LT_OQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + + Vectorized operator<=(const Vectorized& other) const { + auto cmp_mask = _mm512_cmp_pd_mask(values, other.values, _CMP_LE_OQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + + Vectorized operator>(const Vectorized& other) const { + auto cmp_mask = _mm512_cmp_pd_mask(values, other.values, _CMP_GT_OQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + + Vectorized operator>=(const Vectorized& other) const { + auto cmp_mask = _mm512_cmp_pd_mask(values, other.values, _CMP_GE_OQ); + return _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vector, cmp_mask, 0xFFFFFFFFFFFFFFFF)); + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; +}; + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_pd(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_pd(a, b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mul_pd(a, b); +} + +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return _mm512_div_pd(a, b); +} + +// frac. Implement this here so we can use subtraction. +inline Vectorized Vectorized::frac() const { + return *this - this->trunc(); +} + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + auto zero_vec = _mm512_set1_epi64(0); + Vectorized max = _mm512_max_pd(a, b); + auto isnan_mask = _mm512_cmp_pd_mask(a, b, _CMP_UNORD_Q); + auto isnan = _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vec, isnan_mask, 0xFFFFFFFFFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + return _mm512_or_pd(max, isnan); +} + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + auto zero_vec = _mm512_set1_epi64(0); + Vectorized min = _mm512_min_pd(a, b); + auto isnan_mask = _mm512_cmp_pd_mask(a, b, _CMP_UNORD_Q); + auto isnan = _mm512_castsi512_pd( + _mm512_mask_set1_epi64(zero_vec, isnan_mask, 0xFFFFFFFFFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + return _mm512_or_pd(min, isnan); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min, + const Vectorized& max) { + return _mm512_min_pd(max, _mm512_max_pd(min, a)); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min) { + return _mm512_max_pd(min, a); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max) { + return _mm512_min_pd(max, a); +} + +template <> +Vectorized inline operator&( + const Vectorized& a, + const Vectorized& b) { + return _mm512_and_pd(a, b); +} + +template <> +Vectorized inline operator|( + const Vectorized& a, + const Vectorized& b) { + return _mm512_or_pd(a, b); +} + +template <> +Vectorized inline operator^( + const Vectorized& a, + const Vectorized& b) { + return _mm512_xor_pd(a, b); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1.0); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1.0); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1.0); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0); +} + +template <> +inline void convert(const double* src, double* dst, int64_t n) { + int64_t i; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + _mm512_storeu_pd(dst + i, _mm512_loadu_pd(src + i)); + } +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = src[i]; + } +} + +template <> +Vectorized inline fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fmadd_pd(a, b, c); +} + +template <> +Vectorized inline fnmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fnmadd_pd(a, b, c); +} + +template <> +Vectorized inline fmsub( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fmsub_pd(a, b, c); +} + +template <> +Vectorized inline fnmsub( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fnmsub_pd(a, b, c); +} + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_float.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_float.h new file mode 100644 index 0000000000000000000000000000000000000000..85de300852312e7e0141c710d021eec8965b8d84 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_float.h @@ -0,0 +1,946 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#if defined(CPU_CAPABILITY_AVX512) +#define SLEEF_STATIC_LIBS +#include +#endif + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized { + private: + static constexpr __m512i zero_vec{0, 0, 0, 0, 0, 0, 0, 0}; + + public: + __m512 values; + using value_type = float; + using size_type = int; + static constexpr size_type size() { + return 16; + } + Vectorized() { + values = _mm512_setzero_ps(); + } + Vectorized(__m512 v) : values(v) {} + Vectorized(float val) { + values = _mm512_set1_ps(val); + } + Vectorized( + float val1, + float val2, + float val3, + float val4, + float val5, + float val6, + float val7, + float val8, + float val9, + float val10, + float val11, + float val12, + float val13, + float val14, + float val15, + float val16) { + values = _mm512_setr_ps( + val1, + val2, + val3, + val4, + val5, + val6, + val7, + val8, + val9, + val10, + val11, + val12, + val13, + val14, + val15, + val16); + } + Vectorized(const float (&arr)[16]) + : Vectorized( + arr[0], + arr[1], + arr[2], + arr[3], + arr[4], + arr[5], + arr[6], + arr[7], + arr[8], + arr[9], + arr[10], + arr[11], + arr[12], + arr[13], + arr[14], + arr[15]) {} + operator __m512() const { + return values; + } + template + static Vectorized blend( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mask_blend_ps(mask, a.values, b.values); + } + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + auto mmask = _mm512_cmp_epi32_mask( + _mm512_castps_si512(mask.values), all_ones, _MM_CMPINT_EQ); + return _mm512_mask_blend_ps(mmask, a.values, b.values); + } + template + static Vectorized arange( + float base = 0.f, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step); + } + static Vectorized set( + const Vectorized& a, + const Vectorized& b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + case 8: + return blend<255>(a, b); + case 9: + return blend<511>(a, b); + case 10: + return blend<1023>(a, b); + case 11: + return blend<2047>(a, b); + case 12: + return blend<4095>(a, b); + case 13: + return blend<8191>(a, b); + case 14: + return blend<16383>(a, b); + case 15: + return blend<32767>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr, int64_t count = size()) { + if (count == size()) + return _mm512_loadu_ps(reinterpret_cast(ptr)); + + __mmask16 mask = (1ULL << count) - 1; + return _mm512_maskz_loadu_ps(mask, ptr); + } + void store(void* ptr, int64_t count = size()) const { + if (count == size()) { + _mm512_storeu_ps(reinterpret_cast(ptr), values); + } else if (count > 0) { + __mmask16 mask = (1ULL << count) - 1; + _mm512_mask_storeu_ps(reinterpret_cast(ptr), mask, values); + } + } + const float& operator[](int idx) const = delete; + float& operator[](int idx) = delete; + int zero_mask() const { + // returns an integer mask where all zero elements are translated to 1-bit + // and others are translated to 0-bit + __mmask16 cmp = _mm512_cmp_ps_mask(values, _mm512_set1_ps(0.0), _CMP_EQ_OQ); + return static_cast(cmp); + } + Vectorized isnan() const { + auto mask = _mm512_cmp_ps_mask(values, _mm512_set1_ps(0.0), _CMP_UNORD_Q); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + bool has_inf_nan() const { + __m512 self_sub = _mm512_sub_ps(values, values); + return (_mm512_movepi8_mask(_mm512_castps_si512(self_sub)) & + 0x7777777777777777) != 0; + } + Vectorized map(float (*const f)(float)) const { + __at_align__ float tmp[size()]; + store(tmp); + for (const auto i : c10::irange(size())) { + tmp[i] = f(tmp[i]); + } + return loadu(tmp); + } + Vectorized abs() const { + auto mask = _mm512_set1_ps(-0.f); + return _mm512_andnot_ps(mask, values); + } + Vectorized angle() const { + __m512 zero_vec = _mm512_set1_ps(0.f); + const auto nan_vec = _mm512_set1_ps(NAN); + const auto not_nan_mask = _mm512_cmp_ps_mask(values, values, _CMP_EQ_OQ); + const auto not_nan_vec = _mm512_mask_set1_epi32( + _mm512_castps_si512(zero_vec), not_nan_mask, 0xFFFFFFFF); + const auto nan_mask = _mm512_cmp_ps_mask( + _mm512_castsi512_ps(not_nan_vec), zero_vec, _CMP_EQ_OQ); + const auto pi = _mm512_set1_ps(c10::pi); + + const auto neg_mask = _mm512_cmp_ps_mask(values, zero_vec, _CMP_LT_OQ); + auto angle = _mm512_mask_blend_ps(neg_mask, zero_vec, pi); + angle = _mm512_mask_blend_ps(nan_mask, angle, nan_vec); + return angle; + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_ps(0); + } + Vectorized conj() const { + return *this; + } + Vectorized acos() const { + return Vectorized(Sleef_acosf16_u10(values)); + } + // Sleef acoshf/sinhf/coshf overflow for large float inputs where the scalar + // C library returns finite results, because Sleef uses float-range + // intermediates internally while the scalar C library uses double precision. + Vectorized acosh() const { + return map(std::acosh); + } + Vectorized asin() const { + return Vectorized(Sleef_asinf16_u10(values)); + } + Vectorized asinh() const { + return Vectorized(Sleef_asinhf16_u10(values)); + } + Vectorized atan() const { + return Vectorized(Sleef_atanf16_u10(values)); + } + Vectorized atanh() const { + return Vectorized(Sleef_atanhf16_u10(values)); + } + Vectorized atan2(const Vectorized& b) const { + return Vectorized(Sleef_atan2f16_u10(values, b)); + } + Vectorized copysign(const Vectorized& sign) const { + return Vectorized(Sleef_copysignf16(values, sign)); + } + Vectorized erf() const { + // constants + const auto neg_zero_vec = _mm512_set1_ps(-0.f); + const auto one_vec = _mm512_set1_ps(1.0f); + const auto p = _mm512_set1_ps(0.3275911f); + const auto p1 = _mm512_set1_ps(0.254829592f); + const auto p2 = _mm512_set1_ps(-0.284496736f); + const auto p3 = _mm512_set1_ps(1.421413741f); + const auto p4 = _mm512_set1_ps(-1.453152027f); + const auto p5 = _mm512_set1_ps(1.061405429f); + // sign(x) + auto sign_mask = _mm512_and_ps(neg_zero_vec, values); + auto abs_vec = _mm512_abs_ps(values); + // t = 1 / (p * abs(x) + 1) + auto tmp0 = _mm512_fmadd_ps(p, abs_vec, one_vec); + auto t = _mm512_div_ps(one_vec, tmp0); + // r = p5 * t ^ 4 + p4 * t ^ 3 + p3 * t ^ 2 + p2 * t + p1 + auto tmp1 = _mm512_fmadd_ps(p5, t, p4); + auto tmp2 = _mm512_fmadd_ps(tmp1, t, p3); + auto tmp3 = _mm512_fmadd_ps(tmp2, t, p2); + auto r = _mm512_fmadd_ps(tmp3, t, p1); + // - exp(- x * x) + auto pow_2 = _mm512_mul_ps(values, values); + auto neg_pow_2 = _mm512_xor_ps(neg_zero_vec, pow_2); + // auto tmp4 = exp(neg_pow_2); + auto tmp4 = Vectorized(Sleef_expf16_u10(neg_pow_2)); + auto tmp5 = _mm512_xor_ps(neg_zero_vec, tmp4); + // erf(x) = sign(x) * (1 - r * t * exp(- x * x)) + auto tmp6 = _mm512_mul_ps(tmp5, t); + auto tmp7 = _mm512_fmadd_ps(tmp6, r, one_vec); + return _mm512_xor_ps(sign_mask, tmp7); + } + Vectorized erfc() const { + return Vectorized(Sleef_erfcf16_u15(values)); + } + Vectorized erfinv() const { + return map(calc_erfinv); + } + Vectorized exp() const { + return Vectorized(Sleef_expf16_u10(values)); + } + Vectorized exp2() const { + return Vectorized(Sleef_exp2f16_u10(values)); + } + Vectorized expm1() const { + return Vectorized(Sleef_expm1f16_u10(values)); + } + Vectorized fexp_u20() const { + const __m512 vec_c0 = _mm512_set1_ps(0.00010703434948458272f); + const __m512 vec_c1 = _mm512_set1_ps(0.30354260500649682f); + const __m512 vec_c2 = _mm512_set1_ps(-0.22433836478672356); + const __m512 vec_c3 = _mm512_set1_ps(-0.079204240219773236); + + const __m512 vec_exp_log2ef = + _mm512_castsi512_ps(_mm512_set1_epi32(0x3fb8aa3b)); // log2(e) + + const __m512 vec_a = _mm512_set1_ps(std::pow(2, 23) / std::log2(2)); + const __m512 vec_b = _mm512_set1_ps(std::pow(2, 23) * 127.f); + + const __m512 vec_ln_flt_min = + _mm512_castsi512_ps(_mm512_set1_epi32(0xc2aeac50)); + const __m512 vec_ln_flt_max = + _mm512_castsi512_ps(_mm512_set1_epi32(0x42b17218)); + __m512i vec_infinity = _mm512_set1_epi32(0x7F800000); + __m512i vec_zero = _mm512_setzero_epi32(); + + // Fast Exponential Computation on SIMD Architectures + // A. Cristiano I. Malossi, Yves Ineichen, Costas Bekas, and Alessandro + // Curioni exp(x) = 2**(x * log2(e)) + // = 2**xi * 2**xf - TIPS we are using the EEEE floating point + // representation with identification to the exponent and the + // mentissa + // 2**xf will be approximated to a polynomial of degree 3 computed with + // Horner method + // mask for the boundary condition + auto min_mask = _mm512_cmp_ps_mask(values, vec_ln_flt_min, _CMP_LT_OS); + auto max_mask = _mm512_cmp_ps_mask(values, vec_ln_flt_max, _CMP_GT_OS); + + // transformation with log2(e) + auto vec_src = _mm512_mul_ps(values, vec_exp_log2ef); + auto vec_fractional = _mm512_sub_ps(vec_src, _mm512_floor_ps(vec_src)); + + // compute polynomial using Horner Scheme, for superscalar processor + auto vec_res = _mm512_fmadd_ps(vec_fractional, vec_c3, vec_c2); + vec_res = _mm512_fmadd_ps(vec_fractional, vec_res, vec_c1); + vec_res = _mm512_fmadd_ps(vec_fractional, vec_res, vec_c0); + + vec_src = _mm512_sub_ps(vec_src, vec_res); + // the tips is here, headache in perspective + auto tmp = _mm512_fmadd_ps(vec_a, vec_src, vec_b); + // headache bis - we loose precision with the cast but it "fits", but ok + // after f32 -> f16 later + __m512i casted_integer = _mm512_cvttps_epi32(tmp); + // boundary condition, lower than the min -> 0 + casted_integer = _mm512_mask_mov_epi32(casted_integer, min_mask, vec_zero); + // boundary condition, larger than the max -> +oo + casted_integer = + _mm512_mask_mov_epi32(casted_integer, max_mask, vec_infinity); + // final interpretation to float + return _mm512_castsi512_ps(casted_integer); + } + Vectorized exp_u20() const { + // A faster version of exp with ULP=20 + const __m512 vec_factorial_1 = + _mm512_set1_ps(0.999999701f); // 1/factorial(1) + const __m512 vec_factorial_2 = + _mm512_set1_ps(0.499991506f); // 1/factorial(2) + const __m512 vec_factorial_3 = + _mm512_set1_ps(0.166676521f); // 1/factorial(3) + const __m512 vec_factorial_4 = + _mm512_set1_ps(0.0418978221f); // 1/factorial(4) + const __m512 vec_factorial_5 = + _mm512_set1_ps(0.00828929059f); // 1/factorial(5) + const __m512 vec_exp_log2ef = + _mm512_castsi512_ps(_mm512_set1_epi32(0x3fb8aa3b)); // log2(e) + const __m512 vec_half = _mm512_set1_ps(0.5f); + const __m512 vec_one = _mm512_set1_ps(1.f); + const __m512 vec_zero = _mm512_set1_ps(0.f); + const __m512 vec_two = _mm512_set1_ps(2.f); + const __m512 vec_ln2f = + _mm512_castsi512_ps(_mm512_set1_epi32(0x3f317218)); // ln(2) + const __m512 vec_ln_flt_min = + _mm512_castsi512_ps(_mm512_set1_epi32(0xc2aeac50)); + const __m512 vec_ln_flt_max = + _mm512_castsi512_ps(_mm512_set1_epi32(0x42b17218)); + const __m512i vec_127 = _mm512_set1_epi32(0x0000007f); + const int n_mantissa_bits = 23; + + // exp(x) = + // = exp(n * ln(2) + r) // divide x by ln(2) and get quot and rem + // = 2^n * exp(r) // simplify the exp(n*ln(2)) expression + + auto less_ln_flt_min_mask = + _mm512_cmp_ps_mask(values, vec_ln_flt_min, 1 /*_CMP_LT_OS*/); + auto vec_src = _mm512_min_ps(values, vec_ln_flt_max); + vec_src = _mm512_max_ps(vec_src, vec_ln_flt_min); + + // fx = floorf(x * log2ef + 0.5) + auto vec_fx = _mm512_fmadd_ps(vec_src, vec_exp_log2ef, vec_half); + auto vec_fx_i = _mm512_cvt_roundps_epi32( + vec_fx, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC); + vec_fx = _mm512_cvtepi32_ps(vec_fx_i); + + // x = x - fx * ln2 + auto vec_exp_poly = _mm512_fnmadd_ps(vec_fx, vec_ln2f, vec_src); + + // compute polynomial + auto vec_res = + _mm512_fmadd_ps(vec_exp_poly, vec_factorial_5, vec_factorial_4); + vec_res = _mm512_fmadd_ps(vec_exp_poly, vec_res, vec_factorial_3); + vec_res = _mm512_fmadd_ps(vec_exp_poly, vec_res, vec_factorial_2); + vec_res = _mm512_fmadd_ps(vec_exp_poly, vec_res, vec_factorial_1); + vec_res = _mm512_fmadd_ps(vec_exp_poly, vec_res, vec_one); + + // compute 2^(n-1) + auto vec_exp_number = _mm512_sub_ps(vec_fx, vec_one); + auto vec_exp_number_i = _mm512_cvtps_epi32(vec_exp_number); + auto vec_two_pow_n_i = _mm512_add_epi32(vec_exp_number_i, vec_127); + vec_two_pow_n_i = _mm512_slli_epi32(vec_two_pow_n_i, n_mantissa_bits); + auto vec_two_pow_n = _mm512_castsi512_ps(vec_two_pow_n_i); + vec_two_pow_n = + _mm512_mask_blend_ps(less_ln_flt_min_mask, vec_two_pow_n, vec_zero); + + // y = y * 2^n + vec_res = _mm512_mul_ps(vec_res, vec_two_pow_n); + vec_res = _mm512_mul_ps(vec_res, vec_two); + return vec_res; + } + Vectorized fmod(const Vectorized& q) const { + return Vectorized(Sleef_fmodf16(values, q)); + } + Vectorized log() const { + return Vectorized(Sleef_logf16_u10(values)); + } + Vectorized log2() const { + return Vectorized(Sleef_log2f16_u10(values)); + } + Vectorized log10() const { + return Vectorized(Sleef_log10f16_u10(values)); + } + Vectorized log1p() const { + return Vectorized(Sleef_log1pf16_u10(values)); + } + Vectorized frac() const; + Vectorized sin() const { + return Vectorized(Sleef_sinf16_u35(values)); + } + // Sleef sinhf/coshf overflow for large float inputs where std::sinh/cosh + // return finite results, because Sleef uses float-range intermediates + // internally while the scalar C library uses double precision. + Vectorized sinh() const { + return map(std::sinh); + } + Vectorized cos() const { + return Vectorized(Sleef_cosf16_u35(values)); + } + Vectorized cosh() const { + return map(std::cosh); + } + Vectorized ceil() const { + return _mm512_ceil_ps(values); + } + Vectorized floor() const { + return _mm512_floor_ps(values); + } + Vectorized hypot(const Vectorized& b) const { + return Vectorized(Sleef_hypotf16_u05(values, b)); + } + Vectorized i0() const { + return map(calc_i0); + } + Vectorized i0e() const { + return map(calc_i0e); + } + Vectorized digamma() const { + return map(calc_digamma); + } + Vectorized igamma(const Vectorized& x) const { + __at_align__ float tmp[size()]; + __at_align__ float tmp_x[size()]; + store(tmp); + x.store(tmp_x); + for (const auto i : c10::irange(size())) { + tmp[i] = calc_igamma(tmp[i], tmp_x[i]); + } + return loadu(tmp); + } + Vectorized igammac(const Vectorized& x) const { + __at_align__ float tmp[size()]; + __at_align__ float tmp_x[size()]; + store(tmp); + x.store(tmp_x); + for (const auto i : c10::irange(size())) { + tmp[i] = calc_igammac(tmp[i], tmp_x[i]); + } + return loadu(tmp); + } + Vectorized neg() const { + return _mm512_xor_ps(_mm512_set1_ps(-0.f), values); + } + Vectorized nextafter(const Vectorized& b) const { + return Vectorized(Sleef_nextafterf16(values, b)); + } + Vectorized round() const { + return _mm512_roundscale_ps( + values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + } + Vectorized tan() const { + return Vectorized(Sleef_tanf16_u10(values)); + } + Vectorized tanh() const { + return Vectorized(Sleef_tanhf16_u10(values)); + } + Vectorized trunc() const { + return _mm512_roundscale_ps( + values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC)); + } + Vectorized lgamma() const { + return Vectorized(Sleef_lgammaf16_u10(values)); + } + Vectorized sqrt() const { + return _mm512_sqrt_ps(values); + } + Vectorized reciprocal() const { + return _mm512_div_ps(_mm512_set1_ps(1), values); + } + Vectorized rsqrt() const { + return _mm512_div_ps(_mm512_set1_ps(1), _mm512_sqrt_ps(values)); + } + Vectorized pow(const Vectorized& b) const { + return Vectorized(Sleef_powf16_u10(values, b)); + } + float reduce_add() const { + return _mm512_reduce_add_ps(values); + } + float reduce_max() const { + return _mm512_reduce_max_ps(values); + } + // Comparison using the _CMP_**_OQ predicate. + // `O`: get false if an operand is NaN + // `Q`: do not raise if an operand is NaN + Vectorized operator==(const Vectorized& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_EQ_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + + Vectorized operator!=(const Vectorized& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_NEQ_UQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + + Vectorized operator<(const Vectorized& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_LT_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + + Vectorized operator<=(const Vectorized& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_LE_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + + Vectorized operator>(const Vectorized& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_GT_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + + Vectorized operator>=(const Vectorized& other) const { + auto mask = _mm512_cmp_ps_mask(values, other.values, _CMP_GE_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, mask, 0xFFFFFFFF)); + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_ps(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_ps(a, b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mul_ps(a, b); +} + +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return _mm512_div_ps(a, b); +} + +// frac. Implement this here so we can use subtraction +inline Vectorized Vectorized::frac() const { + return *this - this->trunc(); +} + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + auto zero_vec = _mm512_set1_epi32(0); + auto max = _mm512_max_ps(a, b); + auto isnan_mask = _mm512_cmp_ps_mask(a, b, _CMP_UNORD_Q); + auto isnan = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, isnan_mask, 0xFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + return _mm512_or_ps(max, isnan); +} + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + auto zero_vec = _mm512_set1_epi32(0); + auto min = _mm512_min_ps(a, b); + auto isnan_mask = _mm512_cmp_ps_mask(a, b, _CMP_UNORD_Q); + auto isnan = _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, isnan_mask, 0xFFFFFFFF)); + // Exploit the fact that all-ones is a NaN. + return _mm512_or_ps(min, isnan); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min, + const Vectorized& max) { + return _mm512_min_ps(max, _mm512_max_ps(min, a)); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max) { + return _mm512_min_ps(max, a); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min) { + return _mm512_max_ps(min, a); +} + +template <> +Vectorized inline operator&( + const Vectorized& a, + const Vectorized& b) { + return _mm512_and_ps(a, b); +} + +template <> +Vectorized inline operator|( + const Vectorized& a, + const Vectorized& b) { + return _mm512_or_ps(a, b); +} + +template <> +Vectorized inline operator^( + const Vectorized& a, + const Vectorized& b) { + return _mm512_xor_ps(a, b); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +template <> +inline void convert(const float* src, float* dst, int64_t n) { + int64_t i; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + _mm512_storeu_ps(dst + i, _mm512_loadu_ps(src + i)); + } +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = src[i]; + } +} + +template <> +Vectorized inline fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fmadd_ps(a, b, c); +} + +template <> +Vectorized inline fnmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fnmadd_ps(a, b, c); +} + +template <> +Vectorized inline fmsub( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fmsub_ps(a, b, c); +} + +template <> +Vectorized inline fnmsub( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return _mm512_fnmsub_ps(a, b, c); +} + +// TODO: rewrite with ATEN vectorized (need to add unpack and shuffle) +// Used by Inductor CPP codegen for micro gemm +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#L230-L304 +// kernel for transposing mxn where m, n <= 16 +// (M + 1) / 2 * 2 + (M + 3) / 4 * 4 + (M + 7) / 8 * 8 + N instructions +inline void transpose_block( + at::vec::VectorizedN& input, + int M = 16, + int N = 16) { + TORCH_CHECK(M <= 16 && N <= 16, "transpose_block expects M, N <= 16."); + // unpacking and interleaving 32-bit elements + __m512 temp[16]; + int i; + for (i = 0; i < (M + 1) / 2; ++i) { + temp[2 * i] = _mm512_unpacklo_ps(input[2 * i], input[2 * i + 1]); + temp[2 * i + 1] = _mm512_unpackhi_ps(input[2 * i], input[2 * i + 1]); + } + for (i = i * 2; i < 16; ++i) { + temp[i] = _mm512_setzero_ps(); + } + + // unpacking and interleaving 64-bit elements + for (i = 0; i < (M + 3) / 4; ++i) { + input[4 * i] = _mm512_castpd_ps(_mm512_unpacklo_pd( + _mm512_castps_pd(temp[4 * i]), _mm512_castps_pd(temp[4 * i + 2]))); + input[4 * i + 1] = _mm512_castpd_ps(_mm512_unpackhi_pd( + _mm512_castps_pd(temp[4 * i]), _mm512_castps_pd(temp[4 * i + 2]))); + input[4 * i + 2] = _mm512_castpd_ps(_mm512_unpacklo_pd( + _mm512_castps_pd(temp[4 * i + 1]), _mm512_castps_pd(temp[4 * i + 3]))); + input[4 * i + 3] = _mm512_castpd_ps(_mm512_unpackhi_pd( + _mm512_castps_pd(temp[4 * i + 1]), _mm512_castps_pd(temp[4 * i + 3]))); + } + + // shuffle 128-bits (composed of 4 32-bit elements) + for (i = 0; i < (M + 7) / 8; ++i) { + temp[8 * i] = _mm512_shuffle_f32x4(input[8 * i], input[8 * i + 4], 0x88); + temp[8 * i + 1] = + _mm512_shuffle_f32x4(input[8 * i + 1], input[8 * i + 5], 0x88); + temp[8 * i + 2] = + _mm512_shuffle_f32x4(input[8 * i + 2], input[8 * i + 6], 0x88); + temp[8 * i + 3] = + _mm512_shuffle_f32x4(input[8 * i + 3], input[8 * i + 7], 0x88); + temp[8 * i + 4] = + _mm512_shuffle_f32x4(input[8 * i], input[8 * i + 4], 0xdd); + temp[8 * i + 5] = + _mm512_shuffle_f32x4(input[8 * i + 1], input[8 * i + 5], 0xdd); + temp[8 * i + 6] = + _mm512_shuffle_f32x4(input[8 * i + 2], input[8 * i + 6], 0xdd); + temp[8 * i + 7] = + _mm512_shuffle_f32x4(input[8 * i + 3], input[8 * i + 7], 0xdd); + } + + for (i = 0; i < N; ++i) { + if (i < 8) { + input[i] = _mm512_shuffle_f32x4(temp[i], temp[8 + i], 0x88); + } else { + input[i] = _mm512_shuffle_f32x4(temp[i - 8], temp[i], 0xdd); + } + } +} + +// TODO(jgong5): rewrite with ATEN vectorized (need to add unpack and shuffle) +// Used by Inductor CPP codegen +// Code referred to FBGEMM: +// https://github.com/pytorch/FBGEMM/blob/39a423e4ad1a04b77fea81c7d09c3e6f8984fae9/src/UtilsAvx512.cc#L230-L304 +// kernel for transposing mxn where m, n <= 16 +// M + (M + 1) / 2 * 2 + (M + 3) / 4 * 4 + (M + 7) / 8 * 8 + 2 * N instructions +inline void transpose_mxn_16x16( + const float* src, + int64_t ld_src, + float* dst, + int64_t ld_dst, + int M, + int N) { + TORCH_CHECK(M <= 16 && N <= 16, "transpose_mxn expects M, N <= 16."); + // load from src to registers + at::vec::VectorizedN input; + int i; + if (N == 16) { + for (i = 0; i < M; ++i) { + input[i] = _mm512_loadu_ps(&src[i * ld_src]); + } + } else { + __mmask16 src_mask = (1 << N) - 1; + for (i = 0; i < M; ++i) { + input[i] = _mm512_maskz_loadu_ps(src_mask, &src[i * ld_src]); + } + } + for (; i < 16; ++i) { + // Not really needed but to avoid uninitialized variable warning. + // Shouldn't be much overhead because xor can be executed in parallel with + // other instructions. + input[i] = _mm512_setzero_ps(); + } + + transpose_block(input, M, N); + + // store from registers to dst + if (M == 16) { + for (i = 0; i < N; ++i) { + _mm512_storeu_ps(&dst[i * ld_dst], input[i]); + } + } else { + __mmask16 dst_mask = (1 << M) - 1; + for (i = 0; i < N; ++i) { + _mm512_mask_storeu_ps(&dst[i * ld_dst], dst_mask, input[i]); + } + } +} + +template <> +inline void transpose_mxn( + const float* src, + int64_t ld_src, + float* dst, + int64_t ld_dst, + int M, + int N) { + int64_t i = 0; + for (; i < M / 16 * 16; i += 16) { + int64_t j = 0; + for (; j < N / 16 * 16; j += 16) { + transpose_mxn_16x16( + src + i * ld_src + j, ld_src, dst + j * ld_dst + i, ld_dst, 16, 16); + } + // handle remainder j + int nrem = N - j; + if (nrem > 0) { + transpose_mxn_16x16( + src + i * ld_src + j, ld_src, dst + j * ld_dst + i, ld_dst, 16, nrem); + } + } + // handle remainder i + int mrem = M - i; + if (mrem > 0) { + int j = 0; + for (; j < N / 16 * 16; j += 16) { + transpose_mxn_16x16( + src + i * ld_src + j, ld_src, dst + j * ld_dst + i, ld_dst, mrem, 16); + } + // handle remainder j + int nrem = N - j; + transpose_mxn_16x16( + src + i * ld_src + j, ld_src, dst + j * ld_dst + i, ld_dst, mrem, nrem); + } +} + +template < + typename T, + int M, + int N, + typename std::enable_if_t, int> = 0> +inline void transpose_mxn( + const float* src, + int64_t ld_src, + float* dst, + int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_float8.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_float8.h new file mode 100644 index 0000000000000000000000000000000000000000..071dd36201ada25535d8537c21c34a257b051870 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_float8.h @@ -0,0 +1,694 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#if (defined(CPU_CAPABILITY_AVX512)) +#define SLEEF_STATIC_LIBS +#include +#endif + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + +static inline void cvtfp8e4m3_fp32(const __m128i& a, __m512& o) { +#ifdef __AVX10_2__ + // It takes effect only with compatible compiler and hardware in Inductor CPP + // backend. No effect on eager mode. + __m256h f16_vec = _mm256_cvthf8_ph(a); + o = _mm512_cvtph_ps(_mm256_castph_si256(f16_vec)); +#else + // Zero Extend + __m512i x = _mm512_cvtepu8_epi32(a); + __m512i val = _mm512_and_epi32( + _mm512_slli_epi32(x, 24), _mm512_set1_epi32(0x7FFFFFFF)); // nonsign_val + __m512i mant = + _mm512_and_si512(x, _mm512_set1_epi32(0x07)); // mantissa = x & 0x07 + __m512i exp = _mm512_and_si512( + _mm512_srli_epi32(x, 3), + _mm512_set1_epi32(0x0F)); // exp = (x >> 3) & 0x0F + __m512i sign = + _mm512_and_si512(x, _mm512_set1_epi32(0x80)); // sign = x & 0x80 + __m512i _zeros = _mm512_setzero_si512(); + + // --- Step 1: Calculate the renorm_shift + __m512i renorm_shift = _zeros; + // Denorm case (exp == 0 && mant != 0) --- + __mmask16 denormal_mask = _mm512_cmpeq_epi32_mask(exp, _zeros) & + _mm512_cmpneq_epi32_mask(mant, _zeros); + if (denormal_mask) { + // An alternative solution is as what scalar did in + // pytorch/c10/util/Float8_e4m3fn.h To count the num of leading zeros, since + // here we know the unsigned denorm value has zero sign and exp which is 5 + // leading zeros, we need to count the leading zero of mant (3bit) which may + // done through table lookup for example: const uint8_t lz_table[8] = {3, 2, + // 1, 1, 0, 0, 0, 0}; num_leading_zero = lz_table[mant] + 5; + + __m512i _ones = _mm512_set1_epi32(1); + __m512i _twos = _mm512_set1_epi32(2); + __m512i _threes = _mm512_set1_epi32(3); + + // Default leading zero number for denorm value is 1 = 5 - 4 + __m512i denorm_renorm_shift = _ones; + // For mant 001, leading zero number is 3 = 7 -4 + __mmask16 leading_Zero_mask = _mm512_cmpeq_epi32_mask(mant, _ones); + denorm_renorm_shift = + _mm512_mask_mov_epi32(denorm_renorm_shift, leading_Zero_mask, _threes); + // For mant 010 and 011, leading zero number is 2 = 6 -4 + leading_Zero_mask = _mm512_cmpeq_epi32_mask(mant, _twos); + denorm_renorm_shift = + _mm512_mask_mov_epi32(denorm_renorm_shift, leading_Zero_mask, _twos); + leading_Zero_mask = _mm512_cmpeq_epi32_mask(mant, _threes); + denorm_renorm_shift = + _mm512_mask_mov_epi32(denorm_renorm_shift, leading_Zero_mask, _twos); + + renorm_shift = + _mm512_mask_mov_epi32(renorm_shift, denormal_mask, denorm_renorm_shift); + } + + // --- Step 2: calculate norm and denorm --- + __m512i norm_shifted = + _mm512_srli_epi32(_mm512_sllv_epi32(val, renorm_shift), 4); + // exponent bias adjustment: (0x78 - renorm_shift) << 23 + __m512i exp_bias = _mm512_slli_epi32( + _mm512_sub_epi32(_mm512_set1_epi32(0x78), renorm_shift), 23); + val = _mm512_add_epi32(norm_shifted, exp_bias); + + // --- Step 3: Nan case (exp == 0xF && mant == 0x07) --- + __mmask16 nan_mask = _mm512_cmpeq_epi32_mask(exp, _mm512_set1_epi32(0xF)) & + _mm512_cmpeq_epi32_mask(mant, _mm512_set1_epi32(0x07)); + if (nan_mask) { + const __m512i nan_values = _mm512_set1_epi32(0x7FC00000); + val = _mm512_mask_mov_epi32(val, nan_mask, nan_values); + } + + // --- Step 4: Zero case (exp == 0x00 && mant == 0x00) --- + __mmask16 zero_mask = _mm512_cmpeq_epi32_mask(exp, _zeros) & + _mm512_cmpeq_epi32_mask(mant, _zeros); + if (zero_mask) { + val = _mm512_mask_mov_epi32(val, zero_mask, _zeros); + } + + // --- Step 5: OR with sign (sign bit << 24 to get to bit 31) --- + val = _mm512_or_si512(val, _mm512_slli_epi32(sign, 24)); + + o = _mm512_castsi512_ps(val); +#endif +} + +static inline __m128i cvtfp32_fp8e4m3(const __m512& src) { +#ifdef __AVX10_2__ + // It takes effect only with compatible compiler and hardware in Inductor CPP + // backend. No effect on eager mode. + __m256i f16_vec = + _mm512_cvt_roundps_ph(src, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); + return _mm256_cvtph_hf8(_mm256_castsi256_ph(f16_vec)); +#else + // cvt 16x32 from fp32 to fp8 e4m3 + const __m512i sign_mask = _mm512_set1_epi32(0x80000000); + const __m512i fp8_max = _mm512_set1_epi32(UINT32_C(1087) << 20); + const __m512i denorm_thresh = _mm512_set1_epi32(UINT32_C(121) << 23); + const __m512i denorm_mask = _mm512_set1_epi32(UINT32_C(141) << 23); + const __m512i bias_part1 = _mm512_set1_epi32((uint32_t)(7 - 127) << 23); + const __m512i rounding_bias = _mm512_set1_epi32(0x7FFFF); + __m512i f_bits = _mm512_castps_si512(src); + // Extract and save sign + __m512i sign = _mm512_and_epi32(f_bits, sign_mask); + f_bits = _mm512_xor_epi32(f_bits, sign); + + // Prepare result containers + __m512i result = _mm512_setzero_si512(); + + // Step 1: Handle case of overflow + // NaN (f_bits > fp32_inf): set result = 0x7f + // Finite overflow or inf (fp8_max <= f_bits <= fp32_inf): saturate to 0x7e + const __m512i fp32_inf = _mm512_set1_epi32(UINT32_C(0x7F800000)); + __mmask16 overflow_mask = _mm512_cmpge_epu32_mask(f_bits, fp8_max); + if (overflow_mask) { + __mmask16 nan_mask = _mm512_cmpgt_epu32_mask(f_bits, fp32_inf); + __mmask16 sat_mask = overflow_mask & ~nan_mask; + result = _mm512_mask_set1_epi32(result, nan_mask, 0x7f); + result = _mm512_mask_set1_epi32(result, sat_mask, 0x7e); + } + + // Step 2: Handle small numbers (denormals) + // Small numbers (f_bits < denorm_thresh) + __mmask16 denorm_thresh_mask = _mm512_cmplt_epu32_mask(f_bits, denorm_thresh); + + if (denorm_thresh_mask) { + __m512 small_input = _mm512_castsi512_ps(f_bits); + __m512 small_denorm = + _mm512_add_ps(small_input, _mm512_castsi512_ps(denorm_mask)); + __m512i small_denorm_bits = _mm512_castps_si512(small_denorm); + __m512i small_result = _mm512_sub_epi32(small_denorm_bits, denorm_mask); + result = _mm512_mask_mov_epi32(result, denorm_thresh_mask, small_result); + } + + // Step 3: Handle normal numbers + __mmask16 normal_mask = ~(overflow_mask | denorm_thresh_mask); + + if (normal_mask) { + // mant_odd = (f_bits >> 20) & 1 + __m512i mant_odd = + _mm512_and_epi32(_mm512_srli_epi32(f_bits, 20), _mm512_set1_epi32(1)); + // f_bits += bias_part1 + rounding_bias + __m512i rounded = _mm512_add_epi32(f_bits, bias_part1); + rounded = _mm512_add_epi32(rounded, rounding_bias); + // Add mant_odd + rounded = _mm512_add_epi32(rounded, mant_odd); + // Shift right by 20 bits + __m512i normal_result = _mm512_srli_epi32(rounded, 20); + // Rounding may carry into the NaN bit pattern (0x7f); saturate to max + __mmask16 round_overflow = + _mm512_cmpeq_epi32_mask(normal_result, _mm512_set1_epi32(0x7f)); + normal_result = _mm512_mask_set1_epi32(normal_result, round_overflow, 0x7e); + result = _mm512_mask_mov_epi32(result, normal_mask, normal_result); + } + + // Merge back the sign + __m512i sign_shifted = _mm512_srli_epi32(sign, 24); + result = _mm512_or_epi32(result, sign_shifted); + + // Now result is 16 x 32-bit integers, but we only need 8-bit for each + __m512i packed = _mm512_and_si512(result, _mm512_set1_epi32(0xFF)); + + // Narrow 32-bit integers to 8-bit + return _mm512_cvtepi32_epi8(packed); +#endif +} + +static inline float fp8e4m3_to_fp32_scalar(uint8_t val) { + __m512i v = _mm512_set1_epi8(val); + __m128i v_128 = _mm512_castsi512_si128(v); + __m512 o; + cvtfp8e4m3_fp32(v_128, o); + return _mm512_cvtss_f32(o); +} + +static inline uint8_t fp32_to_fp8e4m3_scalar(float val) { + __m512 v = _mm512_set1_ps(val); + __m128i o = cvtfp32_fp8e4m3(v); + return static_cast(_mm_cvtsi128_si32(o)); +} + +static inline void cvtfp8e5m2_fp32(const __m128i& a, __m512& o) { + __m256i a_256 = _mm256_castsi128_si256(a); + __m512i a_512 = _mm512_cvtepu8_epi16(a_256); + a_512 = _mm512_slli_epi16(a_512, 8); + a_256 = _mm512_castsi512_si256(a_512); + cvtfp16_fp32(a_256, o); +} + +static inline __m128i cvtfp32_fp8e5m2(const __m512& src) { + constexpr uint32_t fp32_inf = UINT32_C(255) << 23; + constexpr uint32_t fp8_max = UINT32_C(143) << 23; + constexpr uint32_t denorm_mask = UINT32_C(134) << 23; + + // Cvt to bits + __m512i input_bits = _mm512_castps_si512(src); + __m512i result = _mm512_setzero_si512(); + + // Get the sign + __m512i sign = _mm512_and_si512(input_bits, _mm512_set1_epi32(0x80000000)); + + // Get the unsigned input + input_bits = _mm512_xor_si512(input_bits, sign); + + // Calculate the mask for inf, nan and denorm + __mmask16 greater_than_fp8_max = + _mm512_cmpge_epi32_mask(input_bits, _mm512_set1_epi32(fp8_max)); + __mmask16 greater_than_fp32_inf = + _mm512_cmpgt_epi32_mask(input_bits, _mm512_set1_epi32(fp32_inf)); + __mmask16 less_than_normal = _mm512_cmpgt_epi32_mask( + _mm512_set1_epi32((UINT32_C(113) << 23)), input_bits); + __m512i temp_bits_for_denorm = _mm512_setzero_si512(); + if (less_than_normal) { + __m512i denorm_mask_512i = _mm512_set1_epi32(denorm_mask); + temp_bits_for_denorm = _mm512_castps_si512(_mm512_add_ps( + _mm512_castsi512_ps(input_bits), + _mm512_castsi512_ps(denorm_mask_512i))); + temp_bits_for_denorm = + _mm512_sub_epi32(temp_bits_for_denorm, denorm_mask_512i); + } + + // Step 1: Norm Val + __m512i mant_odd_mask = + _mm512_and_epi32(_mm512_srli_epi32(input_bits, 21), _mm512_set1_epi32(1)); + input_bits = _mm512_add_epi32( + input_bits, _mm512_set1_epi32(((uint32_t)(15 - 127) << 23) + 0xFFFFF)); + input_bits = _mm512_add_epi32(input_bits, mant_odd_mask); + result = _mm512_srli_epi32(input_bits, 21); + + // Step 2: INF and NAN + if (greater_than_fp8_max) { + result = _mm512_mask_mov_epi32( + result, greater_than_fp8_max, _mm512_set1_epi8(0x7C)); + if (greater_than_fp32_inf) { + result = _mm512_mask_mov_epi32( + result, greater_than_fp32_inf, _mm512_set1_epi8(0x7F)); + } + } + + // Step 3: Denorm val + if (less_than_normal) { + result = + _mm512_mask_mov_epi32(result, less_than_normal, temp_bits_for_denorm); + } + + // Step 4: restore sign + result = _mm512_or_si512(result, _mm512_srli_epi32(sign, 24)); + + return _mm512_cvtepi32_epi8(result); +} + +static inline float fp8e5m2_to_fp32_scalar(uint8_t val) { + __m512i v = _mm512_set1_epi8(val); + __m128i v_128 = _mm512_castsi512_si128(v); + __m512 o; + cvtfp8e5m2_fp32(v_128, o); + return _mm512_cvtss_f32(o); +} + +static inline uint8_t fp32_to_fp8e5m2_scalar(float val) { + __m512 v = _mm512_set1_ps(val); + __m128i o = cvtfp32_fp8e5m2(v); + return static_cast(_mm_cvtsi128_si32(o)); +} + +template +class Vectorizedf8 { + static_assert( + std::integral_constant < bool, + std::is_same_v || std::is_same_v < T, + at::Float8_e5m2 >> ::value, + "Support only float8 e4m3."); + + private: + __m512i values; + template + Vectorized inline binary_compare(const VectorizedType& b, Op op) const { + __m512 a0, a1, a2, a3; + __m512 b0, b1, b2, b3; + __m512 o0, o1, o2, o3; + if constexpr (std::is_same_v) { + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(values, 0), a0); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b.values, 0), b0); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(values, 1), a1); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b.values, 1), b1); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(values, 2), a2); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b.values, 2), b2); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(values, 3), a3); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b.values, 3), b3); + } else { + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(values, 0), a0); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b.values, 0), b0); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(values, 1), a1); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b.values, 1), b1); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(values, 2), a2); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b.values, 2), b2); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(values, 3), a3); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b.values, 3), b3); + } + + o0 = op(a0, b0); + o1 = op(a1, b1); + o2 = op(a2, b2); + o3 = op(a3, b3); + __m128i o128_0, o128_1, o128_2, o128_3; + if constexpr (std::is_same_v) { + o128_0 = cvtfp32_fp8e4m3(o0); + o128_1 = cvtfp32_fp8e4m3(o1); + o128_2 = cvtfp32_fp8e4m3(o2); + o128_3 = cvtfp32_fp8e4m3(o3); + } else { + o128_0 = cvtfp32_fp8e5m2(o0); + o128_1 = cvtfp32_fp8e5m2(o1); + o128_2 = cvtfp32_fp8e5m2(o2); + o128_3 = cvtfp32_fp8e5m2(o3); + } + + __m512i result = _mm512_setzero_si512(); + result = _mm512_inserti32x4(result, o128_0, 0); + result = _mm512_inserti32x4(result, o128_1, 1); + result = _mm512_inserti32x4(result, o128_2, 2); + result = _mm512_inserti32x4(result, o128_3, 3); + + return result; + } + + public: + using value_type = uint8_t; + using size_type = int; + static constexpr size_type size() { + return 64; + } + Vectorizedf8() = default; + Vectorizedf8(__m512i v) : values(v) {} + Vectorizedf8(T val) { + value_type uw = val.x; + values = _mm512_set1_epi8(uw); + } + operator __m512i() const { + return values; + } + T& operator[](int idx) = delete; + const T& operator[](int idx) const = delete; + static Vectorized loadu(const void* ptr, int16_t count = size()) { + if (count == size()) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } else if (count == 16) { + // Fast path if only load element number of 16 + __m128i input_128 = + _mm_loadu_si128(reinterpret_cast(ptr)); + return _mm512_castsi128_si512(input_128); + } else { + __mmask64 mask = (1ULL << count) - 1; + return _mm512_maskz_loadu_epi8(mask, ptr); + } + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + if (count == 16) { + // Fast path if only store element number of 16 + _mm_storeu_si128( + reinterpret_cast<__m128i*>(ptr), _mm512_castsi512_si128(values)); + } else { + __mmask64 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi8(ptr, mask, values); + } + } + } + + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto msb_one = _mm512_set1_epi8(0xFF); + auto mask_ = _mm512_cmp_epu8_mask((__m512i)mask, msb_one, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi8(mask_, (__m512i)a, (__m512i)b); + } + + Vectorized abs() const { + return _mm512_andnot_si512(_mm512_set1_epi8(0x80), values); + } + + Vectorized inline operator==(const Vectorizedf8& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_EQ_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + + Vectorized inline operator!=(const Vectorizedf8& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_NEQ_UQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + + Vectorized inline operator>(const Vectorizedf8& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_GT_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + + Vectorized inline operator>=(const Vectorizedf8& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_GE_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + + Vectorized inline operator<(const Vectorizedf8& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_LT_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } + + Vectorized inline operator<=(const Vectorizedf8& other) const { + return binary_compare(other, [](__m512 x, __m512 y) { + auto zero_vec = _mm512_set1_epi32(0); + auto cmp = _mm512_cmp_ps_mask(x, y, _CMP_LE_OQ); + return _mm512_castsi512_ps( + _mm512_mask_set1_epi32(zero_vec, cmp, 0xFFFFFFFF)); + }); + } +}; + +template <> +class Vectorized : public Vectorizedf8 { + public: + using Vectorizedf8::Vectorizedf8; + + using value_type = Float8_e4m3fn; + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template < + typename T, + typename Op, + std::enable_if_t< + std::is_same_v || + std::is_same_v, + int> = 0> +static inline Vectorized binary_fp8_op_as_fp32( + const Vectorized& a, + const Vectorized& b, + Op op) { + __m512 a0, a1, a2, a3; + __m512 b0, b1, b2, b3; + __m512 o0, o1, o2, o3; + if constexpr (std::is_same_v) { + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(a, 0), a0); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b, 0), b0); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(a, 1), a1); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b, 1), b1); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(a, 2), a2); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b, 2), b2); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(a, 3), a3); + cvtfp8e4m3_fp32(_mm512_extracti32x4_epi32(b, 3), b3); + } else { + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(a, 0), a0); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b, 0), b0); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(a, 1), a1); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b, 1), b1); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(a, 2), a2); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b, 2), b2); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(a, 3), a3); + cvtfp8e5m2_fp32(_mm512_extracti32x4_epi32(b, 3), b3); + } + o0 = op(a0, b0); + o1 = op(a1, b1); + o2 = op(a2, b2); + o3 = op(a3, b3); + + __m128i o128_0, o128_1, o128_2, o128_3; + if constexpr (std::is_same_v) { + o128_0 = cvtfp32_fp8e4m3(o0); + o128_1 = cvtfp32_fp8e4m3(o1); + o128_2 = cvtfp32_fp8e4m3(o2); + o128_3 = cvtfp32_fp8e4m3(o3); + } else { + o128_0 = cvtfp32_fp8e5m2(o0); + o128_1 = cvtfp32_fp8e5m2(o1); + o128_2 = cvtfp32_fp8e5m2(o2); + o128_3 = cvtfp32_fp8e5m2(o3); + } + + __m512i result = _mm512_setzero_si512(); + result = _mm512_inserti32x4(result, o128_0, 0); + result = _mm512_inserti32x4(result, o128_1, 1); + result = _mm512_inserti32x4(result, o128_2, 2); + result = _mm512_inserti32x4(result, o128_3, 3); + + return result; +} + +// Refer to +// https://github.com/pytorch/pytorch/pull/153364#discussion_r2086509353 FP8 +, +// -, *, /, planned to be deleted in the future and here is just to make +// compiler happy +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_add_ps(x, y); + }); +} + +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_sub_ps(x, y); + }); +} + +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_mul_ps(x, y); + }); +} + +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_div_ps(x, y); + }); +} + +Vectorized inline operator&( + const Vectorized& a, + const Vectorized& b) { + return _mm512_and_si512(a, b); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +template <> +class Vectorized : public Vectorizedf8 { + public: + using Vectorizedf8::Vectorizedf8; + + using value_type = Float8_e5m2; + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +// Refer to +// https://github.com/pytorch/pytorch/pull/153364#discussion_r2086509353 FP8 +, +// -, *, /, planned to be deleted in the future and here is just to make +// compiler happy +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_add_ps(x, y); + }); +} + +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_sub_ps(x, y); + }); +} + +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_mul_ps(x, y); + }); +} + +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return binary_fp8_op_as_fp32(a, b, [](const __m512& x, const __m512& y) { + return _mm512_div_ps(x, y); + }); +} + +Vectorized inline operator&( + const Vectorized& a, + const Vectorized& b) { + return _mm512_and_si512(a, b); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this == other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1.0f); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1.0f); +} + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_int.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_int.h new file mode 100644 index 0000000000000000000000000000000000000000..cf002eeec7d678a74feeb87c52aee2387cec05ae --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_int.h @@ -0,0 +1,2121 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { + +#ifdef CPU_CAPABILITY_AVX512 + +struct Vectorizedi { + protected: + __m512i values; + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + static inline __m512i invert(const __m512i& v) { + const auto ones = _mm512_set1_epi64(-1); + return _mm512_xor_si512(ones, v); + } + + public: + Vectorizedi() = default; + Vectorizedi(__m512i v) : values(v) {} + operator __m512i() const { + return values; + } +}; + +#else + +struct Vectorizedi {}; // dummy definition to make Vectorizedi always defined + +#endif // CPU_CAPABILITY_AVX512 + +#ifdef CPU_CAPABILITY_AVX512 + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized : public Vectorizedi { + private: + static const Vectorized ones; + + public: + using value_type = int64_t; + using size_type = int; + static constexpr size_type size() { + return 8; + } + using Vectorizedi::Vectorizedi; + Vectorized() { + values = _mm512_setzero_si512(); + } + Vectorized(int64_t v) { + values = _mm512_set1_epi64(v); + } + Vectorized( + int64_t val1, + int64_t val2, + int64_t val3, + int64_t val4, + int64_t val5, + int64_t val6, + int64_t val7, + int64_t val8) { + values = _mm512_setr_epi64(val1, val2, val3, val4, val5, val6, val7, val8); + } + template + static Vectorized blend( + Vectorized a, + Vectorized b) { + return _mm512_mask_blend_epi64(mask, a.values, b.values); + } + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto msb_one = _mm512_set1_epi64(0xFFFFFFFFFFFFFFFF); + auto mask_ = _mm512_cmp_epi64_mask(mask, msb_one, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi64(mask_, a.values, b.values); + } + template + static Vectorized arange( + int64_t base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step); + } + static Vectorized set( + Vectorized a, + Vectorized b, + int64_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } + static Vectorized loadu(const void* ptr, int64_t count) { + if (count == size()) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } else { + __mmask8 mask = (1ULL << count) - 1; + auto ones = _mm512_set1_epi64(1); + return _mm512_mask_loadu_epi64(ones, mask, ptr); + } + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm512-storeu-si512.html + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + __mmask8 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi64(ptr, mask, values); + } + } + const int64_t& operator[](int idx) const = delete; + int64_t& operator[](int idx) = delete; + Vectorized abs() const { + auto is_larger_mask = _mm512_cmpgt_epi64_mask(zero_vector, values); + auto is_larger = + _mm512_mask_set1_epi64(zero_vector, is_larger_mask, 0xFFFFFFFFFFFFFFFF); + auto inverse = _mm512_xor_si512(values, is_larger); + return _mm512_sub_epi64(inverse, is_larger); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_epi64(0); + } + Vectorized conj() const { + return *this; + } + Vectorized neg() const; + Vectorized operator==(const Vectorized& other) const { + auto mask = _mm512_cmpeq_epi64_mask(values, other.values); + return _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF); + } + Vectorized operator!=(const Vectorized& other) const { + auto mask = _mm512_cmpneq_epi64_mask(values, other.values); + return _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF); + } + Vectorized operator<(const Vectorized& other) const { + auto mask = _mm512_cmplt_epi64_mask(values, other.values); + return _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF); + } + Vectorized operator<=(const Vectorized& other) const { + auto mask = _mm512_cmple_epi64_mask(values, other.values); + return _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF); + } + Vectorized operator>(const Vectorized& other) const { + auto mask = _mm512_cmpgt_epi64_mask(values, other.values); + return _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF); + } + Vectorized operator>=(const Vectorized& other) const { + auto mask = _mm512_cmpge_epi64_mask(values, other.values); + return _mm512_mask_set1_epi64(zero_vector, mask, 0xFFFFFFFFFFFFFFFF); + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +struct is_vec_specialized_for : std::bool_constant {}; +template <> +class Vectorized : public Vectorizedi { + private: + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + static const Vectorized ones; + + public: + using value_type = int32_t; + static constexpr int size() { + return 16; + } + using Vectorizedi::Vectorizedi; + Vectorized() = default; + Vectorized(int32_t v) { + values = _mm512_set1_epi32(v); + } + Vectorized( + int32_t val1, + int32_t val2, + int32_t val3, + int32_t val4, + int32_t val5, + int32_t val6, + int32_t val7, + int32_t val8, + int32_t val9, + int32_t val10, + int32_t val11, + int32_t val12, + int32_t val13, + int32_t val14, + int32_t val15, + int32_t val16) { + values = _mm512_setr_epi32( + val1, + val2, + val3, + val4, + val5, + val6, + val7, + val8, + val9, + val10, + val11, + val12, + val13, + val14, + val15, + val16); + } + template + static Vectorized blend( + Vectorized a, + Vectorized b) { + return _mm512_mask_blend_epi32(mask, a.values, b.values); + } + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto msb_one = _mm512_set1_epi32(0xFFFFFFFF); + auto mask_ = _mm512_cmp_epi32_mask(mask, msb_one, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi32(mask_, a.values, b.values); + } + template + static Vectorized arange( + int32_t base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step); + } + static Vectorized set( + Vectorized a, + Vectorized b, + int32_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<1>(a, b); + case 2: + return blend<3>(a, b); + case 3: + return blend<7>(a, b); + case 4: + return blend<15>(a, b); + case 5: + return blend<31>(a, b); + case 6: + return blend<63>(a, b); + case 7: + return blend<127>(a, b); + case 8: + return blend<255>(a, b); + case 9: + return blend<511>(a, b); + case 10: + return blend<1023>(a, b); + case 11: + return blend<2047>(a, b); + case 12: + return blend<4095>(a, b); + case 13: + return blend<8191>(a, b); + case 14: + return blend<16383>(a, b); + case 15: + return blend<32767>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } + static Vectorized loadu(const void* ptr, int32_t count) { + if (count == size()) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } else { + __mmask16 mask = (1ULL << count) - 1; + auto ones = _mm512_set1_epi32(1); + return _mm512_mask_loadu_epi32(ones, mask, ptr); + } + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm512-storeu-si512.html + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + __mmask16 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi32(ptr, mask, values); + } + } + const int32_t& operator[](int idx) const = delete; + int32_t& operator[](int idx) = delete; + Vectorized abs() const { + return _mm512_abs_epi32(values); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_epi32(0); + } + Vectorized conj() const { + return *this; + } + Vectorized neg() const; + int32_t reduce_add() const { + return _mm512_reduce_add_epi32(values); + } + int32_t reduce_max() const { + return _mm512_reduce_max_epi32(values); + } + Vectorized operator==(const Vectorized& other) const { + auto mask = _mm512_cmpeq_epi32_mask(values, other.values); + return _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF); + } + Vectorized operator!=(const Vectorized& other) const { + auto mask = _mm512_cmpneq_epi32_mask(values, other.values); + return _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF); + } + Vectorized operator<(const Vectorized& other) const { + auto mask = _mm512_cmplt_epi32_mask(values, other.values); + return _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF); + } + Vectorized operator<=(const Vectorized& other) const { + auto mask = _mm512_cmple_epi32_mask(values, other.values); + return _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF); + } + Vectorized operator>(const Vectorized& other) const { + auto mask = _mm512_cmpgt_epi32_mask(values, other.values); + return _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF); + } + Vectorized operator>=(const Vectorized& other) const { + auto mask = _mm512_cmpge_epi32_mask(values, other.values); + return _mm512_mask_set1_epi32(zero_vector, mask, 0xFFFFFFFF); + } + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +inline void convert(const int32_t* src, float* dst, int64_t n) { + int64_t i; + // int32_t and float have same size +#ifndef _MSC_VER +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + auto input_vec = + _mm512_loadu_si512(reinterpret_cast(src + i)); + auto output_vec = _mm512_cvtepi32_ps(input_vec); + _mm512_storeu_ps(reinterpret_cast(dst + i), output_vec); + } +#ifndef _MSC_VER +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +template <> +inline void convert(const int32_t* src, double* dst, int64_t n) { + int64_t i; + // int32_t has half the size of double +#ifndef _MSC_VER +#pragma unroll +#endif + for (i = 0; i <= (n - Vectorized::size()); + i += Vectorized::size()) { + auto input_256_vec = + _mm256_loadu_si256(reinterpret_cast(src + i)); + auto output_vec = _mm512_cvtepi32_pd(input_256_vec); + _mm512_storeu_pd(reinterpret_cast(dst + i), output_vec); + } +#ifndef _MSC_VER +#pragma unroll +#endif + for (; i < n; i++) { + dst[i] = static_cast(src[i]); + } +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized : public Vectorizedi { + private: + static const Vectorized ones; + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + + public: + using value_type = int16_t; + static constexpr int size() { + return 32; + } + using Vectorizedi::Vectorizedi; + Vectorized() = default; + Vectorized(int16_t v) { + values = _mm512_set1_epi16(v); + } + Vectorized( + int16_t val1, + int16_t val2, + int16_t val3, + int16_t val4, + int16_t val5, + int16_t val6, + int16_t val7, + int16_t val8, + int16_t val9, + int16_t val10, + int16_t val11, + int16_t val12, + int16_t val13, + int16_t val14, + int16_t val15, + int16_t val16, + int16_t val17, + int16_t val18, + int16_t val19, + int16_t val20, + int16_t val21, + int16_t val22, + int16_t val23, + int16_t val24, + int16_t val25, + int16_t val26, + int16_t val27, + int16_t val28, + int16_t val29, + int16_t val30, + int16_t val31, + int16_t val32) { + values = _mm512_set_epi16( + val32, + val31, + val30, + val29, + val28, + val27, + val26, + val25, + val24, + val23, + val22, + val21, + val20, + val19, + val18, + val17, + val16, + val15, + val14, + val13, + val12, + val11, + val10, + val9, + val8, + val7, + val6, + val5, + val4, + val3, + val2, + val1); + } + template + static Vectorized blend( + Vectorized a, + Vectorized b) { + return _mm512_mask_blend_epi16(mask, a.values, b.values); + } + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto msb_one = _mm512_set1_epi16(0xFFFF); + auto mask_ = _mm512_cmp_epi16_mask(mask, msb_one, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi16(mask_, a.values, b.values); + } + template + static Vectorized arange( + int16_t base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step, + base + 16 * step, + base + 17 * step, + base + 18 * step, + base + 19 * step, + base + 20 * step, + base + 21 * step, + base + 22 * step, + base + 23 * step, + base + 24 * step, + base + 25 * step, + base + 26 * step, + base + 27 * step, + base + 28 * step, + base + 29 * step, + base + 30 * step, + base + 31 * step); + } + static Vectorized set( + Vectorized a, + Vectorized b, + int16_t count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<0x1>(a, b); + case 2: + return blend<0x3>(a, b); + case 3: + return blend<0x7>(a, b); + case 4: + return blend<0xF>(a, b); + case 5: + return blend<0x1F>(a, b); + case 6: + return blend<0x3F>(a, b); + case 7: + return blend<0x7F>(a, b); + case 8: + return blend<0xFF>(a, b); + case 9: + return blend<0x1FF>(a, b); + case 10: + return blend<0x3FF>(a, b); + case 11: + return blend<0x7FF>(a, b); + case 12: + return blend<0xFFF>(a, b); + case 13: + return blend<0x1FFF>(a, b); + case 14: + return blend<0x3FFF>(a, b); + case 15: + return blend<0x7FFF>(a, b); + case 16: + return blend<0xFFFF>(a, b); + case 17: + return blend<0x1FFFF>(a, b); + case 18: + return blend<0x3FFFF>(a, b); + case 19: + return blend<0x7FFFF>(a, b); + case 20: + return blend<0xFFFFF>(a, b); + case 21: + return blend<0x1FFFFF>(a, b); + case 22: + return blend<0x3FFFFF>(a, b); + case 23: + return blend<0x7FFFFF>(a, b); + case 24: + return blend<0xFFFFFF>(a, b); + case 25: + return blend<0x1FFFFFF>(a, b); + case 26: + return blend<0x3FFFFFF>(a, b); + case 27: + return blend<0x7FFFFFF>(a, b); + case 28: + return blend<0xFFFFFFF>(a, b); + case 29: + return blend<0x1FFFFFFF>(a, b); + case 30: + return blend<0x3FFFFFFF>(a, b); + case 31: + return blend<0x7FFFFFFF>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } + static Vectorized loadu(const void* ptr, int16_t count) { + if (count == size()) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } else { + __mmask32 mask = (1ULL << count) - 1; + auto ones = _mm512_set1_epi16(1); + return _mm512_mask_loadu_epi16(ones, mask, ptr); + } + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm512-storeu-si512.html + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + __mmask32 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi16(ptr, mask, values); + } + } + const int16_t& operator[](int idx) const = delete; + int16_t& operator[](int idx) = delete; + Vectorized abs() const { + return _mm512_abs_epi16(values); + } + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_epi16(0); + } + Vectorized conj() const { + return *this; + } + Vectorized neg() const; + Vectorized operator==(const Vectorized& other) const { + auto mask = _mm512_cmpeq_epi16_mask(values, other.values); + return _mm512_mask_set1_epi16(zero_vector, mask, 0xFFFF); + } + Vectorized operator!=(const Vectorized& other) const { + auto mask = _mm512_cmpneq_epi16_mask(values, other.values); + return _mm512_mask_set1_epi16(zero_vector, mask, 0xFFFF); + } + Vectorized operator<(const Vectorized& other) const { + auto mask = _mm512_cmplt_epi16_mask(values, other.values); + return _mm512_mask_set1_epi16(zero_vector, mask, 0xFFFF); + } + Vectorized operator<=(const Vectorized& other) const { + auto mask = _mm512_cmple_epi16_mask(values, other.values); + return _mm512_mask_set1_epi16(zero_vector, mask, 0xFFFF); + } + Vectorized operator>(const Vectorized& other) const { + auto mask = _mm512_cmpgt_epi16_mask(values, other.values); + return _mm512_mask_set1_epi16(zero_vector, mask, 0xFFFF); + } + Vectorized operator>=(const Vectorized& other) const { + auto mask = _mm512_cmpge_epi16_mask(values, other.values); + return _mm512_mask_set1_epi16(zero_vector, mask, 0xFFFF); + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template +class Vectorized8 : public Vectorizedi { + static_assert( + std::is_same_v || std::is_same_v, + "Only int8_t/uint8_t are supported"); + + protected: + static constexpr __m512i zero_vector{0, 0, 0, 0, 0, 0, 0, 0}; + static const Vectorized ones; + + public: + using value_type = T; + static constexpr int size() { + return 64; + } + using Vectorizedi::Vectorizedi; + Vectorized8() = default; + Vectorized8(T v) { + values = _mm512_set1_epi8(v); + } + Vectorized8( + T val1, + T val2, + T val3, + T val4, + T val5, + T val6, + T val7, + T val8, + T val9, + T val10, + T val11, + T val12, + T val13, + T val14, + T val15, + T val16, + T val17, + T val18, + T val19, + T val20, + T val21, + T val22, + T val23, + T val24, + T val25, + T val26, + T val27, + T val28, + T val29, + T val30, + T val31, + T val32, + T val33, + T val34, + T val35, + T val36, + T val37, + T val38, + T val39, + T val40, + T val41, + T val42, + T val43, + T val44, + T val45, + T val46, + T val47, + T val48, + T val49, + T val50, + T val51, + T val52, + T val53, + T val54, + T val55, + T val56, + T val57, + T val58, + T val59, + T val60, + T val61, + T val62, + T val63, + T val64) { + values = _mm512_set_epi8( + val64, + val63, + val62, + val61, + val60, + val59, + val58, + val57, + val56, + val55, + val54, + val53, + val52, + val51, + val50, + val49, + val48, + val47, + val46, + val45, + val44, + val43, + val42, + val41, + val40, + val39, + val38, + val37, + val36, + val35, + val34, + val33, + val32, + val31, + val30, + val29, + val28, + val27, + val26, + val25, + val24, + val23, + val22, + val21, + val20, + val19, + val18, + val17, + val16, + val15, + val14, + val13, + val12, + val11, + val10, + val9, + val8, + val7, + val6, + val5, + val4, + val3, + val2, + val1); + } + template + static Vectorized blend(Vectorized a, Vectorized b) { + return _mm512_mask_blend_epi8(mask, a.values, b.values); + } + template + static Vectorized arange( + T base = 0, + step_t step = static_cast(1)) { + return Vectorized( + base, + base + step, + base + 2 * step, + base + 3 * step, + base + 4 * step, + base + 5 * step, + base + 6 * step, + base + 7 * step, + base + 8 * step, + base + 9 * step, + base + 10 * step, + base + 11 * step, + base + 12 * step, + base + 13 * step, + base + 14 * step, + base + 15 * step, + base + 16 * step, + base + 17 * step, + base + 18 * step, + base + 19 * step, + base + 20 * step, + base + 21 * step, + base + 22 * step, + base + 23 * step, + base + 24 * step, + base + 25 * step, + base + 26 * step, + base + 27 * step, + base + 28 * step, + base + 29 * step, + base + 30 * step, + base + 31 * step, + base + 32 * step, + base + 33 * step, + base + 34 * step, + base + 35 * step, + base + 36 * step, + base + 37 * step, + base + 38 * step, + base + 39 * step, + base + 40 * step, + base + 41 * step, + base + 42 * step, + base + 43 * step, + base + 44 * step, + base + 45 * step, + base + 46 * step, + base + 47 * step, + base + 48 * step, + base + 49 * step, + base + 50 * step, + base + 51 * step, + base + 52 * step, + base + 53 * step, + base + 54 * step, + base + 55 * step, + base + 56 * step, + base + 57 * step, + base + 58 * step, + base + 59 * step, + base + 60 * step, + base + 61 * step, + base + 62 * step, + base + 63 * step); + } + static Vectorized set(Vectorized a, Vectorized b, T count = size()) { + switch (count) { + case 0: + return a; + case 1: + return blend<0x1>(a, b); + case 2: + return blend<0x3>(a, b); + case 3: + return blend<0x7>(a, b); + case 4: + return blend<0xF>(a, b); + case 5: + return blend<0x1F>(a, b); + case 6: + return blend<0x3F>(a, b); + case 7: + return blend<0x7F>(a, b); + case 8: + return blend<0xFF>(a, b); + case 9: + return blend<0x1FF>(a, b); + case 10: + return blend<0x3FF>(a, b); + case 11: + return blend<0x7FF>(a, b); + case 12: + return blend<0xFFF>(a, b); + case 13: + return blend<0x1FFF>(a, b); + case 14: + return blend<0x3FFF>(a, b); + case 15: + return blend<0x7FFF>(a, b); + case 16: + return blend<0xFFFF>(a, b); + case 17: + return blend<0x1FFFF>(a, b); + case 18: + return blend<0x3FFFF>(a, b); + case 19: + return blend<0x7FFFF>(a, b); + case 20: + return blend<0xFFFFF>(a, b); + case 21: + return blend<0x1FFFFF>(a, b); + case 22: + return blend<0x3FFFFF>(a, b); + case 23: + return blend<0x7FFFFF>(a, b); + case 24: + return blend<0xFFFFFF>(a, b); + case 25: + return blend<0x1FFFFFF>(a, b); + case 26: + return blend<0x3FFFFFF>(a, b); + case 27: + return blend<0x7FFFFFF>(a, b); + case 28: + return blend<0xFFFFFFF>(a, b); + case 29: + return blend<0x1FFFFFFF>(a, b); + case 30: + return blend<0x3FFFFFFF>(a, b); + case 31: + return blend<0x7FFFFFFF>(a, b); + case 32: + return blend<0xFFFFFFFF>(a, b); + case 33: + return blend<0x1FFFFFFFF>(a, b); + case 34: + return blend<0x3FFFFFFFF>(a, b); + case 35: + return blend<0x7FFFFFFFF>(a, b); + case 36: + return blend<0xFFFFFFFFF>(a, b); + case 37: + return blend<0x1FFFFFFFFF>(a, b); + case 38: + return blend<0x3FFFFFFFFF>(a, b); + case 39: + return blend<0x7FFFFFFFFF>(a, b); + case 40: + return blend<0xFFFFFFFFFF>(a, b); + case 41: + return blend<0x1FFFFFFFFFF>(a, b); + case 42: + return blend<0x3FFFFFFFFFF>(a, b); + case 43: + return blend<0x7FFFFFFFFFF>(a, b); + case 44: + return blend<0xFFFFFFFFFFF>(a, b); + case 45: + return blend<0x1FFFFFFFFFFF>(a, b); + case 46: + return blend<0x3FFFFFFFFFFF>(a, b); + case 47: + return blend<0x7FFFFFFFFFFF>(a, b); + case 48: + return blend<0xFFFFFFFFFFFF>(a, b); + case 49: + return blend<0x1FFFFFFFFFFFF>(a, b); + case 50: + return blend<0x3FFFFFFFFFFFF>(a, b); + case 51: + return blend<0x7FFFFFFFFFFFF>(a, b); + case 52: + return blend<0xFFFFFFFFFFFFF>(a, b); + case 53: + return blend<0x1FFFFFFFFFFFFF>(a, b); + case 54: + return blend<0x3FFFFFFFFFFFFF>(a, b); + case 55: + return blend<0x7FFFFFFFFFFFFF>(a, b); + case 56: + return blend<0xFFFFFFFFFFFFFF>(a, b); + case 57: + return blend<0x1FFFFFFFFFFFFFF>(a, b); + case 58: + return blend<0x3FFFFFFFFFFFFFF>(a, b); + case 59: + return blend<0x7FFFFFFFFFFFFFF>(a, b); + case 60: + return blend<0xFFFFFFFFFFFFFFF>(a, b); + case 61: + return blend<0x1FFFFFFFFFFFFFFF>(a, b); + case 62: + return blend<0x3FFFFFFFFFFFFFFF>(a, b); + case 63: + return blend<0x7FFFFFFFFFFFFFFF>(a, b); + } + return b; + } + static Vectorized loadu(const void* ptr) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } + static Vectorized loadu_one_fourth(const void* ptr) { + // Fast path if only load element number of 16. + // Note: We didn't merge it as fast path of loadu(const void* ptr, T count), + // Because loadu(const void* ptr, T count) requires zero initialization for + // upper 384 bits. However, by using _mm512_castsi128_si512, the upper 384 + // bits of the result are undefined. + // TODO We can use _mm512_zextsi128_si512 in the future, + // since gcc 9.3 doesn't support it now. + __m128i input_128 = _mm_loadu_si128(reinterpret_cast(ptr)); + return _mm512_castsi128_si512(input_128); + } + static Vectorized loadu(const void* ptr, T count) { + if (count == size()) { + return _mm512_loadu_si512(reinterpret_cast(ptr)); + } else if (count == 16) { + // Fast path if only load element number of 16 + return loadu_one_fourth(ptr); + } else { + __mmask64 mask = (1ULL << count) - 1; + auto ones = _mm512_set1_epi8(1); + return _mm512_mask_loadu_epi8(ones, mask, ptr); + } + } + void store(void* ptr, int count = size()) const { + if (count == size()) { + // ptr need not to be aligned here. See + // https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/intrinsics/intrinsics-for-intel-advanced-vector-extensions/intrinsics-for-load-and-store-operations-1/mm512-storeu-si512.html + _mm512_storeu_si512(reinterpret_cast<__m512i*>(ptr), values); + } else if (count > 0) { + if (count == 16) { + // Fast path if only store element number of 16 + _mm_storeu_si128( + reinterpret_cast<__m128i*>(ptr), _mm512_castsi512_si128(values)); + } else { + __mmask64 mask = (1ULL << count) - 1; + _mm512_mask_storeu_epi8(ptr, mask, values); + } + } + } + const T& operator[](int idx) const = delete; + T& operator[](int idx) = delete; + Vectorized real() const { + return *this; + } + Vectorized imag() const { + return _mm512_set1_epi8(0); + } + Vectorized conj() const { + return *this; + } +}; + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized : public Vectorized8 { + public: + using Vectorized8::Vectorized8; + + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto msb_one = _mm512_set1_epi8(0xFF); + auto mask_ = _mm512_cmp_epi8_mask(mask, msb_one, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi8(mask_, a.values, b.values); + } + + Vectorized neg() const; + + Vectorized abs() const { + return _mm512_abs_epi8(values); + } + + Vectorized operator==(const Vectorized& other) const { + auto mask = _mm512_cmpeq_epi8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator!=(const Vectorized& other) const { + auto mask = _mm512_cmpneq_epi8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator<(const Vectorized& other) const { + auto mask = _mm512_cmplt_epi8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator<=(const Vectorized& other) const { + auto mask = _mm512_cmple_epi8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator>(const Vectorized& other) const { + return other < *this; + } + Vectorized operator>=(const Vectorized& other) const { + return other <= *this; + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +class Vectorized : public Vectorized8 { + public: + using Vectorized8::Vectorized8; + + static Vectorized blendv( + const Vectorized& a, + const Vectorized& b, + const Vectorized& mask) { + auto msb_one = _mm512_set1_epi8(0xFF); + auto mask_ = _mm512_cmp_epu8_mask(mask, msb_one, _MM_CMPINT_EQ); + return _mm512_mask_blend_epi8(mask_, a.values, b.values); + } + + Vectorized neg() const; + + Vectorized abs() const { + return *this; + } + + Vectorized operator==(const Vectorized& other) const { + auto mask = _mm512_cmpeq_epu8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator!=(const Vectorized& other) const { + auto mask = _mm512_cmpneq_epu8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator<(const Vectorized& other) const { + auto mask = _mm512_cmplt_epu8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator<=(const Vectorized& other) const { + auto mask = _mm512_cmple_epu8_mask(values, other.values); + return _mm512_mask_set1_epi8(zero_vector, mask, 0xFF); + } + Vectorized operator>(const Vectorized& other) const { + return other < *this; + } + Vectorized operator>=(const Vectorized& other) const { + return other <= *this; + } + + Vectorized eq(const Vectorized& other) const; + Vectorized ne(const Vectorized& other) const; + Vectorized gt(const Vectorized& other) const; + Vectorized ge(const Vectorized& other) const; + Vectorized lt(const Vectorized& other) const; + Vectorized le(const Vectorized& other) const; +}; + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_epi64(a, b); +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_epi32(a, b); +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_epi16(a, b); +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_epi8(a, b); +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_epi8(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_epi64(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_epi32(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_epi16(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_epi8(a, b); +} + +template <> +Vectorized inline operator-( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sub_epi8(a, b); +} + +// Negation. Defined here so we can utilize operator- +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +inline Vectorized Vectorized::neg() const { + return Vectorized(0) - *this; +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mullo_epi64(a, b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mullo_epi32(a, b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mullo_epi16(a, b); +} + +template +Vectorized inline int_elementwise_binary_512( + const Vectorized& a, + const Vectorized& b, + Op op) { + T values_a[Vectorized::size()]; + T values_b[Vectorized::size()]; + a.store(values_a); + b.store(values_b); + for (int i = 0; i != Vectorized::size(); i++) { + values_a[i] = op(values_a[i], values_b[i]); + } + return Vectorized::loadu(values_a); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + // We don't have an instruction for multiplying int8_t +#ifndef CPU_CAPABILITY_AVX512 + return int_elementwise_binary_512(a, b, std::multiplies()); +#else + __m512i mask00FF = _mm512_set1_epi16(0x00FF); + __m512i a_lo = _mm512_srai_epi16(_mm512_slli_epi16(a, 8), 8); + __m512i b_lo = _mm512_srai_epi16(_mm512_slli_epi16(b, 8), 8); + __m512i a_hi = _mm512_srai_epi16(a, 8); + __m512i b_hi = _mm512_srai_epi16(b, 8); + __m512i res_lo = _mm512_and_si512(_mm512_mullo_epi16(a_lo, b_lo), mask00FF); + __m512i res_hi = _mm512_slli_epi16(_mm512_mullo_epi16(a_hi, b_hi), 8); + __m512i res = _mm512_or_si512(res_hi, res_lo); + return res; +#endif +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + // We don't have an instruction for multiplying uint8_t +#ifndef CPU_CAPABILITY_AVX512 + return int_elementwise_binary_512(a, b, std::multiplies()); +#else + __m512i mask00FF = _mm512_set1_epi16(0x00FF); + __m512i a_lo = _mm512_and_si512(a, mask00FF); + __m512i b_lo = _mm512_and_si512(b, mask00FF); + __m512i a_hi = _mm512_srli_epi16(a, 8); + __m512i b_hi = _mm512_srli_epi16(b, 8); + __m512i res_lo = _mm512_and_si512(_mm512_mullo_epi16(a_lo, b_lo), mask00FF); + __m512i res_hi = _mm512_slli_epi16(_mm512_mullo_epi16(a_hi, b_hi), 8); + __m512i res = _mm512_or_si512(res_hi, res_lo); + return res; +#endif +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_min_epi64(a, b); +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_min_epi32(a, b); +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_min_epi16(a, b); +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_min_epi8(a, b); +} + +template <> +Vectorized inline minimum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_min_epu8(a, b); +} + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_max_epi64(a, b); +} + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_max_epi32(a, b); +} + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_max_epi16(a, b); +} + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_max_epi8(a, b); +} + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return _mm512_max_epu8(a, b); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min_val, + const Vectorized& max_val) { + return _mm512_min_epi64(max_val, _mm512_max_epi64(a, min_val)); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min_val, + const Vectorized& max_val) { + return _mm512_min_epi32(max_val, _mm512_max_epi32(a, min_val)); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min_val, + const Vectorized& max_val) { + return _mm512_min_epi16(max_val, _mm512_max_epi16(a, min_val)); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min_val, + const Vectorized& max_val) { + return _mm512_min_epi8(max_val, _mm512_max_epi8(a, min_val)); +} + +template <> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min_val, + const Vectorized& max_val) { + return _mm512_min_epu8(max_val, _mm512_max_epu8(a, min_val)); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max_val) { + return _mm512_min_epi64(max_val, a); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max_val) { + return _mm512_min_epi32(max_val, a); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max_val) { + return _mm512_min_epi16(max_val, a); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max_val) { + return _mm512_min_epi8(max_val, a); +} + +template <> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max_val) { + return _mm512_min_epu8(max_val, a); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min_val) { + return _mm512_max_epi64(min_val, a); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min_val) { + return _mm512_max_epi32(min_val, a); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min_val) { + return _mm512_max_epi16(min_val, a); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min_val) { + return _mm512_max_epi8(min_val, a); +} + +template <> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min_val) { + return _mm512_max_epu8(min_val, a); +} + +template +std::enable_if_t< + !(std::is_same_v || std::is_same_v), + Vectorized< + int32_t>> inline convert_to_int32(const T* ptr, int count = Vectorized::size()) { + return Vectorized::loadu(ptr, count); +} + +template +std:: + enable_if_t, Vectorized> inline convert_to_int32( + const int8_t* ptr, + int count = Vectorized::size()) { + if (count == Vectorized::size()) { + return _mm512_cvtepi8_epi32( + _mm_loadu_si128(reinterpret_cast(ptr))); + } else { + auto a = Vectorized::loadu(ptr, count); + return _mm512_cvtepi8_epi32(_mm512_castsi512_si128(a)); + } +} + +template +std:: + enable_if_t, Vectorized> inline convert_to_int32( + const uint8_t* ptr, + int count = Vectorized::size()) { + if (count == Vectorized::size()) { + return _mm512_cvtepu8_epi32( + _mm_loadu_si128(reinterpret_cast(ptr))); + } else { + auto a = Vectorized::loadu(ptr, count); + return _mm512_cvtepu8_epi32(_mm512_castsi512_si128(a)); + } +} + +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return int_elementwise_binary_512(a, b, std::divides()); +} +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return int_elementwise_binary_512(a, b, std::divides()); +} +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return int_elementwise_binary_512(a, b, std::divides()); +} +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return int_elementwise_binary_512(a, b, std::divides()); +} +template <> +Vectorized inline operator/( + const Vectorized& a, + const Vectorized& b) { + return int_elementwise_binary_512(a, b, std::divides()); +} + +template < + class T, + typename std::enable_if_t< + std::is_base_of>::value, + int> = 0> +inline Vectorized operator&(const Vectorized& a, const Vectorized& b) { + return _mm512_and_si512(a, b); +} +template < + class T, + typename std::enable_if_t< + std::is_base_of>::value, + int> = 0> +inline Vectorized operator|(const Vectorized& a, const Vectorized& b) { + return _mm512_or_si512(a, b); +} +template < + class T, + typename std::enable_if_t< + std::is_base_of>::value, + int> = 0> +inline Vectorized operator^(const Vectorized& a, const Vectorized& b) { + return _mm512_xor_si512(a, b); +} +template < + class T, + typename std::enable_if_t< + std::is_base_of>::value, + int> = 0> +inline Vectorized operator~(const Vectorized& a) { + return _mm512_xor_si512(a, _mm512_set1_epi32(-1)); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +inline Vectorized Vectorized::eq( + const Vectorized& other) const { + return (*this == other) & Vectorized(1); +} + +inline Vectorized Vectorized::ne( + const Vectorized& other) const { + return (*this != other) & Vectorized(1); +} + +inline Vectorized Vectorized::gt( + const Vectorized& other) const { + return (*this > other) & Vectorized(1); +} + +inline Vectorized Vectorized::ge( + const Vectorized& other) const { + return (*this >= other) & Vectorized(1); +} + +inline Vectorized Vectorized::lt( + const Vectorized& other) const { + return (*this < other) & Vectorized(1); +} + +inline Vectorized Vectorized::le( + const Vectorized& other) const { + return (*this <= other) & Vectorized(1); +} + +template < + bool left_shift, + typename T, + typename std::enable_if_t< + std::is_same_v || std::is_same_v, + int> = 0> +Vectorized inline shift_512_8( + const Vectorized& a, + const Vectorized& b) { + // No vector instruction for shifting int8_t/uint8_t, so emulating + // it instead. + + // Control masks for shuffle operation, treating 512 bits as an + // array of 8-bit elements, and considering pairs of neighboring + // elements. Specifically, a mask named "ctl_M_N" (M,N in [0,1], and + // M!=N) is set so that shuffle will move element with index M from + // input pair into element with index N in output pair, and element + // with index M in output pair will be set to all 0s. + __m512i ctl_0_1 = _mm512_set_epi8( + 62, + 0x80, + 60, + 0x80, + 58, + 0x80, + 56, + 0x80, + 54, + 0x80, + 52, + 0x80, + 50, + 0x80, + 48, + 0x80, + 46, + 0x80, + 44, + 0x80, + 42, + 0x80, + 40, + 0x80, + 38, + 0x80, + 36, + 0x80, + 34, + 0x80, + 32, + 0x80, + 30, + 0x80, + 28, + 0x80, + 26, + 0x80, + 24, + 0x80, + 22, + 0x80, + 20, + 0x80, + 18, + 0x80, + 16, + 0x80, + 14, + 0x80, + 12, + 0x80, + 10, + 0x80, + 8, + 0x80, + 6, + 0x80, + 4, + 0x80, + 2, + 0x80, + 0, + 0x80); + __m512i ctl_1_0 = _mm512_set_epi8( + 0x80, + 63, + 0x80, + 61, + 0x80, + 59, + 0x80, + 57, + 0x80, + 55, + 0x80, + 53, + 0x80, + 51, + 0x80, + 49, + 0x80, + 47, + 0x80, + 45, + 0x80, + 43, + 0x80, + 41, + 0x80, + 39, + 0x80, + 37, + 0x80, + 35, + 0x80, + 33, + 0x80, + 31, + 0x80, + 29, + 0x80, + 27, + 0x80, + 25, + 0x80, + 23, + 0x80, + 21, + 0x80, + 19, + 0x80, + 17, + 0x80, + 15, + 0x80, + 13, + 0x80, + 11, + 0x80, + 9, + 0x80, + 7, + 0x80, + 5, + 0x80, + 3, + 0x80, + 1); + + // Masks for bitwise and operation, treating 512 bits as an array of + // 8-bit elements, and considering them in pairs of neighboring + // elements. A mask named "keep_M" (M in [0,1]) is set so that + // bitwise and will copy element with index M from input pair into + // element with the same index in output pair, while the other + // element in output pair will be set to all 0s. + __m512i keep_0 = _mm512_set1_epi16(0xFF); + __m512i keep_1 = _mm512_set1_epi16(0xFF00); + + // Take each 8-bit element with idx%2==0 from input array to be + // shifted and extend it to 16 bits so that 0s are added to the + // right. Then, perform shifting on this 16-bit number. Upper 8 + // bits will be proper result of shifting original 8-bit number, so + // write them to result array, into the same position from which + // corresponding input element is taken. Also, make sure that + // result array elements with idx%2!=0 are set to all 0s. + // + // Note that number of bits to shift for is extended to 16 bits by + // adding 0s to the left. That means this number is not properly + // sign-extended for negative values. However, number of bits to + // shift is treated as an unsigned integer by respective shift + // intrinsics anyway so if negative then either with or without + // proper sign extension, it will be interpreted as a number greater + // than 32, and the shifting result will be the same. + __m512i a0 = _mm512_shuffle_epi8(a, ctl_0_1); + __m512i b0 = _mm512_and_si512(b, keep_0); + __m512i c0; + if (left_shift) + c0 = _mm512_sllv_epi16(a0, b0); + else if constexpr (std::is_same_v) + c0 = _mm512_srav_epi16(a0, b0); + else + c0 = _mm512_srlv_epi16(a0, b0); + c0 = _mm512_shuffle_epi8(c0, ctl_1_0); + + // Perform shifting the same way for input array elements with + // idx%2==1. + __m512i a1 = _mm512_and_si512(a, keep_1); + __m512i b1 = _mm512_shuffle_epi8(b, ctl_1_0); + __m512i c1; + if (left_shift) + c1 = _mm512_sllv_epi16(a1, b1); + else if constexpr (std::is_same_v) + c1 = _mm512_srav_epi16(a1, b1); + else + c1 = _mm512_srlv_epi16(a1, b1); + c1 = _mm512_and_si512(c1, keep_1); + + // Merge partial results into the final result. + __m512i c = _mm512_or_si512(c0, c1); + + return c; +} + +template <> +Vectorized inline operator<<( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sllv_epi64(a, b); +} + +template <> +Vectorized inline operator<<( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sllv_epi32(a, b); +} + +template <> +Vectorized inline operator<<( + const Vectorized& a, + const Vectorized& b) { + return _mm512_sllv_epi16(a, b); +} + +template <> +Vectorized inline operator<<( + const Vectorized& a, + const Vectorized& b) { + return shift_512_8(a, b); +} + +template <> +Vectorized inline operator<<( + const Vectorized& a, + const Vectorized& b) { + return shift_512_8(a, b); +} + +template <> +Vectorized inline operator>>( + const Vectorized& a, + const Vectorized& b) { + return _mm512_srav_epi64(a, b); +} + +template <> +Vectorized inline operator>>( + const Vectorized& a, + const Vectorized& b) { + return _mm512_srav_epi32(a, b); +} + +template <> +Vectorized inline operator>>( + const Vectorized& a, + const Vectorized& b) { + return _mm512_srav_epi16(a, b); +} + +template <> +Vectorized inline operator>>( + const Vectorized& a, + const Vectorized& b) { + return shift_512_8(a, b); +} + +template <> +Vectorized inline operator>>( + const Vectorized& a, + const Vectorized& b) { + return shift_512_8(a, b); +} + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_mask.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_mask.h new file mode 100644 index 0000000000000000000000000000000000000000..2ce1d895329fd7922f8b93e3b9cd164b93917f94 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_mask.h @@ -0,0 +1,390 @@ +#pragma once + +#include +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + +template +struct VecMaskLoad< + T, + dst_n, + mask_t, + mask_n, + typename std::enable_if_t< + (mask_n == dst_n * 2 && dst_n >= 1) && + (std::is_same_v || std::is_same_v), + void>> { + static inline VectorizedN apply( + const T* ptr, + const VecMask& vec_mask) { + at::vec::Vectorized zero_vec(0); + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + VectorizedN tmp_vec; + VectorizedN result; + for (int i = 0; i < dst_n; i++) { + tmp_vec[0] = vec_mask[2 * i]; + tmp_vec[1] = vec_mask[2 * i + 1]; + auto int64_mask = VecMask(tmp_vec).template cast(); + auto int_mask = int64_mask.template cast()[0]; + auto mmask = _mm512_cmp_epi32_mask(int_mask, all_ones, _MM_CMPINT_EQ); + if constexpr (std::is_same_v) { + result[i] = Vectorized(_mm512_mask_loadu_ps( + zero_vec, mmask, ptr + i * Vectorized::size())); + } else { + result[i] = Vectorized(_mm512_mask_loadu_epi32( + zero_vec, mmask, ptr + i * Vectorized::size())); + } + } + return result; + } +}; + +template +struct VecMaskLoad< + T, + dst_n, + mask_t, + dst_n, + typename std::enable_if_t< + std::is_same_v || std::is_same_v, + void>> { + static inline VectorizedN apply( + const T* ptr, + const VecMask& vec_mask) { + at::vec::Vectorized zero_vec(0); + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < dst_n; i++) { + auto tmp_mask = VecMask(vec_mask[i]); + auto int_mask = tmp_mask.template cast()[0]; + auto mmask = _mm512_cmp_epi32_mask(int_mask, all_ones, _MM_CMPINT_EQ); + if constexpr (std::is_same_v) { + result[i] = Vectorized(_mm512_mask_loadu_ps( + zero_vec, mmask, ptr + i * Vectorized::size())); + } else { + result[i] = Vectorized(_mm512_mask_loadu_epi32( + zero_vec, mmask, ptr + i * Vectorized::size())); + } + } + return result; + } +}; + +template +struct VecMaskLoad< + data_t, + dst_n, + mask_t, + dst_n, + std::enable_if_t< + std::is_same_v || std::is_same_v>> { + static inline VectorizedN apply( + const data_t* ptr, + const VecMask& vec_mask) { + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < dst_n; i++) { + auto tmp_mask = VecMask(vec_mask[i]); + auto int_mask = tmp_mask.template cast(); + auto mmask0 = _mm512_cmp_epi32_mask(int_mask[0], all_ones, _MM_CMPINT_EQ); + auto mmask1 = _mm512_cmp_epi32_mask(int_mask[1], all_ones, _MM_CMPINT_EQ); + auto zero = _mm256_set1_epi16(0); + auto temp0 = _mm256_mask_loadu_epi16( + zero, mmask0, ptr + (2 * i) * Vectorized::size()); + auto temp1 = _mm256_mask_loadu_epi16( + zero, mmask1, ptr + (2 * i + 1) * Vectorized::size()); + result[i] = Vectorized( + _mm512_inserti32x8(_mm512_castsi256_si512(temp0), temp1, 1)); + } + return result; + } +}; + +template +struct VecMaskLoad< + data_t, + dst_n, + mask_t, + mask_n, + typename std::enable_if_t< + (mask_n == 2 * dst_n && dst_n >= 1) && + (std::is_same_v || std::is_same_v)>> { + static inline VectorizedN apply( + const data_t* ptr, + const VecMask& vec_mask) { + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + VectorizedN result; + VectorizedN tmp_vec; + for (int i = 0; i < dst_n; i++) { + tmp_vec[0] = vec_mask[2 * i]; + tmp_vec[1] = vec_mask[2 * i + 1]; + auto int_mask = VecMask(tmp_vec).template cast(); + auto mmask0 = _mm512_cmp_epi32_mask(int_mask[0], all_ones, _MM_CMPINT_EQ); + auto mmask1 = _mm512_cmp_epi32_mask(int_mask[1], all_ones, _MM_CMPINT_EQ); + auto zero = _mm256_set1_epi16(0); + auto temp0 = _mm256_mask_loadu_epi16( + zero, mmask0, ptr + (2 * i) * Vectorized::size()); + auto temp1 = _mm256_mask_loadu_epi16( + zero, mmask1, ptr + (2 * i + 1) * Vectorized::size()); + result[i] = Vectorized( + _mm512_inserti32x8(_mm512_castsi256_si512(temp0), temp1, 1)); + } + return result; + } +}; + +template +struct VecMaskLoad< + data_t, + 1, + mask_t, + 1, + std::enable_if_t< + std::is_same_v || std::is_same_v>> { + static inline VectorizedN apply( + const data_t* ptr, + const VecMask& vec_mask) { + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + auto int_mask = vec_mask.template cast()[0]; + auto mmask = _mm512_cmp_epi32_mask(int_mask, all_ones, _MM_CMPINT_EQ); + auto zero = _mm_set1_epi8(0); + auto temp = _mm_mask_loadu_epi8(zero, mmask, ptr); + return Vectorized( + _mm512_inserti64x2(_mm512_set1_epi32(0), temp, 0)); + } +}; + +template +struct VecMaskLoad< + data_t, + 2, + mask_t, + 1, + std::enable_if_t< + std::is_same_v || std::is_same_v>> { + static inline VectorizedN apply( + const data_t* ptr, + const VecMask& vec_mask) { + auto all_ones = _mm512_set1_epi32(0xFFFFFFFF); + at::vec::Vectorized zero_vec(0); + auto int_mask = vec_mask.template cast()[0]; + auto mmask = _mm512_cmp_epi32_mask(int_mask, all_ones, _MM_CMPINT_EQ); + at::vec::VectorizedN result; + if constexpr (std::is_same_v) { + result[0] = _mm512_mask_loadu_pd(zero_vec, (__mmask8)mmask, ptr); + result[1] = + _mm512_mask_loadu_pd(zero_vec, (__mmask8)(mmask >> 8), ptr + 8); + } else { + result[0] = _mm512_mask_loadu_epi64(zero_vec, (__mmask8)mmask, ptr); + result[1] = + _mm512_mask_loadu_epi64(zero_vec, (__mmask8)(mmask >> 8), ptr + 8); + } + return result; + } +}; + +template +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result[i] = _mm512_castsi512_ps(vec_mask[i]); + } + return result; + } +}; + +template +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result[i] = _mm512_castps_si512(vec_mask[i]); + } + return result; + } +}; + +template +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result[i] = _mm512_castpd_si512(vec_mask[i]); + } + return result; + } +}; + +template +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result[i] = _mm512_castsi512_pd(vec_mask[i]); + } + return result; + } +}; + +template +struct VecMaskCast< + int64_t, + dst_n, + mask_t, + mask_n, + typename std::enable_if_t< + (dst_n == 2 * mask_n) && + (std::is_same_v || std::is_same_v), + void>> { + static inline VecMask apply( + const VecMask& vec_mask) { + VectorizedN result; + auto int_mask = vec_mask.template cast(); +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < mask_n; ++i) { + auto int64_vec = + convert(VectorizedN(int_mask[i])); + result[2 * i] = int64_vec[0]; + result[2 * i + 1] = int64_vec[1]; + } + return VecMask(result); + } +}; + +template +struct VecMaskCast< + dst_t, + dst_n, + int64_t, + mask_n, + typename std::enable_if_t< + (mask_n == 2 * dst_n) && + (std::is_same_v || std::is_same_v), + void>> { + static inline VecMask apply( + const VecMask& vec_mask) { + VectorizedN result; + VectorizedN int64_vec; + for (int i = 0; i < dst_n; ++i) { + int64_vec[0] = vec_mask[2 * i]; + int64_vec[1] = vec_mask[2 * i + 1]; + result[i] = convert(int64_vec); + } + return VecMask(result).template cast(); + } +}; + +template <> +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + auto int64_mask = VecMaskCast::apply(vec_mask); + return VecMaskCast::apply(int64_mask); + } +}; + +template <> +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + auto int64_mask = VecMaskCast::apply(vec_mask); + return VecMaskCast::apply(int64_mask); + } +}; + +template <> +inline bool VecMask::all_zero() const { + __mmask16 mask = _mm512_test_epi32_mask(mask_[0], mask_[0]); + return mask == 0; +} + +template <> +inline bool VecMask::is_masked(int i) const { + return _mm512_movepi32_mask(mask_[0]) & (1 << i); +} + +template <> +inline bool VecMask::all_masked() const { + __mmask16 mask = _mm512_movepi32_mask(mask_[0]); + return mask == 0xffff; +} + +template +struct VecMaskCheck { + static inline bool all_zero(const VectorizedN& vec_mask) { + bool all_zero = true; + for (int i = 0; i < N; ++i) { + all_zero = + all_zero && (_mm512_test_epi64_mask(vec_mask[i], vec_mask[i]) == 0); + if (!all_zero) { + return all_zero; + } + } + return all_zero; + } + + static inline bool is_masked(const VectorizedN& vec_mask, int i) { + for (int j = 0; j < N; ++j) { + if (i < (j + 1) * 8) { + return _mm512_movepi64_mask(vec_mask[j]) & (1 << (i - j * 8)); + } + } + return false; + } + + static inline bool all_masked(const VectorizedN& vec_mask) { + bool all_masked = true; + for (int i = 0; i < N; ++i) { + all_masked = all_masked && (_mm512_movepi64_mask(vec_mask[i]) == 0xff); + if (!all_masked) { + return all_masked; + } + } + return all_masked; + } +}; + +#define VEC_MASK_METHOD_WITH_CAST_TO_INT( \ + T, N, return_type, method, args_def, args) \ + template <> \ + inline return_type VecMask::method args_def const { \ + return cast().method args; \ + } + +VEC_MASK_METHOD_WITH_CAST_TO_INT(float, 1, bool, all_zero, (), ()) +VEC_MASK_METHOD_WITH_CAST_TO_INT(int64_t, 2, bool, all_zero, (), ()) +VEC_MASK_METHOD_WITH_CAST_TO_INT(float, 1, bool, is_masked, (int i), (i)) +VEC_MASK_METHOD_WITH_CAST_TO_INT(int64_t, 2, bool, is_masked, (int i), (i)) +VEC_MASK_METHOD_WITH_CAST_TO_INT(float, 1, bool, all_masked, (), ()) +VEC_MASK_METHOD_WITH_CAST_TO_INT(int64_t, 2, bool, all_masked, (), ()) + +#undef VEC_MASK_DEFINE_METHOD_WITH_CAST_TO_INT + +#endif + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_qint.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_qint.h new file mode 100644 index 0000000000000000000000000000000000000000..64f001abe498c4ffe981c25a6b875c7122bc5d54 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec512/vec512_qint.h @@ -0,0 +1,1543 @@ +#pragma once + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +// This file defines Vectorized<> for the quantized types. +// +// +// Currently, we simply use these classes as efficient converters between +// the quantized types and Vectorized, usually in bandwidth-bound cases +// where doing the arithmetic in full-precision is acceptable (e.g. +// elementwise operators). +// +// +// Conversions are as follows: +// Vectorized -> 4x Vectorized +// Vectorized -> 4x Vectorized +// Vectorized -> 1x Vectorized +// +// The size of the returned float vector is specified by the special +// constexpr function float_num_vecs. The type of the value returned +// from dequantize (and expected as an argument to quantize) is +// specified by float_vec_return_type. +// +// When writing kernels with these vectors, it is expected that floating- +// point operations will be carried out in a loop over +// Vectorized::float_num_vecs iterations. + +namespace at { +namespace vec { +inline namespace CPU_CAPABILITY { + +#if defined(CPU_CAPABILITY_AVX512) + +#ifdef _MSC_VER +__declspec(align(64)) struct Vectorizedqi { + protected: + __m512i vals; +#else +struct Vectorizedqi { + protected: + __m512i vals __attribute__((aligned(64))); +#endif + + public: + Vectorizedqi() { + vals = _mm512_setzero_si512(); + } + Vectorizedqi(__m512i v) : vals(v) {} + operator __m512i() const { + return vals; + } +}; + +template +__m512i pack_saturate_and_clamp( + __m512i first, + __m512i second, + T min_val, + T max_val); + +template <> +inline __m512i pack_saturate_and_clamp( + __m512i first [[maybe_unused]], + __m512i second [[maybe_unused]], + int32_t min_val [[maybe_unused]], + int32_t max_val [[maybe_unused]]) { + // This function is for linkage only, will not be used + TORCH_CHECK(false, "pack_saturate_and_clamp is not supported"); + return __m512i{}; +} + +template <> +inline __m512i pack_saturate_and_clamp( + __m512i first, + __m512i second, + int8_t min_val, + int8_t max_val) { + __m512i packed_and_sat = _mm512_packs_epi16(first, second); + return _mm512_max_epi8( + _mm512_set1_epi8(min_val), + _mm512_min_epi8(packed_and_sat, _mm512_set1_epi8(max_val))); +} + +template <> +inline __m512i pack_saturate_and_clamp( + __m512i first, + __m512i second, + uint8_t min_val, + uint8_t max_val) { + __m512i packed_and_sat = _mm512_packus_epi16(first, second); + return _mm512_max_epu8( + _mm512_set1_epi8(min_val), + _mm512_min_epu8(packed_and_sat, _mm512_set1_epi8(max_val))); +} + +template +typename std::enable_if_t< + std::is_same_v || std::is_same_v, + at::vec::Vectorized< + float>> inline convert_int8_to_float(at::vec::Vectorized src) { + // Note: this function only convert inputs number of elements equal to + // at::vec::Vectorized.size() Only handle first 16*8 bits + __m128i input_128 = _mm512_castsi512_si128(src); + // Convert from 16*uint8/int8 to 16*int32 + __m512i input_512_extended; + if constexpr (std::is_same_v) + input_512_extended = _mm512_cvtepu8_epi32(input_128); + else + input_512_extended = _mm512_cvtepi8_epi32(input_128); + // Convert from 16*int32 to 16*float32 + return _mm512_cvtepi32_ps(input_512_extended); +} + +template +at::vec::Vectorized inline convert_float_to_int8( + at::vec::Vectorized src); + +template <> +at::vec::Vectorized inline convert_float_to_int8( + at::vec::Vectorized src) { + // Convert from float32 to int32 with truncation + __m512i x_values_int32 = _mm512_cvttps_epi32(src); + + // Convert from int32 to int16 using signed saturation + __m512i xy_packed_v = _mm512_packs_epi32(x_values_int32, x_values_int32); + + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + + // Convert from int16 to int8 using unsigned saturation + __m512i xyzw_clamped_v = pack_saturate_and_clamp( + xy_packed_v, xy_packed_v, min_val, max_val); + __m512i permute_mask_v = _mm512_set_epi32( + 0x0f, + 0x0b, + 0x07, + 0x03, + 0x0e, + 0x0a, + 0x06, + 0x02, + 0x0d, + 0x09, + 0x05, + 0x01, + 0x0c, + 0x08, + 0x04, + 0x00); + return _mm512_permutexvar_epi32(permute_mask_v, xyzw_clamped_v); +} + +template <> +at::vec::Vectorized inline convert_float_to_int8( + at::vec::Vectorized src) { + // The type of *_val should be int32_t to ensure correct clamping behavior. + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + __m512 float32_min_val = _mm512_set1_ps(float(min_val)); + __m512 float32_max_val = _mm512_set1_ps(float(max_val)); + __m512 float32_src = _mm512_max_ps(src, float32_min_val); + float32_src = _mm512_min_ps(float32_src, float32_max_val); + __m512i int32_src_clamped = _mm512_cvttps_epi32(float32_src); + __m128i int8_src = _mm512_cvtepi32_epi8(int32_src_clamped); + return _mm512_castsi128_si512(int8_src); +} + +template +at::vec::Vectorized inline round_convert_float_to_int8( + at::vec::Vectorized src); + +template <> +at::vec::Vectorized inline round_convert_float_to_int8( + at::vec::Vectorized src) { + // Convert from float32 to int32 with round nearest + __m512i int32_src_round = _mm512_cvt_roundps_epi32( + src, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + // Convert from int32 to int8 with saturate + __m128i int8_src = _mm512_cvtsepi32_epi8(int32_src_round); + return _mm512_castsi128_si512(int8_src); +} + +template <> +at::vec::Vectorized inline round_convert_float_to_int8( + at::vec::Vectorized src) { + // Clamp float32 to unsigned int range + constexpr auto min_val = std::numeric_limits::min(); + __m512 float32_min_val = _mm512_set1_ps(float(min_val)); + __m512 float32_src = _mm512_max_ps(src, float32_min_val); + // Convert from float32 to int32 with round nearest + __m512i int32_src_round = _mm512_cvt_roundps_epi32( + float32_src, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC)); + // Convert from int32 to int8 with saturate + __m128i int8_src = _mm512_cvtusepi32_epi8(int32_src_round); + return _mm512_castsi128_si512(int8_src); +} + +template +__FORCE_INLINE void QuantizeAvx512( + const float* src, + T* dst, + int len, + float inverse_scale, + int64_t zero_point) { + constexpr int VLEN = 16; + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + const __m512i min_v = _mm512_set1_epi32(min_val); + const __m512i max_v = _mm512_set1_epi32(max_val); + // This is the largest int32 value < int32_max exactly representable in float + constexpr int32_t int32_float_max_val = + std::numeric_limits::max() - 127; + int i = 0; + __m512 inverse_scale_v = _mm512_set1_ps(inverse_scale); + // clang-format off + static const __m512i shuffle_mask_v = _mm512_set_epi8( + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0x0c, 0x08, 0x04, 0x00, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0x0c, 0x08, 0x04, 0x00, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0x0c, 0x08, 0x04, 0x00, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, + 0x0c, 0x08, 0x04, 0x00); + // clang-format on + __m512i permute_mask_v = _mm512_set_epi32( + 0x0f, + 0x0b, + 0x07, + 0x03, + 0x0e, + 0x0a, + 0x06, + 0x02, + 0x0d, + 0x09, + 0x05, + 0x01, + 0x0c, + 0x08, + 0x04, + 0x00); + __m512i permute_mask_l8_v = _mm512_set_epi32( + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x08, + 0x04, + 0x00); + int len_aligned = len / (VLEN * 4) * (VLEN * 4); + for (; i < len_aligned; i += 4 * VLEN) { + // x + __m512 x_vals = _mm512_load_ps(src + i); + __m512 x_transformed_v = _mm512_mul_ps(x_vals, inverse_scale_v); + // If the floating point value is greater than int32_max, + // _mm512_cvtps_epi32 converts them to -ve. Clip at int32_float_max_val to + // Clip at int32_float_max_val to avoid this. + x_transformed_v = + _mm512_min_ps(x_transformed_v, _mm512_set1_ps(int32_float_max_val)); + // y + __m512 y_vals = _mm512_load_ps(src + i + VLEN); + __m512 y_transformed_v = _mm512_mul_ps(y_vals, inverse_scale_v); + y_transformed_v = + _mm512_min_ps(y_transformed_v, _mm512_set1_ps(int32_float_max_val)); + // z + __m512 z_vals = _mm512_load_ps(src + i + 2 * VLEN); + __m512 z_transformed_v = _mm512_mul_ps(z_vals, inverse_scale_v); + z_transformed_v = + _mm512_min_ps(z_transformed_v, _mm512_set1_ps(int32_float_max_val)); + // w + __m512 w_vals = _mm512_load_ps(src + i + 3 * VLEN); + __m512 w_transformed_v = _mm512_mul_ps(w_vals, inverse_scale_v); + w_transformed_v = + _mm512_min_ps(w_transformed_v, _mm512_set1_ps(int32_float_max_val)); + + __m512i x_rounded_v = _mm512_cvtps_epi32(x_transformed_v); + __m512i y_rounded_v = _mm512_cvtps_epi32(y_transformed_v); + __m512i z_rounded_v = _mm512_cvtps_epi32(z_transformed_v); + __m512i w_rounded_v = _mm512_cvtps_epi32(w_transformed_v); + + // add zero point + x_rounded_v = _mm512_add_epi32(x_rounded_v, _mm512_set1_epi32(zero_point)); + y_rounded_v = _mm512_add_epi32(y_rounded_v, _mm512_set1_epi32(zero_point)); + z_rounded_v = _mm512_add_epi32(z_rounded_v, _mm512_set1_epi32(zero_point)); + w_rounded_v = _mm512_add_epi32(w_rounded_v, _mm512_set1_epi32(zero_point)); + + __m512i xy_packed_v = _mm512_packs_epi32(x_rounded_v, y_rounded_v); + __m512i zw_packed_v = _mm512_packs_epi32(z_rounded_v, w_rounded_v); + __m512i xyzw_clamped_v = + pack_saturate_and_clamp(xy_packed_v, zw_packed_v, min_val, max_val); + + xyzw_clamped_v = _mm512_permutexvar_epi32(permute_mask_v, xyzw_clamped_v); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + i), xyzw_clamped_v); + } + + // Additional 8-lane AVX512 version to take advantage when len is smaller + // based on fbgemm::QuantizeAvx2 (https://github.com/pytorch/FBGEMM) + for (; i < len / VLEN * VLEN; i += VLEN) { + __m512 x_vals = _mm512_load_ps(src + i); + __m512 x_transformed_v = _mm512_mul_ps(x_vals, inverse_scale_v); + x_transformed_v = + _mm512_min_ps(x_transformed_v, _mm512_set1_ps(int32_float_max_val)); + __m512i x_rounded_v = _mm512_cvtps_epi32(x_transformed_v); + x_rounded_v = _mm512_add_epi32(x_rounded_v, _mm512_set1_epi32(zero_point)); + __m512i x_clipped_v = + _mm512_max_epi32(min_v, _mm512_min_epi32(max_v, x_rounded_v)); + + x_clipped_v = _mm512_shuffle_epi8(x_clipped_v, shuffle_mask_v); + x_clipped_v = _mm512_permutexvar_epi32(permute_mask_l8_v, x_clipped_v); + _mm_storeu_si128( + reinterpret_cast<__m128i*>(dst + i), + _mm512_castsi512_si128(x_clipped_v)); + } + + for (; i < len; ++i) { + float transformed = src[i] * inverse_scale; + + // Not exactly the same behavior as the vectorized code. + // The vectorized code above always rounds to even in halfway cases + // (https://software.intel.com/en-us/node/523819), but std::nearbyint + // does the same only when the current rounding mode is FE_TONEAREST. + // However, in practice, this should not be a problem because most cases + // use the default rounding mode FE_TONEAREST. + // Note that we cannot implement the same behavior as the vectorized code + // using std::round because it does rounding away from zero in halfway + // cases. + transformed = zero_point + std::nearbyint(transformed); + float clipped = std::clamp(transformed, float(min_val), float(max_val)); + dst[i] = clipped; + } +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +struct Vectorized : public Vectorizedqi { + using size_type = int; + static constexpr size_type size() { + return 16; + } + + static constexpr int float_num_vecs() { + return 1; + } + + static constexpr int int_num_vecs() { + return 1; + } + + using float_vec_return_type = std::array, 1>; + using int_vec_return_type = std::array, 1>; + using value_type = c10::qint32::underlying; + + public: + using Vectorizedqi::Vectorizedqi; + Vectorized() = default; + + Vectorized(__m512i vals_) { + vals = vals_; + } + + // Broadcast constructor + Vectorized(const c10::qint32& val) { + value_type uw = val.val_; + vals = _mm512_set1_epi32(uw); + } + + void store(void* ptr, int count = size()) const { + if (count != size()) { + memcpy(ptr, &vals, std::min(count, size()) * sizeof(value_type)); + } else { + _mm512_storeu_si512((__m512i*)ptr, vals); + } + } + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + // Zero tail past `count`. + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(value_type)); + return loadu(tmp_values); + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { + __m512 float_vals = _mm512_cvtepi32_ps(vals); + return {vec::fmadd(scale, Vectorized(float_vals), scale_zp_premul)}; + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { + __m512 float_vals = _mm512_cvtepi32_ps(vals); + return {(Vectorized(float_vals) - zero_point) * scale}; + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale [[maybe_unused]]) { + Vectorized retval = {}; + auto rhs_data = (__m512)rhs[0]; + at::native::quantize_vec( + scale, zero_point, (float*)&rhs_data, (c10::qint32*)&retval.vals, 16); + return retval; + } + + Vectorized maximum(Vectorized b) const { + return _mm512_max_epi32(vals, b.vals); + } + + Vectorized minimum(Vectorized b) const { + return _mm512_min_epi32(vals, b.vals); + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + return _mm512_min_epi32( + _mm512_max_epi32(vals, zero_point.vals), q_six.vals); + } + + int_vec_return_type widening_subtract(Vectorized b) const { + return {_mm512_sub_epi32(vals, b)}; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + __m512 multiplier_v = _mm512_set1_ps(multiplier); + __m512i zero_point_v = _mm512_set1_epi32(zero_point); + + __m512 scaled = _mm512_mul_ps(_mm512_cvtepi32_ps(inp[0]), multiplier_v); + __m512i rounded = _mm512_cvtps_epi32(scaled); + return _mm512_add_epi32(rounded, zero_point_v); + } + + private: + // Load from memory constructor + Vectorized(const void* ptr) { + vals = _mm512_loadu_si512((const __m512i*)ptr); + } +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + return _mm512_mullo_epi32(a, b); +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + return _mm512_add_epi32(a, b); +} + +/* + * Convert values from int32 back to int8/uint8 + */ +template +__m512i RequantizeAvx512( + const std::array, 4>& inp, + __m512 multiplier, + __m512i zp) { + static_assert( + std::is_same_v || std::is_same_v, + "Only int8_t/uint8_t are supported"); + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + __m512i permute_mask_v = _mm512_set_epi32( + 0x0f, + 0x0b, + 0x07, + 0x03, + 0x0e, + 0x0a, + 0x06, + 0x02, + 0x0d, + 0x09, + 0x05, + 0x01, + 0x0c, + 0x08, + 0x04, + 0x00); + __m512 x_scaled_v = _mm512_mul_ps(_mm512_cvtepi32_ps(inp[0]), multiplier); + __m512 y_scaled_v = _mm512_mul_ps(_mm512_cvtepi32_ps(inp[1]), multiplier); + __m512 z_scaled_v = _mm512_mul_ps(_mm512_cvtepi32_ps(inp[2]), multiplier); + __m512 w_scaled_v = _mm512_mul_ps(_mm512_cvtepi32_ps(inp[3]), multiplier); + + __m512i x_rounded_v = _mm512_cvtps_epi32(x_scaled_v); + __m512i y_rounded_v = _mm512_cvtps_epi32(y_scaled_v); + __m512i z_rounded_v = _mm512_cvtps_epi32(z_scaled_v); + __m512i w_rounded_v = _mm512_cvtps_epi32(w_scaled_v); + + /* Add zero point */ + __m512i x_v = _mm512_add_epi32(x_rounded_v, zp); + __m512i y_v = _mm512_add_epi32(y_rounded_v, zp); + __m512i z_v = _mm512_add_epi32(z_rounded_v, zp); + __m512i w_v = _mm512_add_epi32(w_rounded_v, zp); + + /* Pack to int16_t and saturate */ + __m512i xy_packed_v = _mm512_packs_epi32(x_v, y_v); + __m512i zw_packed_v = _mm512_packs_epi32(z_v, w_v); + + __m512i xyzw_clamped_v = + pack_saturate_and_clamp(xy_packed_v, zw_packed_v, min_val, max_val); + + /* + * xyzw_clamped_v has results in the following layout so we need to + * permute: x0-3 y0-3 z0-3 w0-3 x4-7 y4-7 z4-7 w4-7 x8-11 y8-11 z8-11 w8-11 + * x12-15 y12-15 z12-15 w12-15 + */ + xyzw_clamped_v = _mm512_permutexvar_epi32(permute_mask_v, xyzw_clamped_v); + return xyzw_clamped_v; +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +struct Vectorized : public Vectorizedqi { + static constexpr int size() { + return 64; + } + + static constexpr int float_num_vecs() { + return 4; + } + + static constexpr int int_num_vecs() { + return 4; + } + + using float_vec_return_type = std::array, 4>; + using int_vec_return_type = std::array, 4>; + using value_type = c10::qint8::underlying; + + public: + using Vectorizedqi::Vectorizedqi; + + Vectorized() = default; + Vectorized(__m512i vals_) { + vals = vals_; + } + + // Broadcast constructor + Vectorized(const c10::qint8& val) { + value_type uw = val.val_; + vals = _mm512_set1_epi8(uw); + } + + // This is needed because the compiler emits awful code for the default + // constructor for moving the enum + Vectorized(const Vectorized& other) : Vectorizedqi(other.vals) {} + + // This is added to avoid error: definition of implicit copy assignment + // operator for 'Vectorized' is deprecated because it has a + // user-declared copy constructor [-Werror,-Wdeprecated-copy] + Vectorized& operator=(const Vectorized&) = default; + + void store(void* ptr, int count = size()) const { + if (count != size()) { + memcpy(ptr, &vals, std::min(count, size()) * sizeof(value_type)); + } else { + _mm512_storeu_si512((__m512i*)ptr, vals); + } + } + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + // Zero tail past `count`. + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(value_type)); + return loadu(tmp_values); + } + + private: + __m512i cvtepi8_epi32(__m128i epi8_vals) const { + return _mm512_cvtepi8_epi32(epi8_vals); + } + + public: + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_neg_zp_premul) const { +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_val0 = _mm_set_epi64x(vals.m512i_u64[1], vals.m512i_u64[0]); + __m128i int_val1 = _mm_set_epi64x(vals.m512i_u64[3], vals.m512i_u64[2]); + __m128i int_val2 = _mm_set_epi64x(vals.m512i_u64[5], vals.m512i_u64[4]); + __m128i int_val3 = _mm_set_epi64x(vals.m512i_u64[7], vals.m512i_u64[6]); +#else + __m128i int_val0 = _mm_set_epi64x(vals[1], vals[0]); + __m128i int_val1 = _mm_set_epi64x(vals[3], vals[2]); + __m128i int_val2 = _mm_set_epi64x(vals[5], vals[4]); + __m128i int_val3 = _mm_set_epi64x(vals[7], vals[6]); +#endif + + __m512 float_val0 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val0)); + __m512 float_val1 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val1)); + __m512 float_val2 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val2)); + __m512 float_val3 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val3)); + + auto val0 = + vec::fmadd(scale, Vectorized(float_val0), scale_neg_zp_premul); + auto val1 = + vec::fmadd(scale, Vectorized(float_val1), scale_neg_zp_premul); + auto val2 = + vec::fmadd(scale, Vectorized(float_val2), scale_neg_zp_premul); + auto val3 = + vec::fmadd(scale, Vectorized(float_val3), scale_neg_zp_premul); + return {val0, val1, val2, val3}; + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_val0 = _mm_set_epi64x(vals.m512i_u64[1], vals.m512i_u64[0]); + __m128i int_val1 = _mm_set_epi64x(vals.m512i_u64[3], vals.m512i_u64[2]); + __m128i int_val2 = _mm_set_epi64x(vals.m512i_u64[5], vals.m512i_u64[4]); + __m128i int_val3 = _mm_set_epi64x(vals.m512i_u64[7], vals.m512i_u64[6]); +#else + __m128i int_val0 = _mm_set_epi64x(vals[1], vals[0]); + __m128i int_val1 = _mm_set_epi64x(vals[3], vals[2]); + __m128i int_val2 = _mm_set_epi64x(vals[5], vals[4]); + __m128i int_val3 = _mm_set_epi64x(vals[7], vals[6]); +#endif + + __m512 float_val0 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val0)); + __m512 float_val1 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val1)); + __m512 float_val2 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val2)); + __m512 float_val3 = _mm512_cvtepi32_ps(cvtepi8_epi32(int_val3)); + + auto val0 = (Vectorized(float_val0) - zero_point) * scale; + auto val1 = (Vectorized(float_val1) - zero_point) * scale; + auto val2 = (Vectorized(float_val2) - zero_point) * scale; + auto val3 = (Vectorized(float_val3) - zero_point) * scale; + return {val0, val1, val2, val3}; + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + auto* rhs_data = (float*)rhs.data(); + int8_t quantized_values[64]; + QuantizeAvx512( + rhs_data, quantized_values, 64, inverse_scale, zero_point); + return Vectorized::loadu(quantized_values); + } + + Vectorized maximum(Vectorized b) const { + return _mm512_max_epi8(vals, b.vals); + } + + Vectorized minimum(Vectorized b) const { + return _mm512_min_epi8(vals, b.vals); + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + return _mm512_min_epi8(_mm512_max_epi8(vals, zero_point.vals), q_six.vals); + } + + int_vec_return_type widening_subtract(Vectorized b) const { +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_val0 = _mm_set_epi64x(vals.m512i_u64[1], vals.m512i_u64[0]); + __m128i int_val1 = _mm_set_epi64x(vals.m512i_u64[3], vals.m512i_u64[2]); + __m128i int_val2 = _mm_set_epi64x(vals.m512i_u64[5], vals.m512i_u64[4]); + __m128i int_val3 = _mm_set_epi64x(vals.m512i_u64[7], vals.m512i_u64[6]); +#else + __m128i int_val0 = _mm_set_epi64x(vals[1], vals[0]); + __m128i int_val1 = _mm_set_epi64x(vals[3], vals[2]); + __m128i int_val2 = _mm_set_epi64x(vals[5], vals[4]); + __m128i int_val3 = _mm_set_epi64x(vals[7], vals[6]); +#endif + + __m512i int32_val0 = cvtepi8_epi32(int_val0); + __m512i int32_val1 = cvtepi8_epi32(int_val1); + __m512i int32_val2 = cvtepi8_epi32(int_val2); + __m512i int32_val3 = cvtepi8_epi32(int_val3); + +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_b0 = _mm_set_epi64x(b.vals.m512i_u64[1], b.vals.m512i_u64[0]); + __m128i int_b1 = _mm_set_epi64x(b.vals.m512i_u64[3], b.vals.m512i_u64[2]); + __m128i int_b2 = _mm_set_epi64x(b.vals.m512i_u64[5], b.vals.m512i_u64[4]); + __m128i int_b3 = _mm_set_epi64x(b.vals.m512i_u64[7], b.vals.m512i_u64[6]); +#else + __m128i int_b0 = _mm_set_epi64x(b.vals[1], b.vals[0]); + __m128i int_b1 = _mm_set_epi64x(b.vals[3], b.vals[2]); + __m128i int_b2 = _mm_set_epi64x(b.vals[5], b.vals[4]); + __m128i int_b3 = _mm_set_epi64x(b.vals[7], b.vals[6]); +#endif + + __m512i int32_b0 = cvtepi8_epi32(int_b0); + __m512i int32_b1 = cvtepi8_epi32(int_b1); + __m512i int32_b2 = cvtepi8_epi32(int_b2); + __m512i int32_b3 = cvtepi8_epi32(int_b3); + + __m512i res_0 = _mm512_sub_epi32(int32_val0, int32_b0); + __m512i res_1 = _mm512_sub_epi32(int32_val1, int32_b1); + __m512i res_2 = _mm512_sub_epi32(int32_val2, int32_b2); + __m512i res_3 = _mm512_sub_epi32(int32_val3, int32_b3); + + return { + Vectorized(res_0), + Vectorized(res_1), + Vectorized(res_2), + Vectorized(res_3)}; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + __m512 multiplier_v = _mm512_set1_ps(multiplier); + __m512i zero_point_v = _mm512_set1_epi32(zero_point); + return RequantizeAvx512(inp, multiplier_v, zero_point_v); + } + + private: + // Load from memory constructor + Vectorized(const void* ptr) { + vals = _mm512_loadu_si512((const __m512i*)ptr); + } +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +struct Vectorized : public Vectorizedqi { + static constexpr int size() { + return 64; + } + + static constexpr int float_num_vecs() { + return 4; + } + + static constexpr int int_num_vecs() { + return 4; + } + + using float_vec_return_type = std::array, 4>; + using int_vec_return_type = std::array, 4>; + using value_type = c10::quint8::underlying; + + public: + using Vectorizedqi::Vectorizedqi; + Vectorized() = default; + + Vectorized(__m512i vals_) { + vals = vals_; + } + + // Broadcast constructor + Vectorized(const c10::quint8& val) { + value_type uw = val.val_; + vals = _mm512_set1_epi8(uw); + } + + Vectorized(const Vectorized& other) : Vectorizedqi(other.vals) {} + + // This is added to avoid error: definition of implicit copy assignment + // operator for 'Vectorized' is deprecated because it has a + // user-declared copy constructor [-Werror,-Wdeprecated-copy] + Vectorized& operator=(const Vectorized&) = default; + + void store(void* ptr, int count = size()) const { + if (count != size()) { + memcpy(ptr, &vals, std::min(count, size()) * sizeof(value_type)); + } else { + _mm512_storeu_si512((__m512i*)ptr, vals); + } + } + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + // Zero tail past `count`. + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(value_type)); + return loadu(tmp_values); + } + + private: + __m512i cvtepu8_epi32(__m128i epu8_vals) const { + return _mm512_cvtepu8_epi32(epu8_vals); + } + + public: + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul) const { +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_val0 = _mm_set_epi64x(vals.m512i_u64[1], vals.m512i_u64[0]); + __m128i int_val1 = _mm_set_epi64x(vals.m512i_u64[3], vals.m512i_u64[2]); + __m128i int_val2 = _mm_set_epi64x(vals.m512i_u64[5], vals.m512i_u64[4]); + __m128i int_val3 = _mm_set_epi64x(vals.m512i_u64[7], vals.m512i_u64[6]); +#else + __m128i int_val0 = _mm_set_epi64x(vals[1], vals[0]); + __m128i int_val1 = _mm_set_epi64x(vals[3], vals[2]); + __m128i int_val2 = _mm_set_epi64x(vals[5], vals[4]); + __m128i int_val3 = _mm_set_epi64x(vals[7], vals[6]); +#endif + + __m512 float_val0 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val0)); + __m512 float_val1 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val1)); + __m512 float_val2 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val2)); + __m512 float_val3 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val3)); + + auto val0 = + vec::fmadd(scale, Vectorized(float_val0), scale_zp_premul); + auto val1 = + vec::fmadd(scale, Vectorized(float_val1), scale_zp_premul); + auto val2 = + vec::fmadd(scale, Vectorized(float_val2), scale_zp_premul); + auto val3 = + vec::fmadd(scale, Vectorized(float_val3), scale_zp_premul); + + return {val0, val1, val2, val3}; + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_val0 = _mm_set_epi64x(vals.m512i_u64[1], vals.m512i_u64[0]); + __m128i int_val1 = _mm_set_epi64x(vals.m512i_u64[3], vals.m512i_u64[2]); + __m128i int_val2 = _mm_set_epi64x(vals.m512i_u64[5], vals.m512i_u64[4]); + __m128i int_val3 = _mm_set_epi64x(vals.m512i_u64[7], vals.m512i_u64[6]); +#else + __m128i int_val0 = _mm_set_epi64x(vals[1], vals[0]); + __m128i int_val1 = _mm_set_epi64x(vals[3], vals[2]); + __m128i int_val2 = _mm_set_epi64x(vals[5], vals[4]); + __m128i int_val3 = _mm_set_epi64x(vals[7], vals[6]); +#endif + + __m512 float_val0 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val0)); + __m512 float_val1 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val1)); + __m512 float_val2 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val2)); + __m512 float_val3 = _mm512_cvtepi32_ps(cvtepu8_epi32(int_val3)); + + auto val0 = (Vectorized(float_val0) - zero_point) * scale; + auto val1 = (Vectorized(float_val1) - zero_point) * scale; + auto val2 = (Vectorized(float_val2) - zero_point) * scale; + auto val3 = (Vectorized(float_val3) - zero_point) * scale; + + return {val0, val1, val2, val3}; + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale) { + auto* rhs_data = (float*)rhs.data(); + uint8_t quantized_values[64]; + QuantizeAvx512( + rhs_data, quantized_values, 64, inverse_scale, zero_point); + return Vectorized::loadu(quantized_values); + } + + Vectorized maximum(Vectorized b) const { + return _mm512_max_epu8(vals, b.vals); + } + + Vectorized minimum(Vectorized b) const { + return _mm512_min_epu8(vals, b.vals); + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + return _mm512_min_epu8(_mm512_max_epu8(vals, zero_point.vals), q_six.vals); + } + + int_vec_return_type widening_subtract(Vectorized b) const { +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_val0 = _mm_set_epi64x(vals.m512i_u64[1], vals.m512i_u64[0]); + __m128i int_val1 = _mm_set_epi64x(vals.m512i_u64[3], vals.m512i_u64[2]); + __m128i int_val2 = _mm_set_epi64x(vals.m512i_u64[5], vals.m512i_u64[4]); + __m128i int_val3 = _mm_set_epi64x(vals.m512i_u64[7], vals.m512i_u64[6]); +#else + __m128i int_val0 = _mm_set_epi64x(vals[1], vals[0]); + __m128i int_val1 = _mm_set_epi64x(vals[3], vals[2]); + __m128i int_val2 = _mm_set_epi64x(vals[5], vals[4]); + __m128i int_val3 = _mm_set_epi64x(vals[7], vals[6]); +#endif + + __m512i int32_val0 = cvtepu8_epi32(int_val0); + __m512i int32_val1 = cvtepu8_epi32(int_val1); + __m512i int32_val2 = cvtepu8_epi32(int_val2); + __m512i int32_val3 = cvtepu8_epi32(int_val3); + +#if defined(_MSC_VER) && !defined(__clang__) + __m128i int_b0 = _mm_set_epi64x(b.vals.m512i_u64[1], b.vals.m512i_u64[0]); + __m128i int_b1 = _mm_set_epi64x(b.vals.m512i_u64[3], b.vals.m512i_u64[2]); + __m128i int_b2 = _mm_set_epi64x(b.vals.m512i_u64[5], b.vals.m512i_u64[4]); + __m128i int_b3 = _mm_set_epi64x(b.vals.m512i_u64[7], b.vals.m512i_u64[6]); +#else + __m128i int_b0 = _mm_set_epi64x(b.vals[1], b.vals[0]); + __m128i int_b1 = _mm_set_epi64x(b.vals[3], b.vals[2]); + __m128i int_b2 = _mm_set_epi64x(b.vals[5], b.vals[4]); + __m128i int_b3 = _mm_set_epi64x(b.vals[7], b.vals[6]); +#endif + + __m512i int32_b0 = cvtepu8_epi32(int_b0); + __m512i int32_b1 = cvtepu8_epi32(int_b1); + __m512i int32_b2 = cvtepu8_epi32(int_b2); + __m512i int32_b3 = cvtepu8_epi32(int_b3); + + __m512i res_0 = _mm512_sub_epi32(int32_val0, int32_b0); + __m512i res_1 = _mm512_sub_epi32(int32_val1, int32_b1); + __m512i res_2 = _mm512_sub_epi32(int32_val2, int32_b2); + __m512i res_3 = _mm512_sub_epi32(int32_val3, int32_b3); + return { + Vectorized(res_0), + Vectorized(res_1), + Vectorized(res_2), + Vectorized(res_3)}; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + __m512 multiplier_v = _mm512_set1_ps(multiplier); + __m512i zero_point_v = _mm512_set1_epi32(zero_point); + return RequantizeAvx512(inp, multiplier_v, zero_point_v); + } + + private: + // Load from memory constructor + Vectorized(const void* ptr) { + vals = _mm512_loadu_si512((const __m512i*)ptr); + } +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +#else + +// NOTE: These are low-performance implementations that we fall back on. + +template < + typename T, + typename float_vec_return_type_, + typename int_vec_return_type_, + int size_> +struct VectorizedQuantizedConverter { + static constexpr int size() { + return size_; + } + + static constexpr int float_num_vecs() { + return size() / 8; + } + + static constexpr int int_num_vecs() { + return size() / 8; + } + + using float_vec_return_type = float_vec_return_type_; + using int_vec_return_type = int_vec_return_type_; + + using value_type = typename T::underlying; + std::array vals; + + VectorizedQuantizedConverter(T val) { + for (const auto i : c10::irange(size())) { + vals[i] = val.val_; + } + } + + VectorizedQuantizedConverter(const void* ptr) { + memcpy(vals.data(), ptr, sizeof(value_type) * size()); + } + + void store(void* ptr, int count = size()) const { + memcpy( + ptr, + vals.data(), + std::min(count, size()) * sizeof(value_type)); + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point, + Vectorized scale_zp_premul [[maybe_unused]]) const { + float_vec_return_type rv; + for (const auto i : c10::irange(float_num_vecs())) { + float tmp_vals[16]; + for (const auto j : c10::irange(16)) { + tmp_vals[j] = at::native::dequantize_val( + scale[j], zero_point[j], T(vals[16 * i + j])); + } + rv[i] = Vectorized( + tmp_vals[0], + tmp_vals[1], + tmp_vals[2], + tmp_vals[3], + tmp_vals[4], + tmp_vals[5], + tmp_vals[6], + tmp_vals[7], + tmp_vals[8], + tmp_vals[9], + tmp_vals[10], + tmp_vals[11], + tmp_vals[12], + tmp_vals[13], + tmp_vals[14], + tmp_vals[15]); + } + return rv; + } + + float_vec_return_type dequantize( + Vectorized scale, + Vectorized zero_point) const { + Vectorized scale_zp_premul; + return dequantize(scale, zero_point, scale_zp_premul); + } + + protected: + VectorizedQuantizedConverter() = default; +}; + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +struct Vectorized : public VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + 16> { + Vectorized() + : VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + 16>() {} + Vectorized(c10::qint32 val) + : VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + 16>(val) {} + Vectorized(const void* ptr) + : VectorizedQuantizedConverter< + c10::qint32, + std::array, 1>, + std::array, 1>, + 16>(ptr) {} + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + // Zero tail past `count`. + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(value_type)); + return loadu(tmp_values); + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale [[maybe_unused]]) { + std::array qvals; + std::array float_vals; + + for (const auto i : c10::irange(float_num_vecs())) { + rhs[i].store(&float_vals[i * 16], 16); + } + + at::native::quantize_vec( + scale, + zero_point, + float_vals.data(), + (c10::qint32*)qvals.data(), + 16 * float_num_vecs()); + + return Vectorized::loadu(qvals.data()); + } + + Vectorized maximum(Vectorized b) const { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::max(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized minimum(Vectorized b) const { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::min(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::min( + std::max(vals[i], zero_point.vals[i]), q_six.vals[i]); + } + return retval; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + int_vec_return_type retval; + for (const auto i : c10::irange(size())) { + retval[0].vals[i] = vals[i] - b.vals[i]; + } + return retval; + } + + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = + std::nearbyint(static_cast(inp[0].vals[i]) * multiplier) + + zero_point; + } + return retval; + } +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +template <> +Vectorized inline operator*( + const Vectorized& a, + const Vectorized& b) { + Vectorized retval; + for (const auto i : c10::irange(std::decay_t::size())) { + retval.vals[i] = a.vals[i] * b.vals[i]; + } + return retval; +} + +template <> +Vectorized inline operator+( + const Vectorized& a, + const Vectorized& b) { + Vectorized retval; + for (const auto i : c10::irange(std::decay_t::size())) { + retval.vals[i] = a.vals[i] + b.vals[i]; + } + return retval; +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +struct Vectorized : public VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + 64> { + Vectorized() + : VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + 64>() {} + Vectorized(c10::qint8 val) + : VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + 64>(val) {} + Vectorized(const void* ptr) + : VectorizedQuantizedConverter< + c10::qint8, + std::array, 4>, + std::array, 4>, + 64>(ptr) {} + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + // Zero tail past `count`. + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(value_type)); + return loadu(tmp_values); + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale [[maybe_unused]]) { + std::array qvals; + std::array float_vals; + + for (const auto i : c10::irange(float_num_vecs())) { + rhs[i].store(&float_vals[i * 16], 16); + } + + at::native::quantize_vec( + scale, + zero_point, + float_vals.data(), + (c10::qint8*)qvals.data(), + 16 * float_num_vecs()); + + return Vectorized::loadu(qvals.data()); + } + + Vectorized maximum(Vectorized b) const { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::max(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized minimum(Vectorized b) const { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::min(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::min( + std::max(vals[i], zero_point.vals[i]), q_six.vals[i]); + } + return retval; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + int_vec_return_type retval; + constexpr int elem_per_int_vec = size() / int_num_vecs(); + for (const auto i : c10::irange(int_num_vecs())) { + for (const auto j : c10::irange(elem_per_int_vec)) { + retval[i].vals[j] = + static_cast(vals[i * elem_per_int_vec + j]) - + static_cast(b.vals[i * elem_per_int_vec + j]); + } + } + return retval; + } + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + constexpr int elem_per_int_vec = size() / int_num_vecs(); + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + Vectorized retval; + for (const auto i : c10::irange(int_num_vecs())) { + for (const auto j : c10::irange(elem_per_int_vec)) { + int32_t rounded = + std::nearbyint(static_cast(inp[i].vals[j]) * multiplier) + + zero_point; + retval.vals[i * elem_per_int_vec + j] = + std::min(std::max(rounded, min_val), max_val); + } + } + return retval; + } +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +template <> +struct is_vec_specialized_for : std::bool_constant {}; + +template <> +struct Vectorized : public VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + 64> { + Vectorized() + : VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + 64>() {} + Vectorized(c10::quint8 val) + : VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + 64>(val) {} + Vectorized(const void* ptr) + : VectorizedQuantizedConverter< + c10::quint8, + std::array, 4>, + std::array, 4>, + 64>(ptr) {} + + static Vectorized loadu(const void* ptr) { + return Vectorized(ptr); + } + + static Vectorized loadu(const void* ptr, int64_t count) { + // Zero tail past `count`. + __at_align__ value_type tmp_values[size()] = {}; + std::memcpy( + tmp_values, + reinterpret_cast(ptr), + std::min(count, size()) * sizeof(value_type)); + return loadu(tmp_values); + } + + static Vectorized quantize( + const float_vec_return_type& rhs, + float scale, + int32_t zero_point, + float inverse_scale [[maybe_unused]]) { + std::array qvals; + std::array float_vals; + + for (const auto i : c10::irange(float_num_vecs())) { + rhs[i].store(&float_vals[i * 16], 16); + } + + at::native::quantize_vec( + scale, + zero_point, + float_vals.data(), + (c10::quint8*)qvals.data(), + 16 * float_num_vecs()); + + return Vectorized::loadu(qvals.data()); + } + + Vectorized maximum(Vectorized b) const { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::max(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized minimum(Vectorized b) const { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::min(vals[i], b.vals[i]); + } + return retval; + } + + Vectorized relu(Vectorized zero_point) const { + return maximum(zero_point); + } + + Vectorized relu6( + Vectorized zero_point, + Vectorized q_six) { + Vectorized retval; + for (const auto i : c10::irange(size())) { + retval.vals[i] = std::min( + std::max(vals[i], zero_point.vals[i]), q_six.vals[i]); + } + return retval; + } + + int_vec_return_type widening_subtract(Vectorized b) const { + int_vec_return_type retval; + constexpr int elem_per_int_vec = size() / int_num_vecs(); + for (const auto i : c10::irange(int_num_vecs())) { + for (const auto j : c10::irange(elem_per_int_vec)) { + retval[i].vals[j] = + static_cast(vals[i * elem_per_int_vec + j]) - + static_cast(b.vals[i * elem_per_int_vec + j]); + } + } + return retval; + } + static Vectorized requantize_from_int( + const int_vec_return_type& inp, + float multiplier, + int32_t zero_point) { + constexpr int elem_per_int_vec = size() / int_num_vecs(); + constexpr auto min_val = std::numeric_limits::min(); + constexpr auto max_val = std::numeric_limits::max(); + Vectorized retval; + for (const auto i : c10::irange(int_num_vecs())) { + for (const auto j : c10::irange(elem_per_int_vec)) { + int32_t rounded = + std::nearbyint(static_cast(inp[i].vals[j]) * multiplier) + + zero_point; + retval.vals[i * elem_per_int_vec + j] = + std::min(std::max(rounded, min_val), max_val); + } + } + return retval; + } +}; + +template <> +Vectorized inline maximum( + const Vectorized& a, + const Vectorized& b) { + return a.maximum(b); +} + +#endif // defined(CPU_CAPABILITY_AVX512) && !defined(MSVC) + +} // namespace CPU_CAPABILITY +} // namespace vec +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_base.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_base.h new file mode 100644 index 0000000000000000000000000000000000000000..35e42f1c684eac613a523326e3e9cbfd1e24de53 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_base.h @@ -0,0 +1,1563 @@ +#pragma once +#if defined(__GNUC__) && __GNUC__ == 10 && __GNUC_MINOR__ <= 2 && \ + defined(__ARM_FEATURE_SVE) +// Workaround for https: //gcc.gnu.org/bugzilla/show_bug.cgi?id=117161 +#pragma GCC optimize("no-tree-vectorize") +#endif + +// DO NOT DEFINE STATIC DATA IN THIS HEADER! +// See Note [Do not compile initializers with AVX] +// +// Note [Do not compile initializers with AVX] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// If you define a static initializer in this file, the initialization will use +// AVX instructions because these object files are compiled with AVX enabled. +// We need to avoid non-trivial global data in these architecture specific files +// because there's no way to guard the global initializers with CPU capability +// detection. +// +// See https://github.com/pytorch/pytorch/issues/37577 for an instance +// of this bug in the past. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__GNUC__) +#define __FORCE_INLINE __attribute__((always_inline)) inline +#elif defined(_MSC_VER) +#define __FORCE_INLINE __forceinline +#endif + +#if defined(_MSC_FULL_VER) +/* +https://learn.microsoft.com/en-us/cpp/overview/compiler-versions?view=msvc-170 +Use _MSC_FULL_VER to identify current compiler is msvc, +Windows llvm will not have this definition. +*/ +#define __msvc_cl__ +#endif + +// These macros helped us unify vec_base.h +#ifdef CPU_CAPABILITY_AVX512 +#if defined(__GNUC__) +#define __at_align__ __attribute__((aligned(64))) +#elif defined(_WIN32) +#define __at_align__ __declspec(align(64)) +#else +#define __at_align__ +#endif +#define VECTOR_WIDTH 64 +#define int_vector __m512i +#elif defined(__aarch64__) && \ + !defined(CPU_CAPABILITY_SVE256) // CPU_CAPABILITY_AVX512 +// SVE code expects 256-vectors; leave that set for SVE? +#if defined(__GNUC__) +#define __at_align__ __attribute__((aligned(16))) +#elif defined(_WIN32) +#define __at_align__ __declspec(align(16)) +#else +#define __at_align__ +#endif +#define VECTOR_WIDTH 16 +#else // CPU_CAPABILITY_AVX512 +#if defined(__GNUC__) +#define __at_align__ __attribute__((aligned(32))) +#elif defined(_WIN32) +#define __at_align__ __declspec(align(32)) +#else +#define __at_align__ +#endif +#define VECTOR_WIDTH 32 +#define int_vector __m256i +#endif // CPU_CAPABILITY_AVX512 + +// See Note [CPU_CAPABILITY namespace] +namespace at::vec::inline CPU_CAPABILITY { +// at::Half and at::BFloat16 should be treated as floating point +template +struct is_floating_point + : std::integral_constant< + bool, + std::is_floating_point_v || std::is_same_v || + std::is_same_v> {}; + +template +constexpr bool is_floating_point_v = is_floating_point::value; + +template +constexpr bool is_integer_v = std::is_integral_v; + +template +struct is_reduced_floating_point + : std::integral_constant< + bool, + std::is_same_v || std::is_same_v> {}; + +template +constexpr bool is_reduced_floating_point_v = + is_reduced_floating_point::value; + +template +struct is_8bit_integer + : std::integral_constant< + bool, + std::is_same_v || std::is_same_v> { +}; + +template +constexpr bool is_8bit_integer_v = is_8bit_integer::value; + +template +struct int_of_size; + +#define DEFINE_INT_OF_SIZE(int_t) \ + template <> \ + struct int_of_size { \ + using type = int_t; \ + } + +DEFINE_INT_OF_SIZE(int64_t); +DEFINE_INT_OF_SIZE(int32_t); +DEFINE_INT_OF_SIZE(int16_t); +DEFINE_INT_OF_SIZE(int8_t); + +#undef DEFINE_INT_OF_SIZE + +template +using int_same_size_t = typename int_of_size::type; + +/** + * Detect at compile time whether Vectorized has an explicit + * specialization for T. (You are required to specialize this type + * whenever you specialize Vectorized). Useful for generic algorithms + * to decide whether to rely on a specialization being fast. For + * example, they might choose to handle reduced-precision floating + * point types directly if they're supported, or convert through float + * if not. + */ +#if defined(__s390x__) +template +#else +template +#endif +struct is_vec_specialized_for : std::bool_constant { +}; + +template +constexpr bool is_vec_specialized_for_v = is_vec_specialized_for::value; + +// NOTE: If you specialize Vectorized on a type, you must define all +// operations! You must also specialize is_vec_specialized_for for +// that type. + +// emulates Vectorized types +#if defined(__s390x__) +template +#else +template +#endif +struct Vectorized { + private: + __at_align__ std::array values{}; + + public: + using value_type = T; + using size_type = int; + + static constexpr size_type kSize = VECTOR_WIDTH / sizeof(T); + static constexpr size_type size() { + return kSize; + } + Vectorized() = default; + Vectorized(T val) { + values.fill(val); + } + template < + typename... Args, + typename = std::enable_if_t<(sizeof...(Args) == size())>> + Vectorized(Args... vals) : values{vals...} {} + Vectorized(const T (&arr)[kSize]) { // NOLINT(*-avoid-c-arrays) + std::copy(std::begin(arr), std::end(arr), values.begin()); + } + // This also implies const T& operator[](int idx) const + inline operator const T*() const { + return values.data(); + } + // This also implies T& operator[](int idx) + inline operator T*() { + return values.data(); + } + // Return the values as char* for type punning + auto as_bytes() const -> const char* { + return reinterpret_cast(values.data()); + } + template + static Vectorized blend(const Vectorized& a, const Vectorized& b) { + int64_t mask = mask_; + Vectorized vector; + for (const auto i : c10::irange(size())) { + if (mask & 0x01) { + vector[i] = b[i]; + } else { + vector[i] = a[i]; + } + mask = mask >> 1; + } + return vector; + } +// Workaround for https: //gcc.gnu.org/bugzilla/show_bug.cgi?id=117001 +#if __GNUC__ <= 12 && !defined(__clang__) && defined(__ARM_FEATURE_SVE) + static Vectorized __attribute__((optimize("-fno-tree-loop-vectorize"))) + blendv( + const Vectorized& a, +#else + static Vectorized blendv( + const Vectorized& a, +#endif + const Vectorized& b, + const Vectorized& mask) { + Vectorized vector; + std::array, size()> buffer{}; + mask.store(buffer.data()); + for (const auto i : c10::irange(size())) { + if (buffer[i] & 0x01) { + vector[i] = b[i]; + } else { + vector[i] = a[i]; + } + } + return vector; + } + template // step sometimes requires a higher precision type + // (e.g., T=int, step_t=double) + static Vectorized arange( + T base = static_cast(0), + step_t step = static_cast(1)) { + Vectorized vector; + for (const auto i : c10::irange(size())) { + vector.values[i] = base + i * step; + } + return vector; + } + static Vectorized set( + const Vectorized& a, + const Vectorized& b, + int64_t count = size()) { + Vectorized vector; + for (const auto i : c10::irange(size())) { + if (i < count) { + vector[i] = b[i]; + } else { + vector[i] = a[i]; + } + } + return vector; + } + static Vectorized loadu(const void* ptr) { + Vectorized vector; + std::memcpy(vector.values.data(), ptr, VECTOR_WIDTH); + return vector; + } + static Vectorized loadu(const void* ptr, int64_t count) { + Vectorized vector; + std::memcpy( + vector.values.data(), + ptr, + std::min(count, size()) * sizeof(T)); + return vector; + } + static Vectorized loadu_one_fourth(const void* ptr) { + static_assert( + std::is_same_v || std::is_same_v, + "For byte types only"); + return Vectorized::loadu(ptr, 8); + } + + void store(void* ptr, int count = size()) const { + std::memcpy( + ptr, values.data(), std::min(count, size()) * sizeof(T)); + } + int zero_mask() const { + // returns an integer mask where all zero elements are translated to 1-bit + // and others are translated to 0-bit + int mask = 0; + for (int i = 0; i < size(); ++i) { + if (values[i] == static_cast(0)) { + mask |= (1 << i); + } + } + return mask; + } + Vectorized isnan() const { + Vectorized vector; + for (int64_t i = 0; i != size(); i++) { + if (_isnan(values[i])) { + std::memset(&vector.values[i], 0xFF, sizeof(T)); + } else { + std::memset(&vector.values[i], 0, sizeof(T)); + } + } + return vector; + } + bool has_inf_nan() const { + for (int64_t i = 0; i != size(); i++) { + if (_isnan(values[i]) || _isinf(values[i])) { + return true; + } + } + return false; + } +// MSVC versions between 14.36 and 14.42 has a loop unrolling bug on Windows +// Arm64 +// See +// https://developercommunity.visualstudio.com/t/MSVC-loop-unrolling-problem-194033813-/10720692 +#if defined(_WIN32) && defined(__aarch64__) && \ + ((_MSVC_VER >= 1936) && (_MSVC_VER <= 1942)) + Vectorized map(T (*const f)(T)) const { + Vectorized ret; + for (int64_t i = 0; i < size(); i++) { + ret[i] = f(values[i]); + if (++i < size()) + ret[i] = f(values[i]); + } + return ret; + } + T reduce(T (*const f)(T)) const { + T ret = 0; + for (int64_t i = 0; i < size(); i++) { + ret = f(ret, values[i]); + if (++i < size()) + ret = f(ret, values[i]); + } + return ret; + } +#else + Vectorized map(T (*const f)(T)) const { + Vectorized ret; + for (int64_t i = 0; i != size(); i++) { + ret[i] = f(values[i]); + } + return ret; + } + T reduce(T (*const f)(T)) const { + T ret = 0; + for (int64_t i = 0; i != size(); i++) { + ret = f(ret, values[i]); + } + return ret; + } +#endif + Vectorized map(T (*const f)(const T&)) const { + Vectorized ret; + for (int64_t i = 0; i != size(); i++) { + ret[i] = f(values[i]); + } + return ret; + } + T reduce(T (*const f)(const T&)) const { + T ret = 0; + for (int64_t i = 0; i != size(); i++) { + ret = f(ret, values[i]); + } + return ret; + } + template < + typename other_t_abs = T, + typename std::enable_if_t< + !is_floating_point_v && + !c10::is_complex::value, + int> = 0> + Vectorized abs() const { + // other_t_abs is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "other_t_abs must be T"); + return map([](T x) -> T { return x < static_cast(0) ? -x : x; }); + } + template < + typename float_t_abs = T, + typename std::enable_if_t, int> = 0> + Vectorized abs() const { + // float_t_abs is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "float_t_abs must be T"); + // Specifically deal with floating-point because the generic code above + // won't handle -0.0 (which should result in 0.0) properly. + return map([](T x) -> T { return std::abs(x); }); + } + template < + typename complex_t_abs = T, + typename std::enable_if_t::value, int> = 0> + Vectorized abs() const { + // complex_t_abs is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "complex_t_abs must be T"); + // Specifically map() does not perform the type conversion needed by abs. + return map([](T x) { return static_cast(std::abs(x)); }); + } + + template < + typename other_t_sgn = T, + typename std::enable_if_t::value, int> = 0> + Vectorized sgn() const { + return map(at::native::sgn_impl); + } + + template < + typename other_t_angle = T, + typename std::enable_if_t::value, int> = + 0> + Vectorized angle() const { + // other_t_angle is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "other_t_angle must be T"); + return map(at::native::angle_impl); // compiler is unable to resolve the + // overload without + } + template < + typename complex_t_angle = T, + typename std::enable_if_t::value, int> = + 0> + Vectorized angle() const { + // complex_t_angle is for SFINAE and clarity. Make sure it is not changed. + static_assert( + std::is_same_v, "complex_t_angle must be T"); + return map([](T x) { return static_cast(std::arg(x)); }); + } + template < + typename other_t_real = T, + typename std::enable_if_t::value, int> = 0> + Vectorized real() const { + // other_t_real is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "other_t_real must be T"); + return *this; + } + template < + typename complex_t_real = T, + typename std::enable_if_t::value, int> = + 0> + Vectorized real() const { + // complex_t_real is for SFINAE and clarity. Make sure it is not changed. + static_assert( + std::is_same_v, "complex_t_real must be T"); + return map([](T x) { return static_cast(x.real()); }); + } + template < + typename other_t_imag = T, + typename std::enable_if_t::value, int> = 0> + Vectorized imag() const { + // other_t_imag is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "other_t_imag must be T"); + return Vectorized(0); + } + template < + typename complex_t_imag = T, + typename std::enable_if_t::value, int> = + 0> + Vectorized imag() const { + // complex_t_imag is for SFINAE and clarity. Make sure it is not changed. + static_assert( + std::is_same_v, "complex_t_imag must be T"); + return map([](T x) { return static_cast(x.imag()); }); + } + template < + typename other_t_conj = T, + typename std::enable_if_t::value, int> = 0> + Vectorized conj() const { + // other_t_conj is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "other_t_conj must be T"); + return *this; + } + template < + typename complex_t_conj = T, + typename std::enable_if_t::value, int> = + 0> + Vectorized conj() const { + // complex_t_conj is for SFINAE and clarity. Make sure it is not changed. + static_assert( + std::is_same_v, "complex_t_conj must be T"); + return map([](T x) { return static_cast(std::conj(x)); }); + } + Vectorized acos() const { + return map(std::acos); + } + Vectorized acosh() const { + return map(std::acosh); + } + Vectorized asin() const { + return map(std::asin); + } + Vectorized asinh() const { + return map(std::asinh); + } + Vectorized atan() const { + return map(std::atan); + } + Vectorized atanh() const { + return map(std::atanh); + } + Vectorized atan2(const Vectorized& exp) const { + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = std::atan2(values[i], exp[i]); + } + return ret; + } + template < + typename U = T, + typename std::enable_if_t, int> = 0> + Vectorized copysign(const Vectorized& sign) const { + Vectorized ret; + for (size_type i = 0; i < size(); i++) { + ret[i] = c10::copysign(values[i], sign[i]); + } + return ret; + } + Vectorized erf() const { + return map(std::erf); + } + Vectorized erfc() const { + return map(std::erfc); + } + Vectorized erfinv() const { + return map(calc_erfinv); + } + Vectorized exp() const { + return map(std::exp); + } + Vectorized exp2() const { + return map(exp2_impl); + } + Vectorized expm1() const { + return map(std::expm1); + } + Vectorized exp_u20() const { + return map(std::exp); + } + Vectorized fexp_u20() const { + return map(std::exp); + } + Vectorized frac() const { + return *this - this->trunc(); + } + template < + typename U = T, + typename std::enable_if_t, int> = 0> + Vectorized fmod(const Vectorized& q) const { + // U is for SFINAE purposes only. Make sure it is not changed. + static_assert(std::is_same_v, "U must be T"); + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = std::fmod(values[i], q[i]); + } + return ret; + } + Vectorized log() const { + return map(std::log); + } + Vectorized log10() const { + return map(std::log10); + } + Vectorized log1p() const { + return map(std::log1p); + } + template < + typename other_t_log2 = T, + typename std::enable_if_t::value, int> = 0> + Vectorized log2() const { + // other_t_log2 is for SFINAE and clarity. Make sure it is not changed. + static_assert(std::is_same_v, "other_t_log2 must be T"); + return map(std::log2); + } + template < + typename complex_t_log2 = T, + typename std::enable_if_t::value, int> = + 0> + Vectorized log2() const { + // complex_t_log2 is for SFINAE and clarity. Make sure it is not changed. + static_assert( + std::is_same_v, "complex_t_log2 must be T"); + constexpr auto log_2 = c10::ln_2; + return Vectorized(map(std::log)) / Vectorized(log_2); + } + Vectorized ceil() const { + return map(at::native::ceil_impl); + } + Vectorized cos() const { + return map(std::cos); + } + Vectorized cosh() const { + return map(std::cosh); + } + Vectorized floor() const { + return map(at::native::floor_impl); + } + Vectorized hypot(const Vectorized& b) const { + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = std::hypot(values[i], b[i]); + } + return ret; + } + Vectorized i0() const { + return map(calc_i0); + } + Vectorized i0e() const { + return map(calc_i0e); + } + Vectorized digamma() const { + return map(calc_digamma); + } + Vectorized igamma(const Vectorized& x) const { + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = calc_igamma(values[i], x[i]); + } + return ret; + } + Vectorized igammac(const Vectorized& x) const { + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = calc_igammac(values[i], x[i]); + } + return ret; + } + Vectorized neg() const { + // NB: the trailing return type is needed because we need to coerce the + // return value back to T in the case of unary operator- incurring a + // promotion + return map([](T x) -> T { return -x; }); + } + Vectorized nextafter(const Vectorized& b) const { + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = std::nextafter(values[i], b[i]); + } + return ret; + } + Vectorized round() const { + // We do not use std::round because we would like to round midway numbers to + // the nearest even integer. + return map(at::native::round_impl); + } + Vectorized sin() const { + return map(std::sin); + } + Vectorized sinh() const { + return map(std::sinh); + } + Vectorized tan() const { + return map(std::tan); + } + Vectorized tanh() const { + return map(std::tanh); + } + Vectorized trunc() const { + return map(at::native::trunc_impl); + } + Vectorized lgamma() const { + return map(std::lgamma); + } + Vectorized sqrt() const { + return map(std::sqrt); + } + Vectorized reciprocal() const { + return map([](T x) { return (T)1 / x; }); + } + Vectorized rsqrt() const { + return map([](T x) { return (T)1 / std::sqrt(x); }); + } + Vectorized pow(const Vectorized& exp) const { + Vectorized ret; + for (const auto i : c10::irange(size())) { + ret[i] = std::pow(values[i], exp[i]); + } + return ret; + } + T reduce_add() const { + return reduce([](T x, T y) -> T { return x + y; }); + } + T reduce_max() const { + return reduce(std::max); + } + + private: + template + inline Vectorized binary_pred(const Vectorized& other, Op op) const { + // All bits are set to 1 if the pred is true, otherwise 0. + Vectorized vector; + for (int64_t i = 0; i != size(); i++) { + if (op(values[i], other.values[i])) { + std::memset(&vector.values[i], 0xFF, sizeof(T)); + } else { + std::memset(&vector.values[i], 0, sizeof(T)); + } + } + return vector; + } + + public: + Vectorized operator==(const Vectorized& other) const { + return binary_pred(other, std::equal_to()); + } + Vectorized operator!=(const Vectorized& other) const { + return binary_pred(other, std::not_equal_to()); + } + Vectorized operator>=(const Vectorized& other) const { + return binary_pred(other, std::greater_equal()); + } + Vectorized operator<=(const Vectorized& other) const { + return binary_pred(other, std::less_equal()); + } + Vectorized operator>(const Vectorized& other) const { + return binary_pred(other, std::greater()); + } + Vectorized operator<(const Vectorized& other) const { + return binary_pred(other, std::less()); + } + + private: + template + inline Vectorized binary_pred_bool(const Vectorized& other, Op op) + const { + // 1 if the pred is true, otherwise 0. + Vectorized vector; + for (int i = 0; i != size(); ++i) { + vector[i] = static_cast(op(values[i], other.values[i])); + } + return vector; + } + + public: + Vectorized eq(const Vectorized& other) const { + return binary_pred_bool(other, std::equal_to()); + } + Vectorized ne(const Vectorized& other) const { + return binary_pred_bool(other, std::not_equal_to()); + } + Vectorized gt(const Vectorized& other) const { + return binary_pred_bool(other, std::greater()); + } + Vectorized ge(const Vectorized& other) const { + return binary_pred_bool(other, std::greater_equal()); + } + Vectorized lt(const Vectorized& other) const { + return binary_pred_bool(other, std::less()); + } + Vectorized le(const Vectorized& other) const { + return binary_pred_bool(other, std::less_equal()); + } +}; + +template +Vectorized inline operator-(const Vectorized& a) { + return a.neg(); +} + +// There is an implicit conversion that would make this work if +// these operators weren't template functions, but they are template +// functions (and can't be moved to be non-member friends defined in +// the class body as suggested in +// https://stackoverflow.com/questions/9787593/implicit-type-conversion-with-template/9788255#9788255 +// because we have a lot of disparate specializations of +// Vectorized). So, just explicitly make scalars work. +#define VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(name) \ + template \ + Vectorized inline name(const Vectorized& a, T b) { \ + return name(a, Vectorized(b)); \ + } \ + template \ + Vectorized inline name(T a, const Vectorized& b) { \ + return name(Vectorized(a), b); \ + } +#define VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(op) \ + VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(operator op) + +template +Vectorized inline operator+(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] + b[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(+) + +template +Vectorized inline operator-(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] - b[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(-) + +template +Vectorized inline operator*(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] * b[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(*) + +template +Vectorized inline operator/(const Vectorized& a, const Vectorized& b) + __ubsan_ignore_float_divide_by_zero__ { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] / b[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(/) + +template , int> = 0> +Vectorized inline operator%(const Vectorized& a, const Vectorized& b) + __ubsan_ignore_float_divide_by_zero__ { + return a - a / b * b; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(%) + +template +Vectorized inline operator||( + const Vectorized& a, + const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] || b[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(||) + +// Implements the IEEE 754 201X `maximum` operation, which propagates NaN if +// either input is a NaN. +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = (a[i] > b[i]) ? a[i] : b[i]; + if (_isnan(a[i])) { + // If either input is NaN, propagate a NaN. + // NOTE: The case where b[i] was NaN is handled correctly by the naive + // ternary operator above. + c[i] = a[i]; + } + } + return c; +} + +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline maximum(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = (std::abs(a[i]) > std::abs(b[i])) ? a[i] : b[i]; + if (_isnan(a[i])) { + // If either input is NaN, propagate a NaN. + // NOTE: The case where b[i] was NaN is handled correctly by the naive + // ternary operator above. + c[i] = a[i]; + } + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(maximum) + +// Implements the IEEE 754 201X `minimum` operation, which propagates NaN if +// either input is a NaN. +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = (a[i] < b[i]) ? a[i] : b[i]; + if (_isnan(a[i])) { + // If either input is NaN, propagate a NaN. + // NOTE: The case where b[i] was NaN is handled correctly by the naive + // ternary operator above. + c[i] = a[i]; + } + } + return c; +} + +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline minimum(const Vectorized& a, const Vectorized& b) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = (std::abs(a[i]) < std::abs(b[i])) ? a[i] : b[i]; + if (_isnan(a[i])) { + // If either input is NaN, propagate a NaN. + // NOTE: The case where b[i] was NaN is handled correctly by the naive + // ternary operator above. + c[i] = a[i]; + } + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(minimum) + +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline clamp( + const Vectorized& a, + const Vectorized& min_vec, + const Vectorized& max_vec) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = std::min(std::max(a[i], min_vec[i]), max_vec[i]); + } + return c; +} + +#define VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC(name) \ + template \ + Vectorized inline name( \ + const Vectorized& a, const Vectorized& b, T c) { \ + return name(a, b, Vectorized(c)); \ + } \ + \ + template \ + Vectorized inline name( \ + const Vectorized& a, T b, const Vectorized& c) { \ + return name(a, Vectorized(b), c); \ + } \ + \ + template \ + Vectorized inline name(const Vectorized& a, T b, T c) { \ + return name(a, Vectorized(b), Vectorized(c)); \ + } \ + \ + template \ + Vectorized inline name( \ + T a, const Vectorized& b, const Vectorized& c) { \ + return name(Vectorized(a), b, c); \ + } \ + \ + template \ + Vectorized inline name(T a, const Vectorized& b, T c) { \ + return name(Vectorized(a), b, Vectorized(c)); \ + } \ + \ + template \ + Vectorized inline name(T a, T b, const Vectorized& c) { \ + return name(Vectorized(a), Vectorized(b), c); \ + } + +VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC(clamp) + +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline clamp_max( + const Vectorized& a, + const Vectorized& max_vec) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] > max_vec[i] ? max_vec[i] : a[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(clamp_max) + +template < + class T, + typename std::enable_if_t::value, int> = 0> +Vectorized inline clamp_min( + const Vectorized& a, + const Vectorized& min_vec) { + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] < min_vec[i] ? min_vec[i] : a[i]; + } + return c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(clamp_min) + +struct Vectorizedi; + +#if defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512) +template +static inline Vectorized bitwise_binary_op( + const Vectorized& a, + const Vectorized& b, + Op op) { + int_vector buffer; +#if defined(CPU_CAPABILITY_AVX2) + int_vector a_buffer = + _mm256_load_si256(reinterpret_cast((const T*)a)); + int_vector b_buffer = + _mm256_load_si256(reinterpret_cast((const T*)b)); +#elif defined(CPU_CAPABILITY_AVX512) + int_vector a_buffer = + _mm512_load_si512(reinterpret_cast((const T*)a)); + int_vector b_buffer = + _mm512_load_si512(reinterpret_cast((const T*)b)); +#endif + buffer = op(a_buffer, b_buffer); + __at_align__ std::array::size()> results{}; + +#if defined(CPU_CAPABILITY_AVX2) + _mm256_store_si256(reinterpret_cast(results.data()), buffer); +#elif defined(CPU_CAPABILITY_AVX512) + _mm512_store_si512(reinterpret_cast(results.data()), buffer); +#endif + return Vectorized::loadu(results.data()); +} + +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator&(const Vectorized& a, const Vectorized& b) { + // We enclose _mm512_and_si512 or _mm256_and_si256 with lambda because it is + // always_inline +#if defined(CPU_CAPABILITY_AVX2) + return bitwise_binary_op( + a, b, [](int_vector a, int_vector b) { return _mm256_and_si256(a, b); }); +#elif defined(CPU_CAPABILITY_AVX512) + return bitwise_binary_op( + a, b, [](int_vector a, int_vector b) { return _mm512_and_si512(a, b); }); +#endif +} +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator|(const Vectorized& a, const Vectorized& b) { + // We enclose _mm512_or_si512 or _mm256_or_si256 with lambda because it is + // always_inline +#if defined(CPU_CAPABILITY_AVX2) + return bitwise_binary_op( + a, b, [](int_vector a, int_vector b) { return _mm256_or_si256(a, b); }); +#elif defined(CPU_CAPABILITY_AVX512) + return bitwise_binary_op( + a, b, [](int_vector a, int_vector b) { return _mm512_or_si512(a, b); }); +#endif +} +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator^(const Vectorized& a, const Vectorized& b) { + // We enclose _mm512_xor_si512 or _mm256_xor_si256 with lambda because it is + // always_inline +#if defined(CPU_CAPABILITY_AVX2) + return bitwise_binary_op( + a, b, [](int_vector a, int_vector b) { return _mm256_xor_si256(a, b); }); +#elif defined(CPU_CAPABILITY_AVX512) + return bitwise_binary_op( + a, b, [](int_vector a, int_vector b) { return _mm512_xor_si512(a, b); }); +#endif +} + +#else + +template +auto load(char const* data) -> T { + T ret; + std::memcpy(&ret, data, sizeof(ret)); + return ret; +} + +template +static inline Vectorized bitwise_binary_op( + const Vectorized& a, + const Vectorized& b, + Op op) { + static constexpr uint32_t element_no = VECTOR_WIDTH / sizeof(intmax_t); + __at_align__ std::array buffer{}; + static_assert( + VECTOR_WIDTH % sizeof(intmax_t) == 0, + "VECTOR_WIDTH not a multiple of sizeof(intmax_t)"); + static_assert( + sizeof(buffer) == sizeof(Vectorized), + "sizeof(buffer) must match sizeof(Vectorized)"); + // We should be using memcpy in order to respect the strict aliasing rule + // see: https://github.com/pytorch/pytorch/issues/66119 + // Using char* is defined in the C11 standard 6.5 Expression paragraph 7 + // (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) + const auto* a_data = a.as_bytes(); + const auto* b_data = b.as_bytes(); + // load each intmax_t chunk and process; increase pointers by sizeof(intmax_t) + for (auto& out : buffer) { + out = op(load(a_data), load(b_data)); + a_data += sizeof(intmax_t); + b_data += sizeof(intmax_t); + } + assert(a_data == a.as_bytes() + sizeof(a)); + assert(b_data == b.as_bytes() + sizeof(b)); + return Vectorized::loadu(buffer.data()); +} + +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator&(const Vectorized& a, const Vectorized& b) { + return bitwise_binary_op(a, b, std::bit_and<>()); +} +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator|(const Vectorized& a, const Vectorized& b) { + return bitwise_binary_op(a, b, std::bit_or<>()); +} +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator^(const Vectorized& a, const Vectorized& b) { + return bitwise_binary_op(a, b, std::bit_xor<>()); +} + +#endif // defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512) + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(&) +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(|) +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(^) + +template < + class T, + typename std:: + enable_if_t>, int> = 0> +inline Vectorized operator~(const Vectorized& a) { + using int_t = int_same_size_t; + Vectorized ones(c10::bit_cast((int_t)(~(int_t)0))); // All bits are 1 + return a ^ ones; +} + +template +Vectorized inline operator<<( + const Vectorized& a, + const Vectorized& b) { + constexpr T max_shift = sizeof(T) * CHAR_BIT; + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + T shift = b[i]; + if ((static_cast>(shift) < 0) || + (shift >= max_shift)) { + c[i] = 0; + } else { + c[i] = static_cast>(a[i]) << shift; + } + } + return c; +} + +template +Vectorized inline operator>>( + const Vectorized& a, + const Vectorized& b) { + // right shift value to retain sign bit for signed and no bits for unsigned + constexpr T max_shift = sizeof(T) * CHAR_BIT - std::is_signed_v; + Vectorized c; + for (int i = 0; i != Vectorized::size(); i++) { + T shift = b[i]; + if ((static_cast>(shift) < 0) || + (shift >= max_shift)) { + c[i] = a[i] >> max_shift; + } else { + c[i] = a[i] >> shift; + } + } + return c; +} + +template +inline Vectorized& operator+=(Vectorized& a, const Vectorized& b) { + a = a + b; + return a; +} +template +inline Vectorized& operator-=(Vectorized& a, const Vectorized& b) { + a = a - b; + return a; +} +template +inline Vectorized& operator/=(Vectorized& a, const Vectorized& b) { + a = a / b; + return a; +} +template +inline Vectorized& operator%=(Vectorized& a, const Vectorized& b) { + a = a % b; + return a; +} +template +inline Vectorized& operator*=(Vectorized& a, const Vectorized& b) { + a = a * b; + return a; +} + +template +inline Vectorized& operator<<=(Vectorized& a, const Vectorized& b) { + a = a << b; + return a; +} + +template +inline Vectorized& operator>>=(Vectorized& a, const Vectorized& b) { + a = a >> b; + return a; +} + +template +inline Vectorized fmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return a * b + c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC(fmadd) + +template +inline Vectorized fnmadd( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return -(a * b) + c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC(fnmadd) + +template +inline Vectorized fmsub( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return a * b - c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC(fmsub) + +template +inline Vectorized fnmsub( + const Vectorized& a, + const Vectorized& b, + const Vectorized& c) { + return -(a * b) - c; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC(fnmsub) + +template +Vectorized inline operator&&( + const Vectorized& a, + const Vectorized& b) { + Vectorized ret; + for (int i = 0; i != Vectorized::size(); i++) { + ret[i] = a[i] && b[i]; + } + return ret; +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP(&&) + +template +std::enable_if_t< + scale == 1 || scale == 2 || scale == 4 || scale == 8, + Vectorized< + T>> inline gather(T const* base_addr, const Vectorized>& vindex) { + static constexpr int size = Vectorized::size(); + std::array, size> index_arr{}; + vindex.store(index_arr.data()); + std::array buffer{}; + for (const auto i : c10::irange(size)) { + buffer[i] = base_addr[index_arr[i] * scale / sizeof(T)]; + } + return Vectorized::loadu(buffer.data()); +} + +template +std:: + enable_if_t> inline mask_gather( + const Vectorized& src, + T const* base_addr, + const Vectorized>& vindex, + Vectorized& mask) { + static constexpr int size = Vectorized::size(); + std::array src_arr{}; + // use int type so we can logical and + std::array, size> mask_arr{}; + std::array, size> index_arr{}; + src.store(src_arr.data()); + mask.store(mask_arr.data()); + vindex.store(index_arr.data()); + std::array buffer{}; + for (const auto i : c10::irange(size)) { + if (mask_arr[i] & 0x01) { // check highest bit + buffer[i] = base_addr[index_arr[i] * scale / sizeof(T)]; + } else { + buffer[i] = src_arr[i]; + } + } + mask = Vectorized(static_cast(0)); // "zero out" mask + return Vectorized::loadu(buffer.data()); +} + +// Cast a given vector to another type without changing the bits representation. +// So a Vectorized of 512 bits containing all ones can be cast to a +// Vectorized of 512 bits containing all ones (i.e., eight negative +// 1s). A Vec of 256 bits containing all ones can be cast to a +// Vec of 256 bits containing all ones (i.e., four negative 1s). +// There is a struct here because we don't have static_if and I can't +// partially specialize a templated function. +template +struct CastImpl { + static inline Vectorized apply(const Vectorized& src) { + std::array::size()> src_arr{}; + src.store(src_arr.data()); + return Vectorized::loadu(src_arr.data()); + } +}; + +template +struct CastImpl { + static inline Vectorized apply(const Vectorized& src) { + return src; + } +}; + +template +inline Vectorized cast(const Vectorized& src) { + return CastImpl::apply(src); +} + +template > +inline Vectorized convert_to_int_of_same_size( + const Vectorized& src) { + static_assert(sizeof(T) == sizeof(IntType)); + static constexpr int size = Vectorized::size(); + + std::array src_arr{}; + src.store(static_cast(src_arr.data())); + std::array buffer{}; + std::transform( + src_arr.cbegin(), src_arr.cend(), buffer.begin(), [](const T& x) { + return static_cast(x); + }); + return Vectorized::loadu(static_cast(buffer.data())); +} + +template > +inline Vectorized convert_to_fp_of_same_size( + const Vectorized& src) { + static_assert(sizeof(T) == sizeof(IntType)); + static constexpr int size = Vectorized::size(); + + std::array src_arr{}; + src.store(static_cast(src_arr.data())); + std::array buffer{}; + std::transform( + src_arr.cbegin(), src_arr.cend(), buffer.begin(), [](const IntType& x) { + return static_cast(x); + }); + return Vectorized::loadu(static_cast(buffer.data())); +} + +// clang-format off +// Example inputs for AVX512: +// a Vectorized = {a0, b0, a1, b1, a2, b2, a3, b3, a4, b4, a5, b5, a6, b6, a7, b7} +// b Vectorized = {a8, b8, a9, b9, a10, b10, a11, b11, a12, b12, a13, b13, a14, b14, a15, b15} +// returns: +// Vectorized = {a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15} +// Vectorized = {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15} +// Example inputs for AVX2: a Vectorized = {a0, b0, a1, b1, a2, b2, a3, b3} +// b Vectorized = {a4, b4, a5, b5, a6, b6, a7, b7} +// returns: Vectorized = {a0, a1, a2, a3, a4, a5, a6, a7} +// Vectorized = {b0, b1, b2, b3, b4, b5, b6, b7} +// clang-format on +template +inline std::enable_if_t< + Vectorized::size() % 2 == 0, + std::pair, Vectorized>> +deinterleave2(const Vectorized& a, const Vectorized& b) { + static constexpr int size = Vectorized::size(); + static constexpr int half_size = size / 2; + std::array a_arr{}; + std::array b_arr{}; + std::array buffer1{}; + std::array buffer2{}; + a.store(a_arr.data()); + b.store(b_arr.data()); + for (const auto i : c10::irange(half_size)) { + buffer1[i] = a_arr[i * 2]; + buffer1[half_size + i] = b_arr[i * 2]; + buffer2[i] = a_arr[i * 2 + 1]; + buffer2[half_size + i] = b_arr[i * 2 + 1]; + } + return std::make_pair( + Vectorized::loadu(buffer1.data()), + Vectorized::loadu(buffer2.data())); +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(deinterleave2) + +// clang-format off +// inverse operation of deinterleave2 +// Example inputs for AVX512: +// a Vectorized = {a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15} +// b Vectorized = {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15} +// returns, for AVX512: +// Vectorized = {a0, b0, a1, b1, a2, b2, a3, b3, a4, b4, a5, b5, a6, b6, a7, b7} +// Vectorized = {a8, b8, a9, b9, a10, b10, a11, b11, a12, b12, a13, b13, a14, b14, a15, b15} +// Example inputs for AVX2 : a Vectorized = {a0, a1, a2, a3, a4, a5, a6, a7} +// b Vectorized = {b0, b1, b2, b3, b4, b5, b6, b7} +// returns: Vectorized = {a0, b0, a1, b1, a2, b2, a3, b3} +// Vectorized = {a4, b4, a5, b5, a6, b6, a7, b7} +// clang-format on +template +inline std::enable_if_t< + Vectorized::size() % 2 == 0, + std::pair, Vectorized>> +interleave2(const Vectorized& a, const Vectorized& b) { + static constexpr int size = Vectorized::size(); + static constexpr int half_size = size / 2; + std::array a_arr{}; + std::array b_arr{}; + std::array buffer1{}; + std::array buffer2{}; + a.store(a_arr.data()); + b.store(b_arr.data()); + for (const auto i : c10::irange(half_size)) { + buffer1[i * 2] = a_arr[i]; + buffer1[i * 2 + 1] = b_arr[i]; + buffer2[i * 2] = a_arr[half_size + i]; + buffer2[i * 2 + 1] = b_arr[half_size + i]; + } + return std::make_pair( + Vectorized::loadu(buffer1.data()), + Vectorized::loadu(buffer2.data())); +} + +VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC(interleave2) + +#undef VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_FUNC +#undef VECTORIZED_SUPPORT_SCALARS_FOR_BINARY_OP +#undef VECTORIZED_SUPPORT_SCALARS_FOR_TERNARY_FUNC + +template +inline void convert(const src_T* src, dst_T* dst, int64_t n) { +#ifndef _MSC_VER +#pragma unroll +#endif + for ([[maybe_unused]] const auto i : c10::irange(n)) { + *dst = c10::convert(c10::load(src)); + src++; + dst++; + } +} + +template +inline Vectorized flip(const Vectorized& data) { + static constexpr int size = Vectorized::size(); + std::array output{}; + std::array buffer{}; + data.store(buffer.data()); + for (const auto i : c10::irange(size)) { + output[i] = buffer[size - i - 1]; + } + return Vectorized::loadu(output.data()); +} + +// Transpose the `src` buffer of type `T` and size (M,N) into the `dst` buffer. +// `ld_src` is the leading dimension of `src` and `ld_dst` is the leading +// dimension of `dst`. +template +inline void transpose_mxn( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst, + int M, + int N) { + for (int i = 0; i < M; i++) { + for (int j = 0; j < N; j++) { + dst[j * ld_dst + i] = src[i * ld_src + j]; + } + } +} + +template +inline void transpose_mxn( + const T* src, + int64_t ld_src, + T* dst, + int64_t ld_dst) { + transpose_mxn(src, ld_src, dst, ld_dst, M, N); +} + +inline std::ostream& operator<<(std::ostream& stream, const c10::qint32& val) { + stream << val.val_; + return stream; +} +inline std::ostream& operator<<(std::ostream& stream, const c10::qint8& val) { + stream << static_cast(val.val_); + return stream; +} +inline std::ostream& operator<<(std::ostream& stream, const c10::quint8& val) { + stream << static_cast(val.val_); + return stream; +} + +template +std::ostream& operator<<(std::ostream& stream, const Vectorized& vec) { + std::array::size()> buf{}; + vec.store(buf.data()); + stream << "vec["; + for (int i = 0; i != Vectorized::size(); i++) { + if (i != 0) { + stream << ", "; + } + stream << buf[i]; + } + stream << ']'; + return stream; +} + +} // namespace at::vec::inline CPU_CAPABILITY + +// additional headers for more operations that depend on vec_base +#include +#include +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_convert.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_convert.h new file mode 100644 index 0000000000000000000000000000000000000000..bc498837f6c6a11cbf3246fc72315323c8b856d1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_convert.h @@ -0,0 +1,157 @@ +#pragma once + +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + typename Enabled = void> +struct VecConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + constexpr int count = std::min( + VectorizedN::size(), VectorizedN::size()); + __at_align__ src_t src_buf[VectorizedN::size()]; + src.store(src_buf); + __at_align__ dst_t dst_buf[VectorizedN::size()]; + for (int i = 0; i < count; i++) { + dst_buf[i] = static_cast(src_buf[i]); + } + return VectorizedN::loadu(dst_buf, count); + } +}; + +// Specialized for float-to-int vector conversion. +// It ensures the result staying within the destination +// type's limits without any undefined behavior. +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + typename = + std::enable_if_t && is_floating_point_v>> +struct VecRoundConvert { + static inline VectorizedN apply( + const VectorizedN& src) { + constexpr int count = std::min( + VectorizedN::size(), VectorizedN::size()); + __at_align__ src_t src_buf[VectorizedN::size()]; + src.store(src_buf); + __at_align__ dst_t dst_buf[VectorizedN::size()]; + constexpr auto min_val = + static_cast(std::numeric_limits::min()); + constexpr auto max_val = + static_cast(std::numeric_limits::max()); + for (int i = 0; i < count; i++) { + dst_buf[i] = static_cast( + std::clamp(std::round(src_buf[i]), min_val, max_val)); + } + return VectorizedN::loadu(dst_buf, count); + } +}; + +template +struct VecConvert< + dst_t, + dst_n, + src_t, + src_n, + std::enable_if_t && dst_n == src_n>> { + static inline VectorizedN apply( + const VectorizedN& src) { + return src; + } +}; + +template +inline std::enable_if_t, Vectorized> convert( + const Vectorized& src) { + return src; +} + +template +inline std::enable_if_t, Vectorized> +round_convert(const Vectorized& src) { + return src; +} + +template +inline std::enable_if_t, Vectorized> +convert(const Vectorized& src) { + return VecConvert::apply(src); +} + +template +inline std::enable_if_t, Vectorized> +round_convert(const Vectorized& src) { + return VecRoundConvert::apply(src); +} + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + std::enable_if_t = 0> +inline VectorizedN convert(const VectorizedN& src) { + return VecConvert::apply(src); +} + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + std::enable_if_t = 0> +inline VectorizedN round_convert( + const VectorizedN& src) { + return VecRoundConvert::apply(src); +} + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + bool keep = false, + std::enable_if_t = 0> +inline std::conditional_t, Vectorized> +convert(const VectorizedN& src) { + return VecConvert::apply(src); +} + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + bool keep = false, + std::enable_if_t = 0> +inline std::conditional_t, Vectorized> +round_convert(const VectorizedN& src) { + return VecRoundConvert::apply(src); +} + +} // namespace CPU_CAPABILITY + +template < + typename scalar_t, + typename std::enable_if_t, int> = 0> +inline std::tuple, Vectorized> convert_to_float( + const Vectorized&); + +template < + typename scalar_t, + typename std::enable_if_t, int> = 0> +inline Vectorized convert_from_float( + const Vectorized&, + const Vectorized&); + +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_half.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_half.h new file mode 100644 index 0000000000000000000000000000000000000000..d7581acabf3d59ef1fd2d8a561b393203e9fbe56 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_half.h @@ -0,0 +1,118 @@ +#pragma once + +#include +#include + +#include + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +// Transpose a [2, 32] matrix to [32, 2] +// Note: the output leading dimension should be 2, +// that is, the output must be contiguous +template > +static inline void transpose_pad_2x32_block( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int krem = 2, + int nrem = 32) { +#if defined(CPU_CAPABILITY_AVX512) + __m512i r0, r1; + __m512i d0, d1; + // load + if (nrem < 32) { + __mmask32 mask_krem_v = (1LL << nrem) - 1; + r0 = _mm512_maskz_loadu_epi16(mask_krem_v, src); + // if krem is not 2, pad with zeros + if (krem == 2) { + r1 = _mm512_maskz_loadu_epi16(mask_krem_v, src + ld_src); + } else { + r1 = _mm512_setzero_si512(); + } + } else { + r0 = _mm512_loadu_si512(reinterpret_cast(src)); + if (krem == 2) { + r1 = _mm512_loadu_si512(reinterpret_cast(src + ld_src)); + } else { + r1 = _mm512_setzero_si512(); + } + } + // transpose + d0 = _mm512_unpacklo_epi16(r0, r1); + d1 = _mm512_unpackhi_epi16(r0, r1); + r0 = _mm512_shuffle_i32x4(d0, d1, 0x88); + r1 = _mm512_shuffle_i32x4(d0, d1, 0xdd); + d0 = _mm512_shuffle_i32x4(r0, r1, 0x88); + d1 = _mm512_shuffle_i32x4(r0, r1, 0xdd); + + // store + if (nrem < 16) { + __mmask32 mask_rem_v = (1LL << (nrem * 2)) - 1; + _mm512_mask_storeu_epi16(dst, mask_rem_v, d0); + } else if (nrem == 16) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), d0); + } else if (nrem < 32) { + __mmask32 mask_rem_v = (1LL << (nrem * 2 - 32)) - 1; + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), d0); + _mm512_mask_storeu_epi16( + reinterpret_cast<__m512i*>(dst + 32), mask_rem_v, d1); + } else { + // normal store + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), d0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 32), d1); + } +#else + TORCH_CHECK( + false, + "transpose_pad_2x32_block is only supported when avx512 is supported") +#endif +} + +// To use AMX to accelerate GEMM, +// reorder the memory format [K, N] -> [K/2, N, 2] +// Note: If K % 2 != 0, pad K implicitly +template > +static inline void pack_vnni2( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int64_t K, + int64_t N) { +#if defined(CPU_CAPABILITY_AVX512) + int64_t bk = 0; + int64_t _K = K / 2 * 2; + int64_t _N = N / 32 * 32; + for (; bk < _K; bk += 2) { + int64_t bn = 0; + for (; bn < _N; bn += 32) { + transpose_pad_2x32_block( + src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src); + } + int64_t nrem = N - bn; + if (nrem > 0) { + transpose_pad_2x32_block( + src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src, 2, nrem); + } + } + if (K % 2 == 1) { + int64_t bn = 0; + for (; bn < _N; bn += 32) { + transpose_pad_2x32_block( + src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src, 1); + } + int64_t nrem = N - bn; + if (nrem > 0) { + transpose_pad_2x32_block( + src + bk * ld_src + bn, dst + bk * N + bn * 2, ld_src, 1, nrem); + } + } +#else + TORCH_CHECK(false, "pack_vnni2 is only supported when avx512 is supported") +#endif +} + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_mask.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_mask.h new file mode 100644 index 0000000000000000000000000000000000000000..92f9322f8ce91fe442b638ffd04458a7170a2309 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_mask.h @@ -0,0 +1,319 @@ +#pragma once + +#include +#include +namespace at::vec { +inline namespace CPU_CAPABILITY { + +/** + * The `VecMask` class provides a convenient interface for working with + * vectorized masks in SIMD operations. It encapsulates a `Vectorized` + * mask that can be directly usable in masked vectorized operations. It provides + * various methods for manipulating and accessing the mask elements: + * 1. `from` and `to`: Conversion between a vector of boolean values and a + * vectorized mask. + * 2. `cast`: Casts the mask to a different base type. + * 3. `all_zero`: Checks if all mask elements are zero. + * 4. `is_masked`: Checks if a specific element is masked. + * 5. `loadu`: Loads data from memory using the mask. + * 6. `all_masked`: Checks if all mask elements are masked. + * + * Some helper template classes are provided to simplify the specialization of + * the `VecMask` for the specific CPU arch: + * 1. `VecMaskLoad`: Loads data from memory using the mask. + * 2. `VecMaskTo`: Converts the mask to boolean. + * 3. `VecMaskCast`: Casts the mask to a different base type. + * + */ +template +class VecMask; + +template < + typename data_t, + int data_n, + typename mask_t, + int mask_n, + typename Enabled = void> +struct VecMaskLoad { + static inline VectorizedN apply( + const data_t* ptr, + const VecMask& vec_mask) { + constexpr typename VecMask::size_type size = + VecMask::size(); + static_assert(VectorizedN::size() >= size); + __at_align__ data_t data[size]; + __at_align__ mask_t mask[size]; + auto mask_ = VectorizedN(vec_mask); + mask_.store(mask); + for (int i = 0; i < size; i++) { + data[i] = mask[i] ? ptr[i] : static_cast(0); + } + return VectorizedN::loadu(data, size); + } +}; + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + typename Enabled = void> +struct VecMaskTo { + static inline VecMask apply( + const VecMask& vec_mask) { + auto zeros = VectorizedN(static_cast(0)); + auto ones = VectorizedN(static_cast(1)); + return VectorizedN::blendv( + zeros, ones, vec_mask.template cast()); + } +}; + +template < + typename dst_t, + int dst_n, + typename src_t, + int src_n, + typename Enabled = void> +struct VecMaskCast { + static inline VecMask apply( + const VecMask& vec_mask) { + return VecMask::from(VectorizedN(vec_mask)); + } +}; + +template +struct VecMaskCast { + static inline VecMask apply(const VecMask& vec_mask) { + return vec_mask; + } +}; + +template +struct VecMaskCheck { + static inline bool all_zero(const VectorizedN& vec_mask) { + __at_align__ T mask[VectorizedN::size()]; + vec_mask.store(mask); + return std::all_of(mask, mask + VectorizedN::size(), [](T m) { + return m == static_cast(0); + }); + } + + static inline bool all_masked(const VectorizedN& vec_mask) { + __at_align__ T mask[VectorizedN::size()]; + vec_mask.store(mask); + return std::all_of(mask, mask + VectorizedN::size(), [](T m) { + return m != static_cast(0); + }); + } + + static inline bool is_masked(const VectorizedN& vec_mask, int i) { + __at_align__ T mask[VectorizedN::size()]; + vec_mask.store(mask); + return mask[i] != static_cast(0); + } +}; + +template +class VecMask { + public: + using size_type = int; + static constexpr size_type size() { + return VectorizedN::size(); + } + + private: + VectorizedN mask_; + + template + constexpr static T value_to_mask(U b) { + if constexpr (std::is_same_v) { + return static_cast(b); + } else { + using int_t = int_same_size_t; + return b ? c10::bit_cast(static_cast(-1)) : static_cast(0); + } + } + + public: + VecMask() : mask_(static_cast(0)) {} + VecMask(const VectorizedN& mask) : mask_(mask) {} + + template = 0> + VecMask(const Vectorized& mask) : mask_(mask) {} + + template + static VecMask from(const VectorizedN& b_vec) { + __at_align__ U b_buf[size()]; + if constexpr (size() >= VectorizedN::size()) { + b_vec.store(b_buf); + for (int i = VectorizedN::size(); i < size(); i++) { + b_buf[i] = static_cast(0); + } + } else { + b_vec.store(b_buf, size()); + } + return from(b_buf); + } + + template + static VecMask from(U b) { + return VectorizedN(value_to_mask(b)); + } + + template + static VecMask from(U* b) { + __at_align__ T mask[size()]; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (int i = 0; i < size(); i++) { + mask[i] = value_to_mask(b[i]); + } + return VectorizedN(VectorizedN::loadu(mask)); + } + + template + static VecMask from(U* b, int count) { + __at_align__ T mask[size()]; +#ifndef __msvc_cl__ +#pragma unroll +#endif + for (int i = 0; i < count; i++) { + mask[i] = value_to_mask(b[i]); + } + return VectorizedN(VectorizedN::loadu(mask, count)); + } + + static VecMask blendv( + const VecMask& c, + const VecMask& b, + const VecMask& a) { + VectorizedN result = VectorizedN::blendv( + VectorizedN(c), VectorizedN(b), VectorizedN(a)); + return result; + } + + static VecMask set( + const VecMask& a, + const VecMask& b, + int64_t count = size()) { + VectorizedN result = VectorizedN::set( + VectorizedN(a), VectorizedN(b), count); + return result; + } + + void store(bool* b, int count = size()) { + constexpr int L = + (VectorizedN::size() + Vectorized::size() - 1) / + Vectorized::size(); + auto res = this->to(); + res.store(b, count); + return; + } + + template = 2, int> = 0> + inline VectorizedN to() const { + return VecMaskTo::apply(*this); + } + + template = 0> + inline Vectorized to() const { + return VecMaskTo::apply(*this); + } + + template + inline VecMask cast() const { + return VecMaskCast::apply(*this); + } + + inline bool all_zero() const { + return VecMaskCheck::all_zero(mask_); + } + + inline bool all_masked() const { + return VecMaskCheck::all_masked(mask_); + } + + inline bool is_masked(int i) const { + return VecMaskCheck::is_masked(mask_, i); + } + + inline operator VectorizedN() const { + return mask_; + } + + template = 0> + inline operator Vectorized() const { + return mask_[0]; + } + + inline Vectorized operator[](int i) const { + return mask_[i]; + } + + template < + typename U, + int L, + std::enable_if_t= 2 && VectorizedN::size() >= size(), int> = 0> + VectorizedN loadu(const U* ptr) const { + return VecMaskLoad::apply(ptr, *this); + } + + template < + typename U, + int L, + std::enable_if_t::size() >= size(), int> = 0> + Vectorized loadu(const U* ptr) const { + return VecMaskLoad::apply(ptr, *this); + } +}; + +#define VEC_MASK_DEFINE_UNARY_OP_GLOBAL(op) \ + template \ + inline VecMask op(const VecMask& a) { \ + return op(VectorizedN(a)); \ + } + +#define VEC_MASK_DEFINE_BINARY_OP_GLOBAL(op) \ + template < \ + typename T, \ + int N, \ + typename V, \ + int M, \ + std::enable_if_t::size() == VecMask::size(), int> = \ + 0> \ + inline VecMask op(const VecMask& a, const VecMask& b) { \ + return op( \ + VectorizedN(a), VectorizedN(b.template cast())); \ + } + +#define VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(op, EXPR) \ + template < \ + typename T, \ + int N, \ + typename V, \ + int M, \ + std::enable_if_t::size() == VecMask::size(), int> = \ + 0> \ + inline VecMask op(const VecMask& a, const VecMask& b) { \ + return EXPR; \ + } + +VEC_MASK_DEFINE_UNARY_OP_GLOBAL(operator~) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator&) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator|) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator^) +VEC_MASK_DEFINE_BINARY_OP_GLOBAL(operator*) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator>, a & ~b) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator<, ~a& b) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator==, ~(a ^ b)) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator>=, (a == b) | (a > b)) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator<=, (a == b) | (a < b)) +VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL(operator!=, (a ^ b)) + +#undef VEC_MASK_DEFINE_UNARY_OP_GLOBAL +#undef VEC_MASK_DEFINE_BINARY_OP_GLOBAL +#undef VEC_MASK_DEFINE_BINARY_OP_WITH_EXPR_GLOBAL + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_n.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_n.h new file mode 100644 index 0000000000000000000000000000000000000000..ff72d41ec5d8fdebd15ec06bd656842b50c865f5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_n.h @@ -0,0 +1,407 @@ +#pragma once + +#include +#include + +namespace at::vec { +inline namespace CPU_CAPABILITY { + +/** + * @brief A class template representing a vectorized type with + * `N * Vectorized::size()` elements, aiming to support vectors of + * arbitrary size. A specific use case of it is to represent vectors + * converted from data types with different sizes but with the same + * number of vector elements, e.g., `VectorizedN` can be + * a vector converted from two `Vectorized`, `VectorizedN` + * can be a vector converted from two `Vectorized` etc. + * + * It supports most of the operations of `Vectorized` + * and the implementation delegates to `Vectorized` with loops over `N`. + * + * @tparam T The underlying type of the vectorized elements. + * @tparam N The number of underlying `Vectorized`. + */ +template +class VectorizedN { + public: + using value_type = T; + using size_type = int; + + static constexpr size_type size_T = sizeof(T); + static constexpr size_type size() { + return Vectorized::size() * N; + } + + private: + std::array, N> values; + + public: + // methods not implemented yet: + // variadic constructor, operator T*, as_bytes, zero_mask + +#define VECTORIZEDN_DEFINE_UNARY_OP(op) \ + VectorizedN op() const { \ + return unary_op([](const Vectorized& a) { return a.op(); }); \ + } + +#define VECTORIZEDN_DEFINE_BINARY_OP(op) \ + VectorizedN op(const VectorizedN& other) const { \ + return binary_op( \ + other, [](const Vectorized& a, const Vectorized& b) { \ + return a.op(b); \ + }); \ + } + + template + inline VectorizedN unary_op(Op op) const { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result.values[i] = op(values[i]); + } + return result; + } + + template + inline VectorizedN binary_op(const VectorizedN& other, Op op) + const { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result.values[i] = op(values[i], other.values[i]); + } + return result; + } + + template + inline VectorizedN ternary_op( + const VectorizedN& other, + const VectorizedN& other2, + Op op) const { + VectorizedN result; +#ifndef _MSC_VER +#pragma unroll +#endif + for (int i = 0; i < N; ++i) { + result.values[i] = op(values[i], other.values[i], other2.values[i]); + } + return result; + } + + VectorizedN() = default; + + explicit VectorizedN(T val) { + for (int i = 0; i < N; ++i) { + values[i] = Vectorized(val); + } + } + + template = 0> + VectorizedN(const Vectorized& val) : values({val}) {} + + template = 0> + VectorizedN(const Vectorized& val_0, const Vectorized& val_1) + : values({val_0, val_1}) {} + + template = 0> + inline operator Vectorized() const { + return values[0]; + } + + inline const Vectorized& operator[](int i) const { + return values[i]; + } + + inline Vectorized& operator[](int i) { + return values[i]; + } + + template + static VectorizedN blend( + const VectorizedN& a, + const VectorizedN& b) { + VectorizedN result; + for (int i = 0; i < N; ++i) { + result.values[i] = + Vectorized::template blend(a.values[i], b.values[i]); + } + return result; + } + + static VectorizedN blendv( + const VectorizedN& a, + const VectorizedN& b, + const VectorizedN& mask) { + VectorizedN result; + for (int i = 0; i < N; ++i) { + result.values[i] = + Vectorized::blendv(a.values[i], b.values[i], mask.values[i]); + } + return result; + } + + template + static VectorizedN arange( + T base = static_cast(0), + step_t step = static_cast(1)) { + VectorizedN result; + for (int i = 0; i < N; ++i) { + result.values[i] = Vectorized::arange(base, step); + base += step * Vectorized::size(); + } + return result; + } + + static VectorizedN set( + const VectorizedN& a, + const VectorizedN& b, + int64_t count = size()) { + VectorizedN result; + for (int i = 0; i < N; ++i) { + if (count > 0) { + result.values[i] = Vectorized::set( + a.values[i], + b.values[i], + std::min(count, (int64_t)Vectorized::size())); + count -= Vectorized::size(); + } else { + result.values[i] = a.values[i]; + } + } + return result; + } + + static VectorizedN loadu(const void* ptr) { + VectorizedN result; + for (int i = 0; i < N; ++i) { + result.values[i] = Vectorized::loadu(ptr); + ptr = static_cast(ptr) + Vectorized::size(); + } + return result; + } + + static VectorizedN loadu(const void* ptr, int64_t count) { + VectorizedN result; + for (int i = 0; i < N; ++i) { + if (count > 0) { + result.values[i] = Vectorized::loadu( + ptr, std::min(count, (int64_t)Vectorized::size())); + ptr = static_cast(ptr) + Vectorized::size(); + count -= Vectorized::size(); + } else { + result.values[i] = Vectorized((T)1); + } + } + return result; + } + + void store(void* ptr) const { + for (int i = 0; i < N; ++i) { + values[i].store(ptr); + ptr = static_cast(ptr) + Vectorized::size(); + } + } + + void store(void* ptr, int count) const { + for (int i = 0; i < N; ++i) { + values[i].store(ptr, std::min(count, (int)Vectorized::size())); + ptr = static_cast(ptr) + Vectorized::size(); + count -= Vectorized::size(); + if (count <= 0) { + break; + } + } + } + + bool has_inf_nan() const { + for (int i = 0; i < N; ++i) { + if (values[i].has_inf_nan()) { + return true; + } + } + return false; + } + + VectorizedN map(T (*const f)(T)) const { + VectorizedN result; + for (int i = 0; i < N; ++i) { + result.values[i] = values[i].map(f); + } + return result; + } + + VectorizedN map(T (*const f)(const T&)) const { + VectorizedN result; + for (int i = 0; i < N; ++i) { + result.values[i] = values[i].map(f); + } + return result; + } + + VECTORIZEDN_DEFINE_UNARY_OP(isnan) + VECTORIZEDN_DEFINE_UNARY_OP(abs) + VECTORIZEDN_DEFINE_UNARY_OP(sgn) + VECTORIZEDN_DEFINE_UNARY_OP(angle) + VECTORIZEDN_DEFINE_UNARY_OP(real) + VECTORIZEDN_DEFINE_UNARY_OP(imag) + VECTORIZEDN_DEFINE_UNARY_OP(conj) + VECTORIZEDN_DEFINE_UNARY_OP(acos) + VECTORIZEDN_DEFINE_UNARY_OP(acosh) + VECTORIZEDN_DEFINE_UNARY_OP(asin) + VECTORIZEDN_DEFINE_UNARY_OP(asinh) + VECTORIZEDN_DEFINE_UNARY_OP(atan) + VECTORIZEDN_DEFINE_UNARY_OP(atanh) + VECTORIZEDN_DEFINE_BINARY_OP(atan2) + VECTORIZEDN_DEFINE_BINARY_OP(copysign) + VECTORIZEDN_DEFINE_UNARY_OP(erf) + VECTORIZEDN_DEFINE_UNARY_OP(erfc) + VECTORIZEDN_DEFINE_UNARY_OP(erfinv) + VECTORIZEDN_DEFINE_UNARY_OP(exp) + VECTORIZEDN_DEFINE_UNARY_OP(exp2) + VECTORIZEDN_DEFINE_UNARY_OP(expm1) + VECTORIZEDN_DEFINE_UNARY_OP(exp_u20) + VECTORIZEDN_DEFINE_UNARY_OP(fexp_u20) + VECTORIZEDN_DEFINE_UNARY_OP(frac) + VECTORIZEDN_DEFINE_BINARY_OP(fmod) + VECTORIZEDN_DEFINE_UNARY_OP(log) + VECTORIZEDN_DEFINE_UNARY_OP(log10) + VECTORIZEDN_DEFINE_UNARY_OP(log1p) + VECTORIZEDN_DEFINE_UNARY_OP(log2) + VECTORIZEDN_DEFINE_UNARY_OP(ceil) + VECTORIZEDN_DEFINE_UNARY_OP(cos) + VECTORIZEDN_DEFINE_UNARY_OP(cosh) + VECTORIZEDN_DEFINE_UNARY_OP(floor) + VECTORIZEDN_DEFINE_BINARY_OP(hypot) + VECTORIZEDN_DEFINE_UNARY_OP(i0) + VECTORIZEDN_DEFINE_UNARY_OP(i0e) + VECTORIZEDN_DEFINE_UNARY_OP(digamma) + VECTORIZEDN_DEFINE_BINARY_OP(igamma) + VECTORIZEDN_DEFINE_BINARY_OP(igammac) + VECTORIZEDN_DEFINE_UNARY_OP(neg) + VECTORIZEDN_DEFINE_BINARY_OP(nextafter) + VECTORIZEDN_DEFINE_UNARY_OP(round) + VECTORIZEDN_DEFINE_UNARY_OP(sin) + VECTORIZEDN_DEFINE_UNARY_OP(sinh) + VECTORIZEDN_DEFINE_UNARY_OP(tan) + VECTORIZEDN_DEFINE_UNARY_OP(tanh) + VECTORIZEDN_DEFINE_UNARY_OP(trunc) + VECTORIZEDN_DEFINE_UNARY_OP(lgamma) + VECTORIZEDN_DEFINE_UNARY_OP(sqrt) + VECTORIZEDN_DEFINE_UNARY_OP(reciprocal) + VECTORIZEDN_DEFINE_UNARY_OP(rsqrt) + VECTORIZEDN_DEFINE_BINARY_OP(pow) + VECTORIZEDN_DEFINE_BINARY_OP(operator==) + VECTORIZEDN_DEFINE_BINARY_OP(operator!=) + VECTORIZEDN_DEFINE_BINARY_OP(operator>=) + VECTORIZEDN_DEFINE_BINARY_OP(operator<=) + VECTORIZEDN_DEFINE_BINARY_OP(operator>) + VECTORIZEDN_DEFINE_BINARY_OP(operator<) + VECTORIZEDN_DEFINE_BINARY_OP(eq) + VECTORIZEDN_DEFINE_BINARY_OP(ne) + VECTORIZEDN_DEFINE_BINARY_OP(gt) + VECTORIZEDN_DEFINE_BINARY_OP(ge) + VECTORIZEDN_DEFINE_BINARY_OP(lt) + VECTORIZEDN_DEFINE_BINARY_OP(le) + +#undef VECTORIZEDN_DEFINE_UNARY_OP +#undef VECTORIZEDN_DEFINE_BINARY_OP +}; + +#define VECTORIZEDN_DEFINE_UNARY_OP_GLOBAL(op) \ + template \ + inline VectorizedN op(const VectorizedN& a) { \ + return a.unary_op([](const Vectorized& a) { return op(a); }); \ + } + +#define VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(op) \ + template \ + inline VectorizedN op( \ + const VectorizedN& a, const VectorizedN& b) { \ + return a.binary_op(b, [](const Vectorized& a, const Vectorized& b) { \ + return op(a, b); \ + }); \ + } + +#define VECTORIZEDN_DEFINE_TERNARY_OP_GLOBAL(op) \ + template \ + inline VectorizedN op( \ + const VectorizedN& a, \ + const VectorizedN& b, \ + const VectorizedN& c) { \ + return a.ternary_op( \ + b, \ + c, \ + [](const Vectorized& a, \ + const Vectorized& b, \ + const Vectorized& c) { return op(a, b, c); }); \ + } + +#define VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(op) \ + template \ + inline VectorizedN& op( \ + VectorizedN& a, const VectorizedN& b) { \ + a = a.binary_op(b, [](const Vectorized& a, const Vectorized& b) { \ + return op(a, b); \ + }); \ + return a; \ + } + +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator+) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator-) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator*) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator/) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator%) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator||) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator<<) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator>>) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(maximum) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(minimum) +VECTORIZEDN_DEFINE_TERNARY_OP_GLOBAL(fmadd) +VECTORIZEDN_DEFINE_TERNARY_OP_GLOBAL(fmsub) +VECTORIZEDN_DEFINE_TERNARY_OP_GLOBAL(clamp) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(clamp_max) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(clamp_min) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator&) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator|) +VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL(operator^) +VECTORIZEDN_DEFINE_UNARY_OP_GLOBAL(operator~) + +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator+=) +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator-=) +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator*=) +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator/=) +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator%=) +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator<<=) +VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL(operator>>=) + +#undef VECTORIZEDN_DEFINE_UNARY_OP_GLOBAL +#undef VECTORIZEDN_DEFINE_BINARY_OP_GLOBAL +#undef VECTORIZEDN_DEFINE_BINARY_OP_INPLACE_GLOBAL + +template +inline T vec_reduce_all(const OpVec& vec_fun, VectorizedN acc_vec) { + Vectorized vec_result = acc_vec[0]; + for (int i = 1; i < N; i++) { + vec_result = vec_fun(vec_result, acc_vec[i]); + } + return vec_reduce_all(vec_fun, vec_result); +} + +template +std::ostream& operator<<(std::ostream& stream, const VectorizedN& vec_n) { + stream << "vec_n["; + for (int i = 0; i < N; ++i) { + if (i != 0) { + stream << ", "; + } + stream << vec_n[i]; + } + stream << ']'; + return stream; +} +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_quant.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_quant.h new file mode 100644 index 0000000000000000000000000000000000000000..fe763aa2615f2b06f3303abe09c2216f8587c02c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vec/vec_quant.h @@ -0,0 +1,253 @@ +#pragma once + +#include +#include + +namespace at::vec { +// See Note [CPU_CAPABILITY namespace] +inline namespace CPU_CAPABILITY { + +// Transpose a [4, 64] block to [64, 4] (with contiguous output, ld=4) +template > +static inline void transpose_pad_4x64_block( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int krem = 4, + int nrem = 64) { +#if defined(CPU_CAPABILITY_AVX512) + __m512i r[4]; + // Load with mask if partial + if (nrem < 64) { + __mmask64 mask = (1ULL << nrem) - 1; + for (int i = 0; i < krem; ++i) { + r[i] = _mm512_maskz_loadu_epi8(mask, src + i * ld_src); + } + for (int i = krem; i < 4; ++i) { + r[i] = _mm512_setzero_si512(); + } + } else { + for (int i = 0; i < krem; ++i) { + r[i] = _mm512_loadu_si512( + reinterpret_cast(src + i * ld_src)); + } + for (int i = krem; i < 4; ++i) { + r[i] = _mm512_setzero_si512(); + } + } + + // Transpose 4x64 bytes using unpack and shuffle + __m512i t0 = _mm512_unpacklo_epi8(r[0], r[1]); + __m512i t1 = _mm512_unpackhi_epi8(r[0], r[1]); + __m512i t2 = _mm512_unpacklo_epi8(r[2], r[3]); + __m512i t3 = _mm512_unpackhi_epi8(r[2], r[3]); + + __m512i u0 = _mm512_unpacklo_epi16(t0, t2); + __m512i u1 = _mm512_unpackhi_epi16(t0, t2); + __m512i u2 = _mm512_unpacklo_epi16(t1, t3); + __m512i u3 = _mm512_unpackhi_epi16(t1, t3); + + __m512i v0 = _mm512_shuffle_i32x4(u0, u1, 0x88); + __m512i v1 = _mm512_shuffle_i32x4(u0, u1, 0xdd); + __m512i v2 = _mm512_shuffle_i32x4(u2, u3, 0x88); + __m512i v3 = _mm512_shuffle_i32x4(u2, u3, 0xdd); + + __m512i r0 = _mm512_shuffle_i32x4(v0, v2, 0x88); + __m512i r1 = _mm512_shuffle_i32x4(v1, v3, 0x88); + __m512i r2 = _mm512_shuffle_i32x4(v0, v2, 0xdd); + __m512i r3 = _mm512_shuffle_i32x4(v1, v3, 0xdd); + + // Store output + if (nrem < 16) { + __mmask64 mask = (1ULL << (nrem * 4)) - 1; + _mm512_mask_storeu_epi8(dst, mask, r0); + } else if (nrem == 16) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + } else if (nrem < 32) { + int n_bytes1 = 64; + int n_bytes2 = (nrem * 4) - n_bytes1; + __mmask64 mask = (1ULL << n_bytes2) - 1; + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + _mm512_mask_storeu_epi8(reinterpret_cast<__m512i*>(dst + 64), mask, r1); + } else if (nrem == 32) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64), r1); + } else if (nrem < 48) { + int n_bytes1 = 64 * 2; + int n_bytes2 = (nrem * 4) - n_bytes1; + __mmask64 mask = (1ULL << n_bytes2) - 1; + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64), r1); + _mm512_mask_storeu_epi8(reinterpret_cast<__m512i*>(dst + 64 * 2), mask, r2); + } else if (nrem == 48) { + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64), r1); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64 * 2), r2); + } else if (nrem < 64) { + int n_bytes1 = 64 * 3; + int n_bytes2 = (nrem * 4) - n_bytes1; + __mmask64 mask = (1ULL << n_bytes2) - 1; + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64), r1); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64 * 2), r2); + _mm512_mask_storeu_epi8(reinterpret_cast<__m512i*>(dst + 64 * 3), mask, r3); + } else { + // normal case, nrem == 64 + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst), r0); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64), r1); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64 * 2), r2); + _mm512_storeu_si512(reinterpret_cast<__m512i*>(dst + 64 * 3), r3); + } +#else + TORCH_CHECK( + false, + "transpose_pad_4x64_block is only supported when AVX-512 is supported") +#endif +} + +// Reorder [K, N] → [K/4, N, 4] (VNNI4-style layout for bit8) +template > +static inline void pack_vnni4( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int64_t K, + int64_t N) { +#if defined(CPU_CAPABILITY_AVX512) + int64_t bk = 0; + int64_t _K = K / 4 * 4; + int64_t _N = N / 64 * 64; + for (; bk < _K; bk += 4) { + int64_t bn = 0; + for (; bn < _N; bn += 64) { + transpose_pad_4x64_block( + src + bk * ld_src + bn, dst + bk * N + bn * 4, ld_src); + } + int64_t nrem = N - bn; + if (nrem > 0) { + transpose_pad_4x64_block( + src + bk * ld_src + bn, dst + bk * N + bn * 4, ld_src, 4, nrem); + } + } + + // Handle leftover K rows (< 4) + if (K % 4 != 0) { + int krem = K - bk; + int64_t bn = 0; + for (; bn < _N; bn += 64) { + transpose_pad_4x64_block( + src + bk * ld_src + bn, dst + bk * N + bn * 4, ld_src, krem); + } + int64_t nrem = N - bn; + if (nrem > 0) { + transpose_pad_4x64_block( + src + bk * ld_src + bn, dst + bk * N + bn * 4, ld_src, krem, nrem); + } + } +#else + TORCH_CHECK(false, "pack_vnni4 is only supported when AVX-512 is supported") +#endif +} + +// This is a helper function for transpose_pack_vnni4 +// Transform a [4, 16] block (with incontiguous output) +// Src: +// a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 +// b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 +// c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 +// d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 +// Dst: +// a1 a2 a3 a4 b1 b2 b3 b4 c1 c2 c3 c4 d1 d2 d3 d4 +// a5 a6 a7 a8 b5 b6 b7 b8 c5 c6 c7 c8 d5 d6 d7 d8 +// a9 a10 a11 a12 b9 b10 b11 b12 c9 c10 c11 c12 d9 d10 d11 d12 +// a13 a14 a15 a16 b13 b14 b15 b16 c13 c14 c15 c16 d13 d14 d15 d16 +template > +static inline void transpose_vnni4_pad_4x16_block( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int64_t ld_dst, + int krem = 4) { +#if defined(CPU_CAPABILITY_AVX512) + __m128i r[4]; + for (int i = 0; i < krem; ++i) { + r[i] = _mm_loadu_si128(reinterpret_cast(src + i * ld_src)); + } + for (int i = krem; i < 4; ++i) { + r[i] = _mm_setzero_si128(); + } + + // Transpose 4x16 bytes using unpack and shuffle + __m128i t0 = _mm_unpacklo_epi32(r[0], r[1]); + __m128i t1 = _mm_unpackhi_epi32(r[0], r[1]); + __m128i t2 = _mm_unpacklo_epi32(r[2], r[3]); + __m128i t3 = _mm_unpackhi_epi32(r[2], r[3]); + + __m128i r0 = _mm_unpacklo_epi64(t0, t2); + __m128i r1 = _mm_unpackhi_epi64(t0, t2); + __m128i r2 = _mm_unpacklo_epi64(t1, t3); + __m128i r3 = _mm_unpackhi_epi64(t1, t3); + + // Store output + if (krem == 4) { + // normal case + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), r0); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + ld_dst), r1); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + ld_dst * 2), r2); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + ld_dst * 3), r3); + } else { + // masked case + __mmask16 mask = (1ULL << (krem * 4)) - 1; + _mm_mask_storeu_epi8(dst, mask, r0); + _mm_mask_storeu_epi8(reinterpret_cast<__m128i*>(dst + ld_dst), mask, r1); + _mm_mask_storeu_epi8( + reinterpret_cast<__m128i*>(dst + ld_dst * 2), mask, r2); + _mm_mask_storeu_epi8( + reinterpret_cast<__m128i*>(dst + ld_dst * 3), mask, r3); + } +#else + TORCH_CHECK( + false, + "transpose_vnni4_pad_4x16_block is only supported when AVX-512 is supported") +#endif +} + +// Do the transpose packing fusion with VNNI4 +// Reorder [K, N] → [N/4, K, 4] (VNNI4-style layout for bit8) +template > +static inline void transpose_pack_vnni4( + const scalar_t* src, + scalar_t* dst, + int64_t ld_src, + int64_t K, + int64_t N) { +#if defined(CPU_CAPABILITY_AVX512) + TORCH_CHECK( + N % 16 == 0, "N needs to be multiple of 16 for transpose_pack_vnni4"); + int64_t bk = 0; + int64_t _K = K / 4 * 4; + for (; bk < _K; bk += 4) { + int64_t bn = 0; + for (; bn < N; bn += 16) { + transpose_vnni4_pad_4x16_block( + src + bk * ld_src + bn, dst + bn * K + bk * 4, ld_src, K * 4); + } + } + + // Handle leftover K rows (< 4) + if (K % 4 != 0) { + int krem = K - bk; + int64_t bn = 0; + for (; bn < N; bn += 16) { + transpose_vnni4_pad_4x16_block( + src + bk * ld_src + bn, dst + bn * K + bk * 4, ld_src, K * 4, krem); + } + } +#else + TORCH_CHECK( + false, "transpose_pack_vnni4 is only supported when AVX-512 is supported") +#endif +} + +} // namespace CPU_CAPABILITY +} // namespace at::vec diff --git a/western_ai/usa/pytorch/aten/src/ATen/cpu/vml.h b/western_ai/usa/pytorch/aten/src/ATen/cpu/vml.h new file mode 100644 index 0000000000000000000000000000000000000000..6c069c85573658d2730b4f1cc852774ee72584de --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cpu/vml.h @@ -0,0 +1,170 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +// This header implements various unary operations using a MKL VML style +// interface. + +// It implements various functions with a simple interface +// For example it enables the user to call vsin(float* out, const float* in, +// size) This functions takes a pointer to a continuous output array of floats and +// a constant input array. It will then apply sin to each value in the input +// array and write the result into the output array. out and in may point to the +// same memory, i.e. this fully supports in-place operations. These functions +// also implement their own parallelization, so take precautions when calling +// these from threaded functions. + +// When MKL is available it will call into MKL's VML library similar to NumPy +// If MKL is not available it will use SLEEF. + +// This file might be compiled under AVX or AVX2 when called from e.g. +// UnaryOpsKernel.cpp + +#include +#include +#include +#include +#include + +#if AT_MKL_ENABLED() && !defined(__APPLE__) +#include +#endif + + +namespace at::vml { +inline namespace CPU_CAPABILITY { + +using namespace vec; + +template +inline void vrsqrt(scalar_t* out, scalar_t* in, int64_t size) { + parallel_for(0, size, 2048, [out, in](int64_t begin, int64_t end) { + map( + [](const Vectorized& x) { + return Vectorized((scalar_t)1) / x.sqrt(); + }, + out + begin, + in + begin, + end - begin); + }); +} + +// NB: We ignore numerical errors by convention and leave them to the user + +#define IMPLEMENT_VML(op) \ + template \ + inline void v##op(scalar_t* out, const scalar_t* in, int64_t size) { \ + using vec_t = Vectorized>; \ + vec::map([](vec_t x) { return x.op(); }, out, in, size); \ + } \ + +IMPLEMENT_VML(abs) +IMPLEMENT_VML(acos) +IMPLEMENT_VML(asin) +IMPLEMENT_VML(atan) +IMPLEMENT_VML(atanh) +IMPLEMENT_VML(ceil) +IMPLEMENT_VML(cos) +// IMPLEMENT_VML(cosh) +IMPLEMENT_VML(erf) +IMPLEMENT_VML(erfc) +IMPLEMENT_VML(erfinv) +IMPLEMENT_VML(exp) +IMPLEMENT_VML(expm1) +IMPLEMENT_VML(floor) +IMPLEMENT_VML(i0) +IMPLEMENT_VML(i0e) +IMPLEMENT_VML(digamma) +IMPLEMENT_VML(reciprocal) +IMPLEMENT_VML(log) +IMPLEMENT_VML(log10) +IMPLEMENT_VML(log1p) +IMPLEMENT_VML(log2) +IMPLEMENT_VML(neg) +IMPLEMENT_VML(sin) +// IMPLEMENT_VML(sinh) +IMPLEMENT_VML(sqrt) +IMPLEMENT_VML(round) +IMPLEMENT_VML(rsqrt) +IMPLEMENT_VML(tan) +IMPLEMENT_VML(tanh) +IMPLEMENT_VML(trunc) +IMPLEMENT_VML(lgamma) + + +#if AT_MKL_ENABLED() && !defined(__APPLE__) + +// NB: LP64 MKL is the most commonly used and thus we assume it here. That means +// we need to expect MKL_INT to be of type int, which implies int32_t or int64_t in most +// cases. +static_assert( + std::is_same_v || std::is_same_v, + "MKL_INT is assumed to be int32_t or int64_t"); +#define IMPLEMENT_VML_MKL_STUB(op, mklop, type, mkltype) \ + template <> \ + inline void v##op(type * out, const type * in, int64_t size) { \ + auto constexpr max_mkl_ind = std::numeric_limits::max(); \ + if (size <= static_cast(max_mkl_ind)) { \ + vm##mkltype##mklop( \ + size, in, out, VML_HA | VML_FTZDAZ_OFF | VML_ERRMODE_IGNORE); \ + } else { \ + int64_t ind = 0; \ + int64_t chunks = size / max_mkl_ind; \ + int64_t rest = size % max_mkl_ind; \ + for (; ind < chunks; ind++) { \ + vm##mkltype##mklop( \ + max_mkl_ind, \ + in + ind * max_mkl_ind, \ + out + ind * max_mkl_ind, \ + VML_HA | VML_FTZDAZ_OFF | VML_ERRMODE_IGNORE); \ + } \ + vm##mkltype##mklop( \ + rest, \ + in + ind * max_mkl_ind, \ + out + ind * max_mkl_ind, \ + VML_HA | VML_FTZDAZ_OFF | VML_ERRMODE_IGNORE); \ + } \ + } + +#define IMPLEMENT_VML_MKL(op, mklop) \ + IMPLEMENT_VML_MKL_STUB(op, mklop, float, s) \ + IMPLEMENT_VML_MKL_STUB(op, mklop, double, d) + +// NB: abs, cosh and sinh were temporarily disabled due to issues with Apple +// NB: expm1 is disabled because on some configs it produces expm1(nan)=-1 +IMPLEMENT_VML_MKL(acos, Acos) +IMPLEMENT_VML_MKL(asin, Asin) +IMPLEMENT_VML_MKL(atan, Atan) +IMPLEMENT_VML_MKL(cos, Cos) +// IMPLEMENT_VML_MKL(cosh, Cosh) +IMPLEMENT_VML_MKL(erf, Erf) +IMPLEMENT_VML_MKL(erfc, Erfc) +IMPLEMENT_VML_MKL(erfinv, ErfInv) +IMPLEMENT_VML_MKL(exp, Exp) +// IMPLEMENT_VML_MKL(expm1, Expm1) +IMPLEMENT_VML_MKL(log, Ln) +IMPLEMENT_VML_MKL(log10, Log10) +IMPLEMENT_VML_MKL(sin, Sin) +// IMPLEMENT_VML_MKL(sinh, Sinh) +IMPLEMENT_VML_MKL(sqrt, Sqrt) +IMPLEMENT_VML_MKL(tan, Tan) +IMPLEMENT_VML_MKL(tanh, Tanh) +IMPLEMENT_VML_MKL(trunc, Trunc) + +// Not vectorized in MKL version tested +// IMPLEMENT_VML_MKL(abs, Abs) +// IMPLEMENT_VML_MKL(log1p, Log1p) + +#if INTEL_MKL_VERSION >= 20180406 +IMPLEMENT_VML_MKL(log2, Log2) +#endif + +#endif + +} // namespace +} // namespace at::vml diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/ATenCUDAGeneral.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/ATenCUDAGeneral.h new file mode 100644 index 0000000000000000000000000000000000000000..3938aa341bb3943a9e42a3178d3233868b755101 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/ATenCUDAGeneral.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include +#include + +#include + +// Use TORCH_CUDA_CPP_API or TORCH_CUDA_CU_API for exports from this folder diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/ApplyGridUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/ApplyGridUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..b67b0905a09fd2a1bb17f7cc69863fd849ded1ff --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/ApplyGridUtils.cuh @@ -0,0 +1,47 @@ +#include + +#include + +namespace at::cuda { + +/** + Computes ceil(a / b) +*/ +template +__host__ __device__ __forceinline__ T ATenCeilDiv(T a, T b) { + return (a + b - 1) / b; +} + +namespace { + +// Threads per block for our apply kernel +// FIXME: use occupancy calculator instead +constexpr uint32_t AT_APPLY_THREADS_PER_BLOCK = 512; +constexpr uint32_t AT_APPLY_BLOCKS_PER_SM = 4; + +template +inline bool getApplyGrid(uint64_t totalElements, dim3& grid, c10::DeviceIndex curDevice, int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK) { + if (curDevice == -1) return false; + uint64_t numel_per_thread = static_cast(max_threads_per_block) * static_cast(step); + uint64_t numBlocks = ATenCeilDiv(totalElements, numel_per_thread); + uint64_t maxGridX = at::cuda::getDeviceProperties(curDevice)->maxGridSize[0]; + if (numBlocks > maxGridX) + numBlocks = maxGridX; + grid = dim3(numBlocks); + return true; +} + +constexpr int getApplyBlocksPerSM() { + return AT_APPLY_BLOCKS_PER_SM; +} + +constexpr int getApplyBlockSize() { + return AT_APPLY_THREADS_PER_BLOCK; +} + +inline dim3 getApplyBlock(int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK) { + return dim3(max_threads_per_block); +} + +} // anonymous namespace +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/AsmUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/AsmUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..1daf0349042c77bf0627c61ecfa294a5b5c73a3c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/AsmUtils.cuh @@ -0,0 +1,149 @@ +#pragma once +#include + +// Collection of direct PTX functions + +namespace at::cuda { + +template +struct Bitfield {}; + +template <> +struct Bitfield { + static __device__ __host__ __forceinline__ + unsigned int getBitfield(unsigned int val, int pos, int len) { +#if !defined(__CUDA_ARCH__) + pos &= 0xff; + len &= 0xff; + + unsigned int m = (1u << len) - 1u; + return (val >> pos) & m; +#else + unsigned int ret; + asm("bfe.u32 %0, %1, %2, %3;" : "=r"(ret) : "r"(val), "r"(pos), "r"(len)); + return ret; +#endif + } + + static __device__ __host__ __forceinline__ + unsigned int setBitfield(unsigned int val, unsigned int toInsert, int pos, int len) { +#if !defined(__CUDA_ARCH__) + pos &= 0xff; + len &= 0xff; + + unsigned int m = (1u << len) - 1u; + toInsert &= m; + toInsert <<= pos; + m <<= pos; + + return (val & ~m) | toInsert; +#else + unsigned int ret; + asm("bfi.b32 %0, %1, %2, %3, %4;" : + "=r"(ret) : "r"(toInsert), "r"(val), "r"(pos), "r"(len)); + return ret; +#endif + } +}; + +template <> +struct Bitfield { + static __device__ __host__ __forceinline__ + uint64_t getBitfield(uint64_t val, int pos, int len) { +#if !defined(__CUDA_ARCH__) + pos &= 0xff; + len &= 0xff; + + uint64_t m = (1u << len) - 1u; + return (val >> pos) & m; +#else + uint64_t ret; + asm("bfe.u64 %0, %1, %2, %3;" : "=l"(ret) : "l"(val), "r"(pos), "r"(len)); + return ret; +#endif + } + + static __device__ __host__ __forceinline__ + uint64_t setBitfield(uint64_t val, uint64_t toInsert, int pos, int len) { +#if !defined(__CUDA_ARCH__) + pos &= 0xff; + len &= 0xff; + + uint64_t m = (1u << len) - 1u; + toInsert &= m; + toInsert <<= pos; + m <<= pos; + + return (val & ~m) | toInsert; +#else + uint64_t ret; + asm("bfi.b64 %0, %1, %2, %3, %4;" : + "=l"(ret) : "l"(toInsert), "l"(val), "r"(pos), "r"(len)); + return ret; +#endif + } +}; + +__device__ __forceinline__ int getLaneId() { +#if defined(USE_ROCM) + return __lane_id(); +#else + int laneId; + asm("mov.s32 %0, %%laneid;" : "=r"(laneId) ); + return laneId; +#endif +} + +#if defined(USE_ROCM) +__device__ __forceinline__ unsigned long long int getLaneMaskLt() { + const std::uint64_t m = (1ull << getLaneId()) - 1ull; + return m; +} +#else +__device__ __forceinline__ unsigned getLaneMaskLt() { + unsigned mask; + asm("mov.u32 %0, %%lanemask_lt;" : "=r"(mask)); + return mask; +} +#endif + +#if defined (USE_ROCM) +__device__ __forceinline__ unsigned long long int getLaneMaskLe() { + std::uint64_t m = UINT64_MAX >> (sizeof(std::uint64_t) * CHAR_BIT - (getLaneId() + 1)); + return m; +} +#else +__device__ __forceinline__ unsigned getLaneMaskLe() { + unsigned mask; + asm("mov.u32 %0, %%lanemask_le;" : "=r"(mask)); + return mask; +} +#endif + +#if defined(USE_ROCM) +__device__ __forceinline__ unsigned long long int getLaneMaskGt() { + const std::uint64_t m = getLaneMaskLe(); + return m ? ~m : m; +} +#else +__device__ __forceinline__ unsigned getLaneMaskGt() { + unsigned mask; + asm("mov.u32 %0, %%lanemask_gt;" : "=r"(mask)); + return mask; +} +#endif + +#if defined(USE_ROCM) +__device__ __forceinline__ unsigned long long int getLaneMaskGe() { + const std::uint64_t m = getLaneMaskLt(); + return ~m; +} +#else +__device__ __forceinline__ unsigned getLaneMaskGe() { + unsigned mask; + asm("mov.u32 %0, %%lanemask_ge;" : "=r"(mask)); + return mask; +} +#endif + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/Atomic.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/Atomic.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e5e5799df8924d662261fa2f1cf69bc0454525ae --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/Atomic.cuh @@ -0,0 +1,513 @@ +#pragma once + +#include +#include +#include + +#include + +#if !(defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800)))) +#include +#endif + +#if defined(USE_ROCM) +#include +#endif + +template +struct AtomicFPOp; + +template <> +struct AtomicFPOp { + template + inline __device__ at::Half operator() (at::Half *address, at::Half val, const func_t& func) { + unsigned int * address_as_ui = + (unsigned int *) ((char *)address - ((size_t)address & 2)); + unsigned int old = *address_as_ui; + unsigned int assumed; + + at::Half hsum; + do { + assumed = old; + hsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff); + hsum = func(hsum, val); + old = (size_t)address & 2 ? (old & 0xffff) | (hsum.x << 16) : (old & 0xffff0000) | hsum.x; + old = atomicCAS(address_as_ui, assumed, old); + } while (assumed != old); + hsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff); + return hsum; + } +}; + +template <> +struct AtomicFPOp { + template + inline __device__ at::BFloat16 operator() (at::BFloat16 *address, at::BFloat16 val, const func_t& func) { + unsigned int * address_as_ui = + (unsigned int *) ((char *)address - ((size_t)address & 2)); + unsigned int old = *address_as_ui; + unsigned int assumed; + + at::BFloat16 bsum; + do { + assumed = old; + bsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff); + bsum = func(bsum, val); + old = (size_t)address & 2 ? (old & 0xffff) | (bsum.x << 16) : (old & 0xffff0000) | bsum.x; + old = atomicCAS(address_as_ui, assumed, old); + } while (assumed != old); + bsum.x = (size_t)address & 2 ? (old >> 16) : (old & 0xffff); + return bsum.x; + } +}; + +template <> +struct AtomicFPOp { + template + inline __device__ double operator() (double * address, double val, const func_t& func) { + unsigned long long int* address_as_ull = (unsigned long long int*)address; + unsigned long long int old = *address_as_ull; + unsigned long long int assumed; + + do { + assumed = old; + old = atomicCAS(address_as_ull, assumed, func(val, assumed)); + // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN) + } while (assumed != old); + + return __longlong_as_double(old); + } +}; + +#define ATOMIC_INTEGER_IMPL(NAME) \ +template \ +struct Atomic##NAME##IntegerImpl; \ + \ +template \ +struct Atomic##NAME##IntegerImpl { \ + template \ + inline __device__ void operator()(T *address, T val, const func_t& func) { \ + size_t offset = (size_t)address & 3; \ + uint32_t * address_as_ui = (uint32_t *)((char *)address - offset); \ + uint32_t old = *address_as_ui; \ + uint32_t shift = offset * 8; \ + uint32_t old_byte; \ + uint32_t newval; \ + uint32_t assumed; \ + \ + do { \ + assumed = old; \ + old_byte = (old >> shift) & 0xff; \ + newval = static_cast(func(val, static_cast(old_byte))); \ + newval = (old & ~(0x000000ff << shift)) | (newval << shift); \ + old = atomicCAS(address_as_ui, assumed, newval); \ + } while (assumed != old); \ + } \ +}; \ + \ +template \ +struct Atomic##NAME##IntegerImpl { \ + template \ + inline __device__ void operator()(T *address, T val, const func_t& func) { \ + size_t offset = (size_t)address & 2; \ + uint32_t * address_as_ui = (uint32_t *)((char *)address - offset); \ + bool is_32_align = offset; \ + uint32_t old = *address_as_ui; \ + uint32_t old_bytes; \ + uint32_t newval; \ + uint32_t assumed; \ + \ + do { \ + assumed = old; \ + old_bytes = is_32_align ? old >> 16 : old & 0xffff; \ + newval = static_cast(func(val, static_cast(old_bytes))); \ + newval = is_32_align ? (old & 0xffff) | (newval << 16) : (old & 0xffff0000) | newval; \ + old = atomicCAS(address_as_ui, assumed, newval); \ + } while (assumed != old); \ + } \ +}; \ + \ +template \ +struct Atomic##NAME##IntegerImpl { \ + template \ + inline __device__ void operator()(T *address, T val, const func_t& func) { \ + uint32_t * address_as_ui = (uint32_t *) (address); \ + uint32_t old = *address_as_ui; \ + uint32_t newval; \ + uint32_t assumed; \ + \ + do { \ + assumed = old; \ + newval = static_cast(func(val, static_cast(old))); \ + old = atomicCAS(address_as_ui, assumed, newval); \ + } while (assumed != old); \ + } \ +}; \ + \ +template \ +struct Atomic##NAME##IntegerImpl { \ + template \ + inline __device__ void operator()(T *address, T val, const func_t& func) { \ + unsigned long long * address_as_ui = (unsigned long long *) (address); \ + unsigned long long old = *address_as_ui; \ + unsigned long long newval; \ + unsigned long long assumed; \ + \ + do { \ + assumed = old; \ + newval = static_cast(func(val, static_cast(old))); \ + old = atomicCAS(address_as_ui, assumed, newval); \ + } while (assumed != old); \ + } \ +}; + + +# define GPU_ATOMIC_INTEGER(NAME, OP, DTYPE) \ +inline __device__ void gpuAtomic##NAME(DTYPE *address, DTYPE val) { \ +Atomic##NAME##IntegerImpl()(address, \ + val, \ + [](DTYPE a, DTYPE b) { \ + return OP; \ + }); \ +} \ + +ATOMIC_INTEGER_IMPL(Add) +GPU_ATOMIC_INTEGER(Add, a || b, bool) + +// Don't instantiate gpuAtomicAdd with the macro as it seems non-standard (see int32, int64) +inline __device__ void gpuAtomicAdd(uint8_t *address, uint8_t val) { + AtomicAddIntegerImpl()(address, + val, + [](uint8_t a, uint8_t b) { + return a + b; + }); +} + +inline __device__ void gpuAtomicAdd(int8_t *address, int8_t val) { + AtomicAddIntegerImpl()(address, + val, + [](int8_t a, int8_t b) { + return a + b; + }); +} + +inline __device__ void gpuAtomicAdd(int16_t *address, int16_t val) { + AtomicAddIntegerImpl()(address, + val, + [](int16_t a, int16_t b) { + return a + b; + }); +} + +inline __device__ int32_t gpuAtomicAdd(int32_t *address, int32_t val) { + return atomicAdd(address, val); +} + +inline __device__ void gpuAtomicAdd(int64_t *address, int64_t val) { +#if defined(USE_ROCM) + __atomic_fetch_add(address, val, __ATOMIC_RELAXED); +#else + static_assert(sizeof(unsigned long long int) == sizeof(int64_t), "bitwidth change is not allowed"); + atomicAdd(reinterpret_cast(address), static_cast(val)); +#endif +} + +inline __device__ at::Half gpuAtomicAdd(at::Half *address, at::Half val) { +#if defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 700))) + return AtomicFPOp()(address, val, + [](at::Half hsum, at::Half val) { + return hsum + val; + }); +#else + return atomicAdd(reinterpret_cast<__half*>(address), val); +#endif +} + +inline __device__ at::BFloat16 gpuAtomicAdd(at::BFloat16 *address, at::BFloat16 val) { +#if defined(USE_ROCM) || ((defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))) +return AtomicFPOp()(address, val, + [](at::BFloat16 bsum, at::BFloat16 val) { + return bsum + val; + }); +#else + __nv_bfloat16 r = atomicAdd(reinterpret_cast<__nv_bfloat16*>(address), *reinterpret_cast<__nv_bfloat16*>(&val)); + return *reinterpret_cast(&r); +#endif +} + +#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 600) +// from CUDA C Programmic Guide +inline __device__ double atomicAdd(double* address, double val) +#if defined(__clang__) && defined(__CUDA__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wgcc-compat" + __attribute__((enable_if(true, ""))) +#pragma GCC diagnostic pop +#endif +{ + + return AtomicFPOp()(address, val, + [](double val, unsigned long long int assumed) { + return __double_as_longlong(val + __longlong_as_double(assumed)); + }); +} +#elif defined(USE_ROCM) || !(defined(__CUDA_ARCH__)) + +/* Note [hip-clang differences to hcc] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * The upcoming hip-clang compiler for ROCm differs from hcc in a few details. + * It exports the __HIP__ macro, we can hence differentiate between hcc and + * hip-clang. In the below, hcc only received support for atomicAdd with double + * typing after work week 18312. hip-clang had support from the first version. + * In general, the code-visible differences between hip-clang and hcc will be + * minimal. + */ + +#if defined(USE_ROCM) && __hcc_workweek__ < 18312 && !__HIP__ + // This needs to be defined for the host side pass + inline __device__ double atomicAdd(double *address, double val) { } +#endif +#endif + +inline __device__ double gpuAtomicAdd(double *address, double val) { + return atomicAdd(address, val); +} + +inline __device__ float gpuAtomicAdd(float *address, float val) { + return atomicAdd(address, val); +} + +template +inline __device__ void gpuAtomicAdd(c10::complex *address, c10::complex val) { + gpuAtomicAdd(&address->real_, val.real_); + gpuAtomicAdd(&address->imag_, val.imag_); +} + +/* Note [gpuAtomicAdd vs atomicAdd] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Some extensions such as torchvision call atomicAdd() + * directly and require non-library provided data type support. Only for these, we + * continue to provide atomicAdd overloads. + */ +inline __device__ at::Half atomicAdd(at::Half *address, at::Half val) { + return gpuAtomicAdd(address, val); +} + +inline __device__ at::BFloat16 atomicAdd(at::BFloat16 *address, at::BFloat16 val) { + return gpuAtomicAdd(address, val); +} + +inline __device__ void atomicAdd(uint8_t *address, uint8_t val) { + gpuAtomicAdd(address, val); +} + +inline __device__ void atomicAdd(int8_t *address, int8_t val) { + gpuAtomicAdd(address, val); +} + +inline __device__ void atomicAdd(int16_t *address, int16_t val) { + gpuAtomicAdd(address, val); +} + +inline __device__ void atomicAdd(int64_t *address, int64_t val) { + gpuAtomicAdd(address, val); +} + +inline __device__ void atomicAdd(bool *address, bool val) { + gpuAtomicAdd(address, val); +} + +/* Note [explicitly non-returning atomics] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * AMD's MI100 (gfx908) provides an optimized fp32 atomicAdd, exposed via atomicAddNoRet(). + * Due to compiler limitations, callers must opt-in to guarantee the optimized instruction. + * This non-returning atomicAddNoRet cannot be used to implement the returning atomicAdd, + * therefore we need a new API 'gpuAtomicAddNoReturn'. + */ +template +inline __device__ void gpuAtomicAddNoReturn(c10::complex *address, c10::complex val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(uint8_t *address, uint8_t val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(int8_t *address, int8_t val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(int16_t *address, int16_t val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(int32_t *address, int32_t val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(int64_t *address, int64_t val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(bool *address, bool val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(at::Half *address, at::Half val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(at::BFloat16 *address, at::BFloat16 val) { gpuAtomicAdd(address, val); } + +/* Note [HIP unsafeAtomicAdd] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Use unsafeAtomicAdd instead of atomicAdd for fp32 and fp64. + * On HIP, atomicAdd is always correct but is a slow CAS loop. + * unsafeAtomicAdd will use HW instructions and is much faster, + * but the caller must guarantee the pointer is GPU memory. + * If the pointer is system memory, the result is a silent no-op. + * This guarantee is upheld by all PyTorch uses of unsafeAtomicAdd. + * AMD HIP atomic header file is named amd_hip_atomic.h and is + * under the LLVM compiler directory. + */ +#if defined(USE_ROCM) +inline __device__ void gpuAtomicAddNoReturn(float *address, float val) { + if (__builtin_amdgcn_processor_is("gfx908")) + return atomicAddNoRet(address, val); + (void)unsafeAtomicAdd(address, val); +} +inline __device__ void gpuAtomicAddNoReturn(double *address, double val) { (void)unsafeAtomicAdd(address, val); } +#else +inline __device__ void gpuAtomicAddNoReturn(float *address, float val) { gpuAtomicAdd(address, val); } +inline __device__ void gpuAtomicAddNoReturn(double *address, double val) { gpuAtomicAdd(address, val); } +#endif + +// Atomic multiplication implementation. + +ATOMIC_INTEGER_IMPL(Mul) +GPU_ATOMIC_INTEGER(Mul, a * b, uint8_t) +GPU_ATOMIC_INTEGER(Mul, a * b, int8_t) +GPU_ATOMIC_INTEGER(Mul, a * b, int16_t) +GPU_ATOMIC_INTEGER(Mul, a * b, int32_t) +GPU_ATOMIC_INTEGER(Mul, a * b, int64_t) + +inline __device__ at::Half gpuAtomicMul(at::Half * address, at::Half val) { + return AtomicFPOp()(address, val, + [](at::Half bsum, at::Half val) { + return bsum * val; + }); +} + +inline __device__ at::BFloat16 gpuAtomicMul(at::BFloat16 * address, at::BFloat16 val) { + return AtomicFPOp()(address, val, + [](at::BFloat16 bsum, at::BFloat16 val) { + return bsum * val; + }); +} + +inline __device__ double gpuAtomicMul(double * address, double val) { + return AtomicFPOp()(address, val, + [](double val, unsigned long long int assumed) { + return __double_as_longlong(val * __longlong_as_double(assumed)); + }); +} + +// Dont use a templated function for this since the addition function defaults to the CUDA built-in. +inline __device__ float gpuAtomicMul (float * address, float val) { + unsigned int* address_as_ull = (unsigned int*)address; + unsigned int old = *address_as_ull; + unsigned int assumed; + + do { + assumed = old; + old = atomicCAS(address_as_ull, assumed, + __float_as_int(val * + __int_as_float(assumed))); + + // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN) + } while (assumed != old); + + return __int_as_float(old); +} + +// Atomic maximum implementation. + +template +__host__ __device__ T safe_max(T a, T b) { + T max = at::_isnan(b) ? b : std::max(a, b); + return max; +} + +ATOMIC_INTEGER_IMPL(Max) +GPU_ATOMIC_INTEGER(Max, safe_max(a, b), uint8_t) +GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int8_t) +GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int16_t) +GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int32_t) +GPU_ATOMIC_INTEGER(Max, safe_max(a, b), int64_t) + +inline __device__ at::Half gpuAtomicMax(at::Half * address, at::Half val) { + return AtomicFPOp()(address, val, + [](at::Half bsum, at::Half val) { + return safe_max(bsum, val); + }); +} + +inline __device__ at::BFloat16 gpuAtomicMax(at::BFloat16 * address, at::BFloat16 val) { + return AtomicFPOp()(address, val, + [](at::BFloat16 bsum, at::BFloat16 val) { + return safe_max(bsum, val); + }); +} + +inline __device__ double gpuAtomicMax(double * address, double val) { + return AtomicFPOp()(address, val, + [](double val, unsigned long long int assumed) { + return __double_as_longlong(safe_max(val, __longlong_as_double(assumed))); + }); +} + +// Dont use a templated function for this since the addition function defaults to the CUDA built-in. +inline __device__ float gpuAtomicMax(float * address, float val) { + unsigned int* address_as_ull = (unsigned int*)address; + unsigned int old = *address_as_ull; + unsigned int assumed; + + do { + assumed = old; + old = atomicCAS(address_as_ull, assumed, + __float_as_int(safe_max(val, __int_as_float(assumed)))); + + // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN) + } while (assumed != old); + + return __int_as_float(old); +} + +// Atomic minimum implementation. + +template +__host__ __device__ T safe_min(T a, T b) { + T min = at::_isnan(b) ? b : std::min(a, b); + return min; +} + +ATOMIC_INTEGER_IMPL(Min) +GPU_ATOMIC_INTEGER(Min, safe_min(a, b), uint8_t) +GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int8_t) +GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int16_t) +GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int32_t) +GPU_ATOMIC_INTEGER(Min, safe_min(a, b), int64_t) + +inline __device__ at::Half gpuAtomicMin(at::Half * address, at::Half val) { + return AtomicFPOp()(address, val, + [](at::Half bsum, at::Half val) { + return safe_min(bsum, val); + }); +} + +inline __device__ at::BFloat16 gpuAtomicMin(at::BFloat16 * address, at::BFloat16 val) { + return AtomicFPOp()(address, val, + [](at::BFloat16 bsum, at::BFloat16 val) { + return safe_min(bsum, val); + }); +} + +inline __device__ double gpuAtomicMin(double * address, double val) { + return AtomicFPOp()(address, val, + [](double val, unsigned long long int assumed) { + return __double_as_longlong(safe_min(val, __longlong_as_double(assumed))); + }); +} + +// Dont use a templated function for this since the addition function defaults to the CUDA built-in. +inline __device__ float gpuAtomicMin(float * address, float val) { + unsigned int* address_as_ull = (unsigned int*)address; + unsigned int old = *address_as_ull; + unsigned int assumed; + + do { + assumed = old; + old = atomicCAS(address_as_ull, assumed, + __float_as_int(safe_min(val, __int_as_float(assumed)))); + + // Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN) + } while (assumed != old); + + return __int_as_float(old); +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAApplyUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAApplyUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..7c15de43fc9b0e569cfc34b69648e6d3615feff7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAApplyUtils.cuh @@ -0,0 +1,533 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// +// This file contains pointwise operation functions and kernels that +// work on both contiguous and non-contiguous tensor arguments of +// arbitrary (up to MAX_CUTORCH_DIMS) dimensioned arguments without +// copying or temporary storage. +// + +/* + NOTE [ CUDA_tensor_applyN helpers ] + + The following CUDA_tensor_applyN (where N currently can be 1, 2, 3, or 4) + functions apply a pointwise operator to N tensor(s). + + The calling convention is + + 1. The template arguments should be, sequentially, + - First N typename args specify the scalar types of each of the N tensors. + - (Optional) `int step` arg specifies the number of elements processed + together at the same time. + Default is 1. + - A usually omitted (i.e., inferred) typename arg specifies the type of the + function/functor applied on `N * step` values in each iteration of each + CUDA thread. + 2. The arguments should be, sequentially, + - N tensors + - op: a function/functor that processes `N * step` values at the same time. + - If `step == 1`, it must have signature + `void(*)(scalar1_t&, scalar2_t&, ..., scalarN_t&)`, where + `scalar*_t`s are the first N typename template args, and the inputs + are the `N` values from the `N` tensors retrieved at a common index. + - Otherwise, it must must have signature + void(*)(int n, scalar1_t&, scalar1_t&, ..., scalar1_t&, // repeat `step` times + scalar2_t&, scalar2_t&, ..., scalar2_t&, // repeat `step` times + ..., + scalarN_t&, scalarN_t&, ..., scalarN_t&) // repeat `step` times + Different from `step == 1` case, it processes `N * step` values taken + from `step` common indices. Moreover, the first input `n` represents the + number of valid indices (it will always have `0 < n <= step`). It will + almost always be `step`, but at the boundary we may not have full `step` + elements and `n` can be a lesser value. + + E.g., if `step == 4` and `N == 2`, `op` could be + + [](int n, scalar1_t &u1, scalar1_t &u2, scalar1_t &u3, scalar1_t &u4, + scalar2_t &v1, scalar2_t &v2, scalar2_t &v3, scalar2_t &v4) { + // Only process u1, ..., un and v1, ..., vn. + // So if `n == 3`, `u4` and `v4` need not to be considered. + } + + In both cases, the references can actually be const, but at least one of + them should be non-const in order to write the output. + - (Optional, but recommended) N TensorArgType args that specify for each + tensor whether `op` reads AND writes ] (i.e., TensorArgType::ReadWrite), + or only reads (i.e., TensorArgType::ReadOnly). + Default is TensorArgType::ReadWrite for first Tensor, and + TensorArgType::ReadOnly for the rest. + + E.g., + + to compute a = b^2 for a and b of same dtype, we can call + + CUDA_tensor_apply2( + a, b, + [] __device__ (scalar &a_val, const scalar &b_val) { a_val = b_val * b_val; } + ); + + to work on 2 values at the same time, we can call + + CUDA_tensor_apply2( + a, b, + [] __device__ (int n, scalar1 &a_val1, scalar1 &a_val2, + const scalar2 &b_val1, const scalar2 &b_val2) { + // call special vectorized op here, or just do elementwise and enjoy unrolling... + // if n == 1, only process a_val1 and b_val1 + } + ); +*/ + +namespace at::cuda { + +// TODO: combine with TensorArg? So far that's been for debugging, and this is functional... +enum class TensorArgType { ReadWrite, ReadOnly }; + +namespace { + +// Rearrange dimensions for pointwise operations so that strides are in +// decreasing order as much as possible, so that kernels have better memory +// access patterns. +// +// For example, consider a binary operation on two "transposed" 2-dim tensors: +// sizes: 256 512 +// aInfo->strides: 1 256 +// bInfo->strides: 1 256 +// +// Given this, each concurrent memory access inside kernelPointwiseApply2() is +// exactly 256 elements apart, resulting in poor performance. +// +// This function exchanges dimensions so that memory access is contiguous: +// sizes: 512 256 +// aInfo->strides: 256 1 +// bInfo->strides: 256 1 +// +// (Actually, it becomes even better because now collapseDims() can turn each +// input into one contiguous array.) +// +// In general, given M (<=4) TensorInfo's with N dimensions, we can view each +// strides[i] (0 <= i < N) as an M-tuple. Given each pair i < j, we exchange +// strides[i] and [j] if +// (1) strides[i][k] < strides[j][k] for some k (0 <= k < M) +// (exchanging them will benefit input #k), and +// (2) strides[i][k] <= strieds[j][k] for all k +// (exchanging them will not make any input worse). +template +inline void rearrangeDims(detail::TensorInfo* aInfo, + detail::TensorInfo* bInfo = nullptr, + detail::TensorInfo* cInfo = nullptr, + detail::TensorInfo* dInfo = nullptr) { + int numInfos = 1; + int dims = aInfo->dims; + IndexType *sizes[4] = { aInfo->sizes, }; + IndexType *strides[4] = { aInfo->strides, }; + + if (bInfo != nullptr) { + ++numInfos; + if (bInfo->dims != dims) return; + sizes[1] = bInfo->sizes; + strides[1] = bInfo->strides; + } + + if (cInfo != nullptr) { + ++numInfos; + if (cInfo->dims != dims) return; + sizes[2] = cInfo->sizes; + strides[2] = cInfo->strides; + } + + if (dInfo != nullptr) { + ++numInfos; + if (dInfo->dims != dims) return; + sizes[3] = dInfo->sizes; + strides[3] = dInfo->strides; + } + + // Bail out if sizes do not match: we are using "deprecated pointwise + // behavior" among tensors of different shapes but same number of elements. + for (int i = 1; i < numInfos; ++i) { + for (int j = 0; j < dims; ++j) { + if (sizes[i][j] != sizes[0][j]) return; + } + } + + for (int i = 0; i < dims - 1; ++i) { + // No need to consider dimensions of size 1. + if (sizes[0][i] == 1) continue; + + for (int j = i + 1; j < dims; ++j) { + if (sizes[0][j] == 1) continue; + + // Compare the relative sizes of strides between dim #i and dim #j. + bool hasIncreasingStrides = false; + bool hasDecreasingStrides = false; + + for (int k = 0; k < numInfos; k++) { + IndexType stride_i = strides[k][i]; + IndexType stride_j = strides[k][j]; + if (stride_i < stride_j) { + hasIncreasingStrides = true; + } else if (stride_i > stride_j) { + hasDecreasingStrides = true; + } + } + + if (hasIncreasingStrides && !hasDecreasingStrides) { + for (int k = 0; k < numInfos; k++) { + IndexType size = sizes[k][i]; + sizes[k][i] = sizes[k][j]; + sizes[k][j] = size; + + IndexType stride = strides[k][i]; + strides[k][i] = strides[k][j]; + strides[k][j] = stride; + } + } + } + } +} + +// The `remaining_steps` argument is used to support Op that operates on +// multiple elements at the same time. Generally, the strategy of ApplyOpN is to +// 1. Initialize `remaining_steps = step`, where `step` is the template arg of +// CUDA_tensor_applyN helpers. The input arg `n` to `apply()` represents the +// number of elements in bound for this call. It will almost always equal to +// `step` except at boundaries. +// 2. If `remaining_steps > 0` convert the current linearIndex to offset (if in +// bound), and recursively call `ApplyOpN` with `remaining_steps - 1`. +// 3. At `remaining_steps = 0`, +// if `step = 1`, call `op(tensor1_val, tensor2_val, ...)`; +// if `step > 1`, call `op(n, tensor1_val1, tensor1_val2, ..., tensor1_valstep, +// tensor2_val1, tensor2_val2, ..., tensor2_valstep, +// ... +// tensorN_val1, tensorN_val2, ..., tensorN_valstep);` +// +// See NOTE [ CUDA_tensor_applyN helpers ] above for how Op may look like. + +template +struct ApplyOp1 { +__device__ __forceinline__ +static void apply(detail::TensorInfo &a, const Op &op, int n, + IndexType linearIndex, Offsets... aOffsets) { + // Convert `linearIndex` into an offset of `a` + const IndexType aOffset = sizeof...(Offsets) < n ? + detail::IndexToOffset::get(linearIndex, a) : 0; + + ApplyOp1::apply( + a, op, n, linearIndex + 1, aOffsets..., aOffset + ); +} +}; + +// Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`). +// We don't need to pass in how many elements need to processed in this case. +template +struct ApplyOp1 { +__device__ __forceinline__ +static void apply(detail::TensorInfo &a, const Op &op, + int n, IndexType linearIndex, Offset offset) { + op(a.data[offset]); +} +}; + +template +struct ApplyOp1 { +__device__ __forceinline__ +static void apply(detail::TensorInfo &a, const Op &op, int n, + IndexType linearIndex, Offsets... offsets) { + op(n, a.data[offsets]...); +} +}; + +template +C10_LAUNCH_BOUNDS_2(AT_APPLY_THREADS_PER_BLOCK, AT_APPLY_BLOCKS_PER_SM) +__global__ void kernelPointwiseApply1(detail::TensorInfo a, + IndexType totalElements, const Op op) { + for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step; + linearIndex < totalElements; + linearIndex += gridDim.x * blockDim.x * step) { + ApplyOp1::apply( + a, op, ::min(step, static_cast(totalElements - linearIndex)), linearIndex); + } +} + + +template +struct ApplyOp2 { +__device__ __forceinline__ +static void apply(detail::TensorInfo &a, + detail::TensorInfo &b, + const Op &op, int64_t n, IndexType linearIndex, + Offsets... aOffsets, Offsets... bOffsets) { + // Convert `linearIndex` into an offset of `a` + const IndexType aOffset = static_cast(sizeof...(Offsets)) < n ? + detail::IndexToOffset::get(linearIndex, a) : 0; + + // Convert `linearIndex` into an offset of `b` + const IndexType bOffset = static_cast(sizeof...(Offsets)) < n ? + detail::IndexToOffset::get(linearIndex, b) : 0; + + ApplyOp2::apply( + a, b, op, n, linearIndex + 1, aOffsets..., aOffset, bOffsets..., bOffset + ); +} +}; + +// Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`). +// We don't need to pass in how many elements need to processed in this case. +template +struct ApplyOp2 { +__device__ __forceinline__ +static void apply(detail::TensorInfo &a, + detail::TensorInfo &b, + const Op &op, int /*n*/, IndexType /*linearIndex*/, + Offset aOffset, Offset bOffset) { + op(a.data[aOffset], b.data[bOffset]); +} +}; + +template +struct ApplyOp2 { +__device__ __forceinline__ +static void apply(detail::TensorInfo &a, + detail::TensorInfo &b, + const Op &op, int n, IndexType linearIndex, + Offsets... aOffsets, Offsets... bOffsets) { + op(n, a.data[aOffsets]..., b.data[bOffsets]...); +} +}; + +template +C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm) +__global__ void +kernelPointwiseApply2(detail::TensorInfo a, + detail::TensorInfo b, + IndexType totalElements, + const Op op) { + for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step; + linearIndex < totalElements; + linearIndex += gridDim.x * blockDim.x * step) { + ApplyOp2::apply( + a, b, op, ::min(step, static_cast(totalElements - linearIndex)), + linearIndex); + } +} + +} // anonymous namespace + +template +inline bool CUDA_tensor_apply2(at::TensorBase a, + at::TensorBase b, + const Op op, + TensorArgType aType = TensorArgType::ReadWrite, + TensorArgType bType = TensorArgType::ReadOnly) { + TORCH_CHECK(a.device().is_cuda() && b.device().is_cuda(), + "CUDA_tensor_apply2: Expected tensors to have CUDA DeviceType, but got " + "tensors with type ", a.device().type(), " and ", b.device().type()); + int64_t totalElements = a.numel(); + + if (totalElements != b.numel()) { + return false; + } + + if (a.dim() > MAX_TENSORINFO_DIMS || + b.dim() > MAX_TENSORINFO_DIMS) { + return false; + } + + if (a.numel() == 0) { + // Empty tensor; do nothing + return true; + } + const dim3 block = getApplyBlock(max_threads_per_block); + + dim3 grid; + auto curDevice = current_device(); + if (curDevice == -1) return false; + if (!getApplyGrid(totalElements, grid, curDevice, max_threads_per_block)) { + return false; + } + + /* + Expands readable/writable tensors whose indices may be "overlapped." + This ensures that each element of the tensor is operated on once and only + once. + */ + TensorBase oldA; + TensorBase oldB; + + if (aType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(a)) { + // Must perform in contiguous space + oldA = std::exchange(a, a.contiguous()); + } + if (bType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(b)) { + // Must perform in contiguous space + oldB = std::exchange(b, b.contiguous()); + } + + // It is possible that the tensor dimensions are able to be collapsed, + // and thus we can reduce the actual code complexity of the copy by + // exploiting this knowledge statically, since the div/mod is the + // most expensive part of the operation, more so than memory accesses. + // For instance, when copying a non-contiguous to a contiguous tensor + // (or vice versa), the contiguous tensor can be collapsed to one + // dimension, and the loop to translate the linear index to the array + // index can be similarly collapsed. That is what this unrolling is for. + +#define HANDLE_CASE(TYPE, A, B) \ + kernelPointwiseApply2 \ + <<>>( \ + aInfo, bInfo, static_cast(totalElements), op); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); + +#define HANDLE_B_CASE(TYPE, A, B) { \ + switch (B) { \ + case 1: \ + HANDLE_CASE(TYPE, A, 1); \ + break; \ + case 2: \ + HANDLE_CASE(TYPE, A, 2); \ + break; \ + default: \ + HANDLE_CASE(TYPE, A, -1); \ + break; \ + } \ +} + +#define HANDLE_A_CASE(TYPE, A, B) { \ + switch (A) { \ + case 1: \ + HANDLE_B_CASE(TYPE, 1, B); \ + break; \ + case 2: \ + HANDLE_B_CASE(TYPE, 2, B); \ + break; \ + default: \ + HANDLE_B_CASE(TYPE, -1, B); \ + break; \ + } \ +} + + if (detail::canUse32BitIndexMath(a) && + detail::canUse32BitIndexMath(b)) { + detail::TensorInfo aInfo = + detail::getTensorInfo(a); + + detail::TensorInfo bInfo = + detail::getTensorInfo(b); + rearrangeDims(&aInfo, &bInfo); + aInfo.collapseDims(); + bInfo.collapseDims(); + + HANDLE_A_CASE(unsigned int, aInfo.dims, bInfo.dims); + } else { + detail::TensorInfo aInfo = + detail::getTensorInfo(a); + + detail::TensorInfo bInfo = + detail::getTensorInfo(b); + rearrangeDims(&aInfo, &bInfo); + aInfo.collapseDims(); + bInfo.collapseDims(); + + /* + Only instantiates the all 1D special case and the fallback all nD case for + large (64-bit indexed) tensors to reduce compilation time. + */ + if (aInfo.dims == 1 && bInfo.dims == 1) { + HANDLE_CASE(uint64_t, 1, 1); + } else { + HANDLE_CASE(uint64_t, -1, -1); + } + } +#undef HANDLE_CASE +#undef HANDLE_B_CASE +#undef HANDLE_A_CASE + + if (oldA.defined()) { + at::native::copy_ignoring_overlaps(oldA, a); + } + + if (oldB.defined()) { + at::native::copy_ignoring_overlaps(oldB, b); + } + + return true; +} + +/* Provides default step = 1 to CUDA_tensor_apply2. */ +template +inline bool CUDA_tensor_apply2(const at::TensorBase &a, + const at::TensorBase &b, + const Op op, + TensorArgType aType = TensorArgType::ReadWrite, + TensorArgType bType = TensorArgType::ReadOnly) { + return CUDA_tensor_apply2(a, b, op, aType, bType); +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDABlas.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDABlas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a257037a2ddc8b3c878f719f0b479de119043a7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDABlas.cpp @@ -0,0 +1,2695 @@ +/* + Provides the implementations of CUDA BLAS function templates. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifdef USE_ROCM +#include +#include +// until hipblas has an API to accept flags, we must use rocblas here +#include +#include +#include +#include +#define PYTORCH_ROCBLAS_VERSION_DECIMAL (ROCBLAS_VERSION_MAJOR * 100 + ROCBLAS_VERSION_MINOR) +#define USE_GEMM_FLAGS_FP16_ALT_IMPL (PYTORCH_ROCBLAS_VERSION_DECIMAL >= 242) +// needed to work around calling rocblas API instead of hipblas API +static rocblas_operation hipOperationToRocOperation(hipblasOperation_t op) +{ + switch(op) + { + case HIPBLAS_OP_N: + return rocblas_operation_none; + case HIPBLAS_OP_T: + return rocblas_operation_transpose; + case HIPBLAS_OP_C: + return rocblas_operation_conjugate_transpose; + } + TORCH_CHECK(false, "HIPBLAS_STATUS_INVALID_ENUM"); +} +static hipblasStatus_t rocBLASStatusToHIPStatus(rocblas_status error) +{ + switch(error) + { + case rocblas_status_size_unchanged: + case rocblas_status_size_increased: + case rocblas_status_success: + return HIPBLAS_STATUS_SUCCESS; + case rocblas_status_invalid_handle: + return HIPBLAS_STATUS_NOT_INITIALIZED; + case rocblas_status_not_implemented: + return HIPBLAS_STATUS_NOT_SUPPORTED; + case rocblas_status_invalid_pointer: + case rocblas_status_invalid_size: + case rocblas_status_invalid_value: + return HIPBLAS_STATUS_INVALID_VALUE; + case rocblas_status_memory_error: + return HIPBLAS_STATUS_ALLOC_FAILED; + case rocblas_status_internal_error: + return HIPBLAS_STATUS_INTERNAL_ERROR; + } + TORCH_CHECK(false, "HIPBLAS_STATUS_INVALID_ENUM"); +} +// hipblas does not have hipblasSetMathMode +#define hipblasSetMathMode(handle, flags) HIPBLAS_STATUS_SUCCESS +// until we use hiblas v2 +// hipify correctly maps things like CUDA_R_16F to HIP_R_16F, +// however hipblas v1 is still using its custom type +#ifndef HIPBLAS_V2 +#define HIP_R_16F HIPBLAS_R_16F +#define HIP_R_32F HIPBLAS_R_32F +#define HIP_R_64F HIPBLAS_R_64F +#define HIP_C_16F HIPBLAS_C_16F +#define HIP_C_32F HIPBLAS_C_32F +#define HIP_C_64F HIPBLAS_C_64F +#define HIP_R_8I HIPBLAS_R_8I +#define HIP_R_8U HIPBLAS_R_8U +#define HIP_R_32I HIPBLAS_R_32I +#define HIP_R_32U HIPBLAS_R_32U +#define HIP_C_8I HIPBLAS_C_8I +#define HIP_C_8U HIPBLAS_C_8U +#define HIP_C_32I HIPBLAS_C_32I +#define HIP_C_32U HIPBLAS_C_32U +#define HIP_R_16BF HIPBLAS_R_16B +#define HIP_C_16BF HIPBLAS_C_16B +#endif +#endif + +#define CUDABLAS_POSINT_CHECK(FD, X) \ + TORCH_CHECK( \ + (X > 0 && X <= INT_MAX), \ + "at::cuda::blas::" #FD " argument " #X \ + " must be positive and less than ", \ + INT_MAX, \ + " but got ", \ + X) + +#define CUDABLAS_NONNEGINT_CHECK(FD, X) \ + TORCH_CHECK( \ + (X >= 0 && X <= INT_MAX), \ + "at::cuda::blas::" #FD " argument " #X \ + " must be non-negative and less than ", \ + INT_MAX, \ + " but got ", \ + X) + +namespace { + +void _cublasAdjustLdLevel2(int64_t m, int64_t n, int64_t* lda) { + // Note: leading dimensions generally are checked that they are > 0 + // and at least as big the result requires (even if the value won't + // be used). + + // Q: Why does Level3 check trans but this doesn't? + // A: In level 2, the sizes (m, n) specify the size of A + // (independent of trans value). In level 3. the sizes (m, n, k) + // specify the sizes of op(A), op(B) where op depend on trans + // values. + if (n <= 1) + *lda = std::max(m, 1); +} + +#if !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12000 +class CuBlasSMCarveoutGuard { + public: + explicit CuBlasSMCarveoutGuard(cublasHandle_t handle) : handle_(handle) { + const auto smCarveout = at::globalContext()._SMCarveout_EXPERIMENTAL(); + if (smCarveout.has_value()) { + const int smCount = + at::cuda::getCurrentDeviceProperties()->multiProcessorCount; + const int carveout = smCarveout.value(); + TORCH_CHECK( + carveout >= 0 && carveout < smCount, + "SM carveout must be between 0 and ", + smCount - 1, + " (num_sms-1), got ", + carveout); + TORCH_CUDABLAS_CHECK( + cublasSetSmCountTarget(handle_, smCount - carveout)); + enabled_ = true; + } + } + ~CuBlasSMCarveoutGuard() { + if (enabled_) { + cublasSetSmCountTarget(handle_, 0); + } + } + CuBlasSMCarveoutGuard(const CuBlasSMCarveoutGuard&) = delete; + CuBlasSMCarveoutGuard& operator=(const CuBlasSMCarveoutGuard&) = delete; + + private: + cublasHandle_t handle_; + bool enabled_ = false; +}; +#define CUBLAS_SM_CARVEOUT_GUARD(handle) CuBlasSMCarveoutGuard smCarveoutGuard(handle) +#else +#define CUBLAS_SM_CARVEOUT_GUARD(handle) +#endif + +#ifdef USE_ROCM +static c10::cuda::CUDAStream _getCarveoutStream(int32_t value) { + // 0 is default value, meaning full CUs i.e. no mask + if (value == 0) { + return at::cuda::getCurrentCUDAStream(); + } + static int32_t last_value = 0; + static hipStream_t stream; + if (last_value == 0) { + // first request, do nothing for this case + } + else if (last_value == value) { + // stream was created previously and value hasn't changed + return c10::cuda::getStreamFromExternal(stream, c10::cuda::current_device()); + } + else { + // need a new stream and a previous stream exists, delete it + AT_CUDA_CHECK(hipStreamDestroy(stream)); + } + + // if we got here, we need to create a new stream + int32_t CUs = at::cuda::getCurrentDeviceProperties()->multiProcessorCount; + // how many uint32_t do we need to cover all CUs, fill bitmask with 1 + uint32_t mask_size = static_cast((CUs + 32 - 1) / 32); + std::vector mask(mask_size, uint32_t{0x00000000}); + // starting from lowest order bits, in 32-bit chunks + // set bits to 0 based on how many CUs to carve out + int32_t full_shifts = value / 32; + int32_t remainder = value % 32; + for (int32_t i = 0; i < full_shifts; i++) { + mask[i] = uint32_t{0xffffffff}; + } + mask[full_shifts] = uint32_t{0xffffffff} << (32 - remainder); + + // finally, create masked stream + AT_CUDA_CHECK(hipExtStreamCreateWithCUMask(&stream, mask_size, &mask[0])); + + last_value = value; + return c10::cuda::getStreamFromExternal(stream, c10::cuda::current_device()); +} + +static void _syncCurrentWithCarveoutStream(hipStream_t stream, bool presync) { + hipEvent_t event; + AT_CUDA_CHECK(hipEventCreateWithFlags(&event, hipEventDisableTiming)); + + auto current_stream = at::cuda::getCurrentCUDAStream(); + + if (presync) { + AT_CUDA_CHECK(hipEventRecord(event, current_stream)); + AT_CUDA_CHECK(hipStreamWaitEvent(stream, event, 0)); + } + else { + AT_CUDA_CHECK(hipEventRecord(event, stream)); + AT_CUDA_CHECK(hipStreamWaitEvent(current_stream, event, 0)); + } +} +#endif + +} // anonymous namespace + +namespace at::cuda::blas { + +using detail::CuBlasLtMatmulDescriptor; +using detail::CuBlasLtMatrixLayout; +using detail::CuBlasLtMatmulPreference; +using detail::CublasLtWorkspace; + +/* LEVEL 3 BLAS FUNCTIONS */ + +#define GEMM_CHECK_ARGVALUES(Dtype) \ + do { \ + CUDABLAS_NONNEGINT_CHECK(gemm, m); \ + CUDABLAS_NONNEGINT_CHECK(gemm, n); \ + CUDABLAS_NONNEGINT_CHECK(gemm, k); \ + CUDABLAS_POSINT_CHECK(gemm, lda); \ + CUDABLAS_POSINT_CHECK(gemm, ldb); \ + CUDABLAS_POSINT_CHECK(gemm, ldc); \ + } while (0) + +#define BGEMM_CHECK_ARGVALUES(Dtype) \ + do { \ + CUDABLAS_NONNEGINT_CHECK(bgemm, m); \ + CUDABLAS_NONNEGINT_CHECK(bgemm, n); \ + CUDABLAS_NONNEGINT_CHECK(bgemm, k); \ + CUDABLAS_POSINT_CHECK(bgemm, lda); \ + CUDABLAS_POSINT_CHECK(bgemm, ldb); \ + CUDABLAS_POSINT_CHECK(bgemm, ldc); \ + CUDABLAS_NONNEGINT_CHECK(bgemm, num_batches); \ + } while (0) + +template +static inline bool bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { +#if defined(USE_ROCM) && ROCM_VERSION == 60400 + // regression in ROCm 6.4, planned fixed in 6.4.1, hipblaslt TT fp32 calculation errors + // best to disallow hipblaslt for this specific case + if constexpr (std::is_same_v) { + if (detail::cublasOpFromChar(transa) == CUBLAS_OP_T && detail::cublasOpFromChar(transb) == CUBLAS_OP_T) { + return false; + } + } +#endif + const auto type_info = detail::getCublasLtTypeInfo(); + const cudaDataType_t abType = type_info.ab_type; + const cudaDataType_t cType = type_info.c_type; + const cublasComputeType_t computeType = type_info.compute_type; + const cudaDataType_t scaleType = type_info.scale_type; + CuBlasLtMatmulPreference preference; +#ifndef USE_ROCM + at::Half halpha; + at::Half hbeta; + uint32_t mask = -1; +#endif + void * alpha_ptr = α + void * beta_ptr = β + if constexpr (std::is_same_v) { +#ifndef USE_ROCM + if (computeType == CUBLAS_COMPUTE_16F) { + halpha = alpha; + hbeta = beta; + alpha_ptr = &halpha; + beta_ptr = &hbeta; + } +#endif + } +#ifndef USE_ROCM + if constexpr (std::is_same_v) { + auto fp16_reduction = at::globalContext().allowFP16ReductionCuBLAS(); + if (fp16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + mask = + fp16_reduction == + at::CuBLASReductionOption::DisallowReducedPrecisionAllowSplitK + ? (CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE | + CUBLASLT_REDUCTION_SCHEME_NONE) + : CUBLASLT_REDUCTION_SCHEME_NONE; + preference.setAttribute( + CUBLASLT_MATMUL_PREF_REDUCTION_SCHEME_MASK, mask); + } + } else if constexpr (std::is_same_v) { + auto bf16_reduction = at::globalContext().allowBF16ReductionCuBLAS(); + if (bf16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + mask = + bf16_reduction == + at::CuBLASReductionOption::DisallowReducedPrecisionAllowSplitK + ? (CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE | + CUBLASLT_REDUCTION_SCHEME_NONE) + : CUBLASLT_REDUCTION_SCHEME_NONE; + preference.setAttribute( + CUBLASLT_MATMUL_PREF_REDUCTION_SCHEME_MASK, mask); + } + } +#endif + + cublasLtHandle_t ltHandle = at::cuda::getCurrentCUDABlasLtHandle(); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + + CuBlasLtMatmulDescriptor computeDesc(computeType, scaleType); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSA, opa); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSB, opb); + auto stream = at::cuda::getCurrentCUDAStream(); +#ifndef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + computeDesc.setAttribute( + CUBLASLT_MATMUL_DESC_SM_COUNT_TARGET, + at::cuda::getCurrentDeviceProperties()->multiProcessorCount - + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + } +#else + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + stream = _getCarveoutStream( + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + _syncCurrentWithCarveoutStream(stream, true); + } +#endif + CuBlasLtMatrixLayout Adesc(abType, m, k, lda, opa != CUBLAS_OP_N); + CuBlasLtMatrixLayout Bdesc(abType, k, n, ldb, opb != CUBLAS_OP_N); + CuBlasLtMatrixLayout Cdesc(cType, m, n, ldc); + + if (num_batches > 1) { + int num_batches_as_int = static_cast(num_batches); + Adesc.setAttribute(CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, num_batches_as_int); + Bdesc.setAttribute(CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, num_batches_as_int); + Cdesc.setAttribute(CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, num_batches_as_int); + Adesc.setAttribute(CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stridea); + Bdesc.setAttribute(CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, strideb); + Cdesc.setAttribute(CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stridec); + } + +#ifndef USE_ROCM + uint32_t a_alignment = detail::getAlignment(reinterpret_cast(a)); + uint32_t b_alignment = detail::getAlignment(reinterpret_cast(b)); + uint32_t c_alignment = detail::getAlignment(reinterpret_cast(c)); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_A_BYTES, a_alignment); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_B_BYTES, b_alignment); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_C_BYTES, c_alignment); +#endif + + auto ltworkspace = CublasLtWorkspace(); + TORCH_CHECK(ltworkspace.ptr != nullptr, "OOM trying to allocate workspace for cublaslt"); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, ltworkspace.size); + + cublasStatus_t cublasStatus = CUBLAS_STATUS_SUCCESS; + cublasLtMatmulHeuristicResult_t heuristicResult = {}; + int returnedResult = 0; + // on Blackwell+, we fake a n > 1 matmul when querying heuristics + // to prevent cuBLASLt from dispatching to a GEMV kernel for batch-invariance +#ifndef USE_ROCM + const bool lie_to_cublaslt = mask == CUBLASLT_REDUCTION_SCHEME_NONE && n == 1 && at::cuda::getCurrentDeviceProperties()->major >= 10; +#else + const bool lie_to_cublaslt = false; +#endif + if (lie_to_cublaslt) { + const auto fake_ldb = ldb == 1 ? 2 : ldb; + const auto fake_ldc = ldc == 1 ? 2 : ldc; + CuBlasLtMatrixLayout FakeBdesc(abType, k, 2, fake_ldb, opb == CUBLAS_OP_T); + CuBlasLtMatrixLayout FakeCdesc(cType, m, 2, fake_ldc); + if (num_batches > 1) { + int num_batches_as_int = static_cast(num_batches); + FakeBdesc.setAttribute( + CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, num_batches_as_int); + FakeCdesc.setAttribute( + CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, num_batches_as_int); + FakeBdesc.setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, strideb); + FakeCdesc.setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stridec); + } + + TORCH_CUDABLAS_CHECK(cublasLtMatmulAlgoGetHeuristic( + ltHandle, + computeDesc.descriptor(), + Adesc.descriptor(), + FakeBdesc.descriptor(), + FakeCdesc.descriptor(), + FakeCdesc.descriptor(), + preference.descriptor(), + 1, + &heuristicResult, + &returnedResult)); + } else { + TORCH_CUDABLAS_CHECK(cublasLtMatmulAlgoGetHeuristic( + ltHandle, + computeDesc.descriptor(), + Adesc.descriptor(), + Bdesc.descriptor(), + Cdesc.descriptor(), + Cdesc.descriptor(), + preference.descriptor(), + 1, + &heuristicResult, + &returnedResult)); + } + if (returnedResult == 0) { + cublasStatus = CUBLAS_STATUS_NOT_SUPPORTED; + } + else { + cublasStatus = cublasLtMatmul( + ltHandle, + computeDesc.descriptor(), + alpha_ptr, + a, + Adesc.descriptor(), + b, + Bdesc.descriptor(), + beta_ptr, + c, + Cdesc.descriptor(), + c, + Cdesc.descriptor(), + &heuristicResult.algo, + ltworkspace.ptr, + ltworkspace.size, + stream); +#ifdef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + _syncCurrentWithCarveoutStream(stream, false); + } +#endif + } + if (cublasStatus != CUBLAS_STATUS_SUCCESS) { + TORCH_WARN( + "bgemm_internal_cublaslt error: ", + at::cuda::blas::_cublasGetErrorEnum(cublasStatus), + " when calling cublasLtMatmul with transpose_mat1 ", + transa, + " transpose_mat2 ", + transb, + " m ", + m, + " n ", + n, + " k ", + k, + " lda ", + lda, + " ldb ", + ldb, + " ldc ", + ldc, + " abType ", + abType, + " cType ", + cType, + " computeType ", + computeType, + " scaleType ", + scaleType, + ". Will attempt to recover by calling cublas instead."); + return false; + } + return true; +} + + +template +inline void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + TORCH_CHECK(false, "at::cuda::blas::bgemm: not implemented for input type ", typeid(Dtype).name(), " and output type ", typeid(C_Dtype).name()); +} + +template <> +void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES(double)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + BGEMM_CHECK_ARGVALUES(double); + TORCH_CUDABLAS_CHECK(cublasDgemmStridedBatched( + handle, opa, opb, m, n, k, &alpha, a, lda, stridea, b, ldb, strideb, &beta, c, ldc, stridec, num_batches)); +} + +template <> +void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES(float)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + BGEMM_CHECK_ARGVALUES(float); + TORCH_CUDABLAS_CHECK(cublasSgemmStridedBatched( + handle, opa, opb, m, n, k, &alpha, a, lda, stridea, b, ldb, strideb, &beta, c, ldc, stridec, num_batches)); +} + +template <> +void bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + BGEMM_CHECK_ARGVALUES(c10::complex); + TORCH_CUDABLAS_CHECK(cublasZgemmStridedBatched( + handle, opa, opb, m, n, k, reinterpret_cast(&alpha), reinterpret_cast(a), + lda, stridea, reinterpret_cast(b), ldb, strideb, reinterpret_cast(&beta), + reinterpret_cast(c), ldc, stridec, num_batches)); +} + +template <> +void bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + BGEMM_CHECK_ARGVALUES(c10::complex); + TORCH_CUDABLAS_CHECK(cublasCgemmStridedBatched( + handle, opa, opb, m, n, k, reinterpret_cast(&alpha), reinterpret_cast(a), + lda, stridea, reinterpret_cast(b), ldb, strideb, reinterpret_cast(&beta), + reinterpret_cast(c), ldc, stridec, num_batches)); +} + +template +inline void bgemm_internal_cublas_half_helper(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, C_Dtype)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + BGEMM_CHECK_ARGVALUES(at::Half); + float falpha = alpha; + float fbeta = beta; +#ifndef USE_ROCM + at::Half halpha; + at::Half hbeta; + auto compute_type = CUDA_R_32F; +#endif + void * alpha_ptr = &falpha; + void * beta_ptr = &fbeta; +#ifdef USE_ROCM + int flag = 0; + rocblas_datatype c_type = std::is_same::value ? rocblas_datatype_f32_r : rocblas_datatype_f16_r; + rocblas_datatype d_type = c_type; +#if USE_GEMM_FLAGS_FP16_ALT_IMPL + flag = at::ROCmBackwardPassGuard::is_backward_pass() ? rocblas_gemm_flags_fp16_alt_impl : 0; +#endif + TORCH_CUDABLAS_CHECK(rocBLASStatusToHIPStatus(rocblas_gemm_strided_batched_ex((rocblas_handle)handle, + hipOperationToRocOperation(opa), + hipOperationToRocOperation(opb), (int)m, (int)n, (int)k, + (void*)alpha_ptr, a, rocblas_datatype_f16_r, (int)lda, stridea, + b, rocblas_datatype_f16_r, (int)ldb, strideb, + (void*)beta_ptr, c, c_type, (int)ldc, stridec, + c, d_type, (int)ldc, stridec, + (int) num_batches, rocblas_datatype_f32_r, rocblas_gemm_algo_standard, + 0, flag))); +#else + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + if (prop->major >= 7 && at::globalContext().allowFP16AccumulationCuBLAS()) { + halpha = alpha; + hbeta = beta; + compute_type = CUDA_R_16F; + alpha_ptr = &halpha; + beta_ptr = &hbeta; + } + if (prop->major >= 5){ + TORCH_CUDABLAS_CHECK(cublasGemmStridedBatchedEx( + handle, opa, opb, m, n, k, + alpha_ptr, a, CUDA_R_16F, lda, stridea, + b, CUDA_R_16F, ldb, strideb, beta_ptr, + c, std::is_same_v ? CUDA_R_32F : CUDA_R_16F, ldc, stridec, + num_batches, compute_type, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); + } else { + for (const auto i : c10::irange(num_batches)) { + if (std::is_same_v) { + float* c_ptr = (float*)(c + i * stridec); + at::cuda::blas::gemm( + transa, transb, + m, n, k, + alpha, (a + i * stridea), lda, + (b + i * strideb), ldb, beta, + c_ptr, ldc); + } else { + at::cuda::blas::gemm( + transa, transb, + m, n, k, + alpha, (a + i * stridea), lda, + (b + i * strideb), ldb, beta, + (c + i * stridec), ldc); + } + } + } +#endif // USE_ROCM +} + +template +inline void bgemm_internal_cublas_bfloat16_helper(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, C_Dtype)) { + BGEMM_CHECK_ARGVALUES(at::BFloat16); + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + const float falpha = alpha; + const float fbeta = beta; + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + +#if defined(USE_ROCM) + auto compute_type = CUBLAS_COMPUTE_32F; +#else + auto compute_type = CUDA_R_32F; +#endif + TORCH_CUDABLAS_CHECK(cublasGemmStridedBatchedEx(handle, + opa, opb, (int)m, (int)n, (int)k, + (void*)&falpha, a, CUDA_R_16BF, (int)lda, stridea, + b, CUDA_R_16BF, (int)ldb, strideb, + (void*)&fbeta, c, std::is_same_v ? CUDA_R_32F : CUDA_R_16BF, + (int)ldc, stridec, (int)num_batches, + compute_type, + CUBLAS_GEMM_DEFAULT_TENSOR_OP)); +} + +template <> +void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES(at::Half)) { + bgemm_internal_cublas_half_helper(CUDABLAS_BGEMM_ARGS(at::Half)); +} + +template <> +void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)) { + bgemm_internal_cublas_half_helper(CUDABLAS_BGEMM_ARGS(at::Half)); +} + +template <> +void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16)) { + bgemm_internal_cublas_bfloat16_helper(CUDABLAS_BGEMM_ARGS(at::BFloat16)); +} + + +template <> +void bgemm_internal_cublas(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)) { + bgemm_internal_cublas_bfloat16_helper(CUDABLAS_BGEMM_ARGS(at::BFloat16)); +} + + +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(double)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { +#ifdef USE_ROCM + // hipblaslt does not support double gemm yet + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(double)); +#else + if (!bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGS(double))) { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(double)); + } +#endif + } + else { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(double)); + } +} + +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(float)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { + if (!bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGS(float))) { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(float)); + } + } + else { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(float)); + } +} + +template <> +void bgemm_internal>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { +#ifdef USE_ROCM + // hipblaslt does not support complex gemm yet + bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGS(c10::complex)); +#else + if (!bgemm_internal_cublaslt>(CUDABLAS_BGEMM_ARGS(c10::complex))) { + bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } +#endif + } + else { + bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } +} + +template <> +void bgemm_internal>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { +#ifdef USE_ROCM + // hipblaslt does not support complex gemm yet + bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGS(c10::complex)); +#else + if (!bgemm_internal_cublaslt>(CUDABLAS_BGEMM_ARGS(c10::complex))) { + bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } +#endif + } + else { + bgemm_internal_cublas>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } +} + +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(at::Half)) +{ + auto preferred = at::globalContext().blasPreferredBackend(); +#ifdef USE_ROCM + // hipBLASLt has no equivalent of rocblas_gemm_flags_fp16_alt_impl on gfx90a, + // so a backward fp16 GEMM on the hipBLASLt path silently flushes subnormals + // (issue #182952). Route fp16 backward GEMMs to rocBLAS so the + // ROCmBackwardPassGuard / fp16_alt_impl handling still applies. + if (preferred == BlasBackend::Cublaslt && + at::ROCmBackwardPassGuard::is_backward_pass() && + at::detail::getCUDAHooks().isGPUArch({"gfx90a"})) { + preferred = BlasBackend::Cublas; + } +#endif + if (preferred == BlasBackend::Cublaslt) { + if (!bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGS(at::Half))) { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::Half)); + } + } + else { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::Half)); + } +} + +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { + if (!bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGS(at::BFloat16))) { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } + } +#if defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM) + else if (at::globalContext().blasPreferredBackend() == BlasBackend::Ck) { + at::native::bgemm_internal_ck(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } +#endif + else { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } +} + +template<> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)) +{ + if (at::globalContext().allowFP16AccumulationCuBLAS()) { + // Do not allow fp16 reductions with fp32 output + TORCH_CHECK(false, "bgemm input type at::Half and output type float is not supported with allowFP16AccumulationCuBLAS"); + } + + auto preferred = at::globalContext().blasPreferredBackend(); +#ifdef USE_ROCM + // See bgemm_internal: reroute fp16 backward GEMMs off hipBLASLt on + // gfx90a to preserve subnormals (issue #182952). + if (preferred == BlasBackend::Cublaslt && + at::ROCmBackwardPassGuard::is_backward_pass() && + at::detail::getCUDAHooks().isGPUArch({"gfx90a"})) { + preferred = BlasBackend::Cublas; + } +#endif + if (preferred == BlasBackend::Cublaslt) { + if (!bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGS(at::Half))) { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::Half)); + } + } +#if defined(USE_ROCM) && !defined(_MSC_VER) + else if (preferred == BlasBackend::Ck) { + TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported for ROCm"); + } +#endif + else { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::Half)); + } +} + +template<> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { + if (!bgemm_internal_cublaslt(CUDABLAS_BGEMM_ARGS(at::BFloat16))) { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } + } +#if defined(USE_ROCM) && !defined(_MSC_VER) + else if (at::globalContext().blasPreferredBackend() == BlasBackend::Ck) { + TORCH_CHECK(false, "gemm input type at::BFloat16 and output type float is not supported for ROCm"); + } +#endif + else { + bgemm_internal_cublas(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } +} + +template +inline void bgemm_tunable(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + tunable::GemmStridedBatchedParams params; + params.transa = transa; + params.transb = transb; + params.m = m; + params.n = n; + params.k = k; + params.alpha = alpha; + params.a = a; + params.lda = lda; + params.stride_a = stridea; + params.b = b; + params.ldb = ldb; + params.stride_b = strideb; + params.beta = beta; + params.c = c; + params.ldc = ldc; + params.stride_c = stridec; + params.batch = num_batches; + + bool transa_ = ((transa != 'n') && (transa != 'N')); + bool transb_ = ((transb != 'n') && (transb != 'N')); + + if (transa_ && transb_) { + static tunable::GemmStridedBatchedTunableOp bgemm{}; + bgemm(¶ms); + } + else if (transa_ && !transb_) { + static tunable::GemmStridedBatchedTunableOp bgemm{}; + bgemm(¶ms); + } + else if (!transa_ && transb_) { + static tunable::GemmStridedBatchedTunableOp bgemm{}; + bgemm(¶ms); + } + else if (!transa_ && !transb_) { + static tunable::GemmStridedBatchedTunableOp bgemm{}; + bgemm(¶ms); + } + else { + TORCH_CHECK(false, "unreachable"); + } +} + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(double)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + bgemm_tunable(CUDABLAS_BGEMM_ARGS(double)); + } + else { + bgemm_internal(CUDABLAS_BGEMM_ARGS(double)); + } +} + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(float)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + bgemm_tunable(CUDABLAS_BGEMM_ARGS(float)); + } + else { + bgemm_internal(CUDABLAS_BGEMM_ARGS(float)); + } +} + +template <> +void bgemm>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + bgemm_tunable>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } + else { + bgemm_internal>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } +} + +template <> +void bgemm>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + bgemm_tunable>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } + else { + bgemm_internal>(CUDABLAS_BGEMM_ARGS(c10::complex)); + } +} + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(at::Half)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + bgemm_tunable(CUDABLAS_BGEMM_ARGS(at::Half)); + } + else { + bgemm_internal(CUDABLAS_BGEMM_ARGS(at::Half)); + } +} + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + bgemm_tunable(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } + else { + bgemm_internal(CUDABLAS_BGEMM_ARGS(at::BFloat16)); + } +} + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)) { + // TODO: Support tuning for Half inputs and FP32 output + bgemm_internal(CUDABLAS_BGEMM_ARGS(at::Half)); +} + + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)) { + #ifndef USE_ROCM + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + + if (prop->major < 8) + TORCH_CHECK(false, "bgemm input type at::BFloat16 and output type float is only supported for CUDA devices with compute capability 8.0 or higher"); + #endif + // TODO: Support tuning for BFloat16 inputs and FP32 output + bgemm_internal(CUDABLAS_BGEMM_ARGS(at::BFloat16)); +} + + + +template +inline void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + TORCH_CHECK(false, "at::cuda::blas::gemm: not implemented for input type ", typeid(Dtype).name(), " and output type ", typeid(C_Dtype).name()); +} + +template <> +void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES(double)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + GEMM_CHECK_ARGVALUES(double); + TORCH_CUDABLAS_CHECK(cublasDgemm( + handle, opa, opb, m, n, k, &alpha, a, lda, b, ldb, &beta, c, ldc)); +} + +template <> +void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES(float)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + GEMM_CHECK_ARGVALUES(float); + TORCH_CUDABLAS_CHECK(cublasSgemm( + handle, opa, opb, m, n, k, &alpha, a, lda, b, ldb, &beta, c, ldc)); +} + +template <> +void gemm_internal_cublas>(CUDABLAS_GEMM_ARGTYPES(c10::complex)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + GEMM_CHECK_ARGVALUES(c10::complex); + TORCH_CUDABLAS_CHECK(cublasZgemm( + handle, opa, opb, m, n, k, reinterpret_cast(&alpha), reinterpret_cast(a), + lda, reinterpret_cast(b), ldb, reinterpret_cast(&beta), + reinterpret_cast(c), ldc)); +} + +template <> +void gemm_internal_cublas>(CUDABLAS_GEMM_ARGTYPES(c10::complex)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + GEMM_CHECK_ARGVALUES(c10::complex); + TORCH_CUDABLAS_CHECK(cublasCgemm( + handle, opa, opb, m, n, k, reinterpret_cast(&alpha), reinterpret_cast(a), + lda, reinterpret_cast(b), ldb, reinterpret_cast(&beta), + reinterpret_cast(c), ldc)); +} + +template +inline void gemm_internal_cublas_half_helper(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, C_Dtype)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + float falpha = alpha; + float fbeta = beta; +#ifndef USE_ROCM + at::Half halpha; + at::Half hbeta; + auto compute_type = CUDA_R_32F; +#endif + void * alpha_ptr = &falpha; + void * beta_ptr = &fbeta; + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + GEMM_CHECK_ARGVALUES(at::Half); +#ifdef USE_ROCM + int flag = 0; + rocblas_datatype c_type = std::is_same::value ? rocblas_datatype_f32_r : rocblas_datatype_f16_r; + rocblas_datatype d_type = c_type; +#if USE_GEMM_FLAGS_FP16_ALT_IMPL + flag = at::ROCmBackwardPassGuard::is_backward_pass() ? rocblas_gemm_flags_fp16_alt_impl : 0; +#endif + TORCH_CUDABLAS_CHECK(rocBLASStatusToHIPStatus(rocblas_gemm_ex( + (rocblas_handle)handle, + hipOperationToRocOperation(opa), + hipOperationToRocOperation(opb), + m, + n, + k, + alpha_ptr, + a, + rocblas_datatype_f16_r, + lda, + b, + rocblas_datatype_f16_r, + ldb, + beta_ptr, + c, + c_type, + ldc, + c, + d_type, + ldc, + rocblas_datatype_f32_r, + rocblas_gemm_algo_standard, + 0, + flag))); +#else + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + if (prop->major >= 7 && at::globalContext().allowFP16AccumulationCuBLAS()) { + compute_type = CUDA_R_16F; + halpha = alpha; + hbeta = beta; + alpha_ptr = &halpha; + beta_ptr = &hbeta; + } + if (prop->major >= 5) { + cublasMath_t cublas_flags = CUBLAS_DEFAULT_MATH; + auto fp16_reduction = at::globalContext().allowFP16ReductionCuBLAS(); + TORCH_CHECK(fp16_reduction != + at::CuBLASReductionOption::DisallowReducedPrecisionDisallowSplitK, + "torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction(" + "..., allow_splitk=False) requires the cuBLASLt backend"); + if (fp16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + cublas_flags = static_cast( + cublas_flags | CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION); + } + // Disallow fp16 reductions that could lead to unexpected overflow issues. + TORCH_CUDABLAS_CHECK(cublasSetMathMode(handle, cublas_flags)); + TORCH_CUDABLAS_CHECK(cublasGemmEx( + handle, + opa, + opb, + m, + n, + k, + alpha_ptr, + a, + CUDA_R_16F, + lda, + b, + CUDA_R_16F, + ldb, + beta_ptr, + c, + std::is_same_v ? CUDA_R_32F : CUDA_R_16F, + ldc, + compute_type, + CUBLAS_GEMM_DEFAULT_TENSOR_OP)); + TORCH_CUDABLAS_CHECK(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); + } else { + TORCH_CUDABLAS_CHECK(cublasSgemmEx( + handle, + opa, + opb, + m, + n, + k, + &falpha, + a, + CUDA_R_16F, + lda, + b, + CUDA_R_16F, + ldb, + &fbeta, + c, + std::is_same_v ? CUDA_R_32F : CUDA_R_16F, + ldc)); + } +#endif +} + +template +inline void gemm_internal_cublas_bfloat16_helper(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, C_Dtype)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + CUBLAS_SM_CARVEOUT_GUARD(handle); + cublasOperation_t opa = detail::cublasOpFromChar(transa); + cublasOperation_t opb = detail::cublasOpFromChar(transb); + float falpha = alpha; + float fbeta = beta; + detail::cublasAdjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); + GEMM_CHECK_ARGVALUES(at::BFloat16); +#ifndef USE_ROCM + cublasMath_t cublas_flags = CUBLAS_DEFAULT_MATH; + auto bf16_reduction = at::globalContext().allowBF16ReductionCuBLAS(); + TORCH_CHECK(bf16_reduction != + at::CuBLASReductionOption::DisallowReducedPrecisionDisallowSplitK, + "torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction(" + "..., allow_splitk=False) requires the cuBLASLt backend"); + if (bf16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + cublas_flags = static_cast( + cublas_flags | CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION); + } +#endif +#if defined(USE_ROCM) + auto compute_type = CUBLAS_COMPUTE_32F; +#else + auto compute_type = CUDA_R_32F; +#endif + TORCH_CUDABLAS_CHECK(cublasSetMathMode(handle, cublas_flags)); + TORCH_CUDABLAS_CHECK(cublasGemmEx( + handle, + opa, + opb, + m, + n, + k, + &falpha, + a, + CUDA_R_16BF, + lda, + b, + CUDA_R_16BF, + ldb, + &fbeta, + c, + std::is_same_v ? CUDA_R_32F : CUDA_R_16BF, + ldc, + compute_type, + CUBLAS_GEMM_DEFAULT_TENSOR_OP)); + TORCH_CUDABLAS_CHECK(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); +} + +template <> +void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES(at::Half)) { + gemm_internal_cublas_half_helper(CUDABLAS_GEMM_ARGS(at::Half)); +} + +template <> +void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)) { + gemm_internal_cublas_half_helper(CUDABLAS_GEMM_ARGS(at::Half)); +} + +template <> +void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES(at::BFloat16)) { + gemm_internal_cublas_bfloat16_helper(CUDABLAS_GEMM_ARGS(at::BFloat16)); +} + +template <> +void gemm_internal_cublas(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)) { + gemm_internal_cublas_bfloat16_helper(CUDABLAS_GEMM_ARGS(at::BFloat16)); +} + +template +inline void gemm_internal_cublaslt(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + // forward to bgemm implementation but set strides and batches to 0 + if (!bgemm_internal_cublaslt(transa, transb, m, n, k, alpha, a, lda, 0, b, ldb, 0, beta, c, ldc, 0, 0)) { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(Dtype)); + } +} + +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(double)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { +#ifdef USE_ROCM + // hipblaslt does not support double gemm yet + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(double)); +#else + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(double)); +#endif + } +#if defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM) + else if (at::globalContext().blasPreferredBackend() == BlasBackend::Ck) { + at::native::gemm_internal_ck(CUDABLAS_GEMM_ARGS(double)); + } +#endif + else { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(double)); + } +} + +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(float)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(float)); + } +#if defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM) + else if (at::globalContext().blasPreferredBackend() == BlasBackend::Ck) { + if (at::detail::getCUDAHooks().isGPUArch({"gfx11", "gfx12"})) { //no CK GEMM version + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(float)); + } else{ + at::native::gemm_internal_ck(CUDABLAS_GEMM_ARGS(float)); + } + } +#endif + else { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(float)); + } +} + +template <> +void gemm_internal>(CUDABLAS_GEMM_ARGTYPES(c10::complex)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { +#ifdef USE_ROCM + // hipblaslt does not support complex gemm yet + gemm_internal_cublas>(CUDABLAS_GEMM_ARGS(c10::complex)); +#else + gemm_internal_cublaslt>(CUDABLAS_GEMM_ARGS(c10::complex)); +#endif + } + else { + gemm_internal_cublas>(CUDABLAS_GEMM_ARGS(c10::complex)); + } +} + +template <> +void gemm_internal>(CUDABLAS_GEMM_ARGTYPES(c10::complex)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { +#ifdef USE_ROCM + // hipblaslt does not support complex gemm yet + gemm_internal_cublas>(CUDABLAS_GEMM_ARGS(c10::complex)); +#else + gemm_internal_cublaslt>(CUDABLAS_GEMM_ARGS(c10::complex)); +#endif + } + else { + gemm_internal_cublas>(CUDABLAS_GEMM_ARGS(c10::complex)); + } +} + +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(at::Half)) +{ + auto preferred = at::globalContext().blasPreferredBackend(); +#ifdef USE_ROCM + // hipBLASLt has no equivalent of rocblas_gemm_flags_fp16_alt_impl on gfx90a, + // so a backward fp16 GEMM on the hipBLASLt path silently flushes subnormals + // (issue #182952). Route fp16 backward GEMMs to rocBLAS so the + // ROCmBackwardPassGuard / fp16_alt_impl handling still applies. + if (preferred == BlasBackend::Cublaslt && + at::ROCmBackwardPassGuard::is_backward_pass() && + at::detail::getCUDAHooks().isGPUArch({"gfx90a"})) { + preferred = BlasBackend::Cublas; + } +#endif + if (preferred == BlasBackend::Cublaslt) { + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(at::Half)); + } +#if defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM) + else if (preferred == BlasBackend::Ck) { + at::native::gemm_internal_ck(CUDABLAS_GEMM_ARGS(at::Half)); + } +#endif + else { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(at::Half)); + } +} + +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(at::BFloat16)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } +#if defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM) + else if (at::globalContext().blasPreferredBackend() == BlasBackend::Ck) { + at::native::gemm_internal_ck(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } +#endif + else { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } +} + +template<> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)) +{ + if (at::globalContext().allowFP16AccumulationCuBLAS()) { + // Do not allow fp16 reductions with fp32 output + TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported with allowFP16AccumulationCuBLAS"); + } + + auto preferred = at::globalContext().blasPreferredBackend(); +#ifdef USE_ROCM + // See gemm_internal: reroute fp16 backward GEMMs off hipBLASLt on + // gfx90a to preserve subnormals (issue #182952). + if (preferred == BlasBackend::Cublaslt && + at::ROCmBackwardPassGuard::is_backward_pass() && + at::detail::getCUDAHooks().isGPUArch({"gfx90a"})) { + preferred = BlasBackend::Cublas; + } +#endif + if (preferred == BlasBackend::Cublaslt) { + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(at::Half)); + } +#if defined(USE_ROCM) && !defined(_MSC_VER) + else if (preferred == BlasBackend::Ck) { + TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported for ROCm"); + } +#endif + else { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(at::Half)); + } +} + +template<> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)) +{ + if (at::globalContext().blasPreferredBackend() == BlasBackend::Cublaslt) { + gemm_internal_cublaslt(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } +#if defined(USE_ROCM) && !defined(_MSC_VER) + else if (at::globalContext().blasPreferredBackend() == BlasBackend::Ck) { + TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported for ROCm"); + } +#endif + else { + gemm_internal_cublas(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } +} + +template +inline void gemm_tunable(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(DType, C_Dtype)) { + tunable::GemmParams params; + params.transa = transa; + params.transb = transb; + params.m = m; + params.n = n; + params.k = k; + params.alpha = alpha; + params.a = a; + params.lda = lda; + params.b = b; + params.ldb = ldb; + params.beta = beta; + params.c = c; + params.ldc = ldc; + + bool transa_ = ((transa != 'n') && (transa != 'N')); + bool transb_ = ((transb != 'n') && (transb != 'N')); + + if (transa_ && transb_) { + static tunable::GemmTunableOp gemm{}; + gemm(¶ms); + } + else if (transa_ && !transb_) { + static tunable::GemmTunableOp gemm{}; + gemm(¶ms); + } + else if (!transa_ && transb_) { + static tunable::GemmTunableOp gemm{}; + gemm(¶ms); + } + else if (!transa_ && !transb_) { + static tunable::GemmTunableOp gemm{}; + gemm(¶ms); + } + else { + TORCH_CHECK(false, "unreachable"); + } +} + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(double)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + gemm_tunable(CUDABLAS_GEMM_ARGS(double)); + } + else { + gemm_internal(CUDABLAS_GEMM_ARGS(double)); + } +} + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(float)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + gemm_tunable(CUDABLAS_GEMM_ARGS(float)); + } + else { + gemm_internal(CUDABLAS_GEMM_ARGS(float)); + } +} + +template <> +void gemm>(CUDABLAS_GEMM_ARGTYPES(c10::complex)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + gemm_tunable>(CUDABLAS_GEMM_ARGS(c10::complex)); + } + else { + gemm_internal>(CUDABLAS_GEMM_ARGS(c10::complex)); + } +} + +template <> +void gemm>(CUDABLAS_GEMM_ARGTYPES(c10::complex)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + gemm_tunable>(CUDABLAS_GEMM_ARGS(c10::complex)); + } + else { + gemm_internal>(CUDABLAS_GEMM_ARGS(c10::complex)); + } +} + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(at::Half)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + gemm_tunable(CUDABLAS_GEMM_ARGS(at::Half)); + } + else { + gemm_internal(CUDABLAS_GEMM_ARGS(at::Half)); + } +} + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(at::BFloat16)) { + auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + gemm_tunable(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } + else { + gemm_internal(CUDABLAS_GEMM_ARGS(at::BFloat16)); + } +} + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)) { + // TODO: Support Tuning for fp16-fp32 gemm + gemm_internal(CUDABLAS_GEMM_ARGS(at::Half)); +} + + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)) { + #ifndef USE_ROCM + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + + if (prop->major < 8) + TORCH_CHECK(false, "gemm input type at::BFloat16 and output type float is only supported for CUDA devices with compute capability 8.0 or higher"); + #endif + // TODO: Support Tuning for bf16-fp32 gemm + gemm_internal(CUDABLAS_GEMM_ARGS(at::BFloat16)); +} + + +template +bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const Dtype* mat1_ptr, + int64_t mat1_ld, + const Dtype* mat2_ptr, + int64_t mat2_ld, + const Dtype* bias, + C_Dtype* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation) { + + if (std::is_same_v && std::is_same_v) { + #ifdef USE_ROCM + TORCH_CHECK(false, "gemm input type at::BFloat16 and output type float is not supported for ROCm"); + #endif + } else if (std::is_same_v && std::is_same_v) { + #ifdef USE_ROCM + TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported for ROCm"); + #endif + if (at::globalContext().allowFP16AccumulationCuBLAS()) + TORCH_CHECK(false, "gemm input type at::Half and output type float is not supported with allowFP16AccumulationCuBLAS"); + } + + using opmath_t = at::opmath_type; + opmath_t beta_val = bias ? 0 : 1; // bias is added in epilogue unless nullptr + + const auto type_info = detail::getCublasLtTypeInfo(); + const cudaDataType_t abType = type_info.ab_type; + const cudaDataType_t cType = type_info.c_type; + const cublasComputeType_t computeType = type_info.compute_type; + const cudaDataType_t scaleType = type_info.scale_type; + CuBlasLtMatmulPreference preference; + void * alpha_ptr = &alpha_val; + void * beta_ptr = &beta_val; +#ifndef USE_ROCM + at::Half halpha_val; + at::Half hbeta_val; +#endif + if constexpr (std::is_same_v) { +#ifndef USE_ROCM + if (computeType == CUBLAS_COMPUTE_16F) { + halpha_val = alpha_val; + hbeta_val = beta_val; + alpha_ptr = &halpha_val; + beta_ptr = &hbeta_val; + } +#endif + } +#ifndef USE_ROCM + if constexpr (std::is_same_v) { + auto fp16_reduction = at::globalContext().allowFP16ReductionCuBLAS(); + if (fp16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + uint32_t mask = + fp16_reduction == + at::CuBLASReductionOption::DisallowReducedPrecisionAllowSplitK + ? (CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE | + CUBLASLT_REDUCTION_SCHEME_NONE) + : CUBLASLT_REDUCTION_SCHEME_NONE; + preference.setAttribute( + CUBLASLT_MATMUL_PREF_REDUCTION_SCHEME_MASK, mask); + } + } else if constexpr (std::is_same_v) { + auto bf16_reduction = at::globalContext().allowBF16ReductionCuBLAS(); + if (bf16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + uint32_t mask = + bf16_reduction == + at::CuBLASReductionOption::DisallowReducedPrecisionAllowSplitK + ? (CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE | + CUBLASLT_REDUCTION_SCHEME_NONE) + : CUBLASLT_REDUCTION_SCHEME_NONE; + preference.setAttribute( + CUBLASLT_MATMUL_PREF_REDUCTION_SCHEME_MASK, mask); + } + } +#endif + + CuBlasLtMatmulDescriptor computeDesc(computeType, scaleType); + cublasOperation_t transa = transpose_mat1 ? CUBLAS_OP_T : CUBLAS_OP_N; + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSA, transa); + cublasOperation_t transb = transpose_mat2 ? CUBLAS_OP_T : CUBLAS_OP_N; + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSB, transb); + auto stream = at::cuda::getCurrentCUDAStream(); +#ifndef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + computeDesc.setAttribute( + CUBLASLT_MATMUL_DESC_SM_COUNT_TARGET, + at::cuda::getCurrentDeviceProperties()->multiProcessorCount - + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + } +#else + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + stream = _getCarveoutStream( + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + _syncCurrentWithCarveoutStream(stream, true); + } +#endif + const cublasLtEpilogue_t epilogue = + detail::cublasLtEpilogue(activation, bias); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_EPILOGUE, epilogue); + + if (bias) { + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_BIAS_POINTER, bias); + } + + CuBlasLtMatrixLayout Adesc(abType, m, k, mat1_ld, transpose_mat1); + CuBlasLtMatrixLayout Bdesc(abType, k, n, mat2_ld, transpose_mat2); + CuBlasLtMatrixLayout Cdesc(cType, m, n, result_ld); + + auto ltworkspace = CublasLtWorkspace(); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, ltworkspace.size); + +#ifndef USE_ROCM + uint32_t a_alignment = detail::getAlignment(reinterpret_cast(mat1_ptr)); + uint32_t b_alignment = detail::getAlignment(reinterpret_cast(mat2_ptr)); + uint32_t c_alignment = detail::getAlignment(reinterpret_cast(result_ptr)); + uint32_t d_alignment = detail::getAlignment(reinterpret_cast(bias)); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_A_BYTES, a_alignment); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_B_BYTES, b_alignment); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_C_BYTES, c_alignment); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_D_BYTES, d_alignment); +#endif + + cublasLtMatmulHeuristicResult_t heuristicResult = {}; + int returnedResult = 0; + cublasLtHandle_t ltHandle = at::cuda::getCurrentCUDABlasLtHandle(); + TORCH_CUDABLAS_CHECK(cublasLtMatmulAlgoGetHeuristic( + ltHandle, + computeDesc.descriptor(), + Adesc.descriptor(), + Bdesc.descriptor(), + Cdesc.descriptor(), + Cdesc.descriptor(), + preference.descriptor(), + 1, + &heuristicResult, + &returnedResult)); + cublasStatus_t cublasStatus = CUBLAS_STATUS_SUCCESS; + if (returnedResult == 0) { + cublasStatus = CUBLAS_STATUS_NOT_SUPPORTED; + } + else { + cublasStatus = cublasLtMatmul( + ltHandle, + computeDesc.descriptor(), + alpha_ptr, + mat1_ptr, + Adesc.descriptor(), + mat2_ptr, + Bdesc.descriptor(), + beta_ptr, + result_ptr, + Cdesc.descriptor(), + result_ptr, + Cdesc.descriptor(), + &heuristicResult.algo, + ltworkspace.ptr, + ltworkspace.size, + stream); +#ifdef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + _syncCurrentWithCarveoutStream(stream, false); + } +#endif + } + if (cublasStatus != CUBLAS_STATUS_SUCCESS) { + TORCH_WARN( + "gemm_and_bias error: ", + at::cuda::blas::_cublasGetErrorEnum(cublasStatus), + " when calling cublasLtMatmul with transpose_mat1 ", + transpose_mat1, + " transpose_mat2 ", + transpose_mat2, + " m ", + m, + " n ", + n, + " k ", + k, + " mat1_ld ", + mat1_ld, + " mat2_ld ", + mat2_ld, + " result_ld ", + result_ld, + " abType ", + abType, + " cType ", + cType, + " computeType ", + computeType, + " scaleType ", + scaleType, + ". Will attempt to recover by calling unfused cublas path."); + return false; + } + return true; +} + +template bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const double* mat1_ptr, + int64_t mat1_ld, + const double* mat2_ptr, + int64_t mat2_ld, + const double* bias, + double* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation); + +template bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const float* mat1_ptr, + int64_t mat1_ld, + const float* mat2_ptr, + int64_t mat2_ld, + const float* bias, + float* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation); + +template bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const at::Half* mat1_ptr, + int64_t mat1_ld, + const at::Half* mat2_ptr, + int64_t mat2_ld, + const at::Half* bias, + at::Half* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation); + +template bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const at::Half* mat1_ptr, + int64_t mat1_ld, + const at::Half* mat2_ptr, + int64_t mat2_ld, + const at::Half* bias, + float* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation); + +template bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const at::BFloat16* mat1_ptr, + int64_t mat1_ld, + const at::BFloat16* mat2_ptr, + int64_t mat2_ld, + const at::BFloat16* bias, + at::BFloat16* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation); + +template bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const at::BFloat16* mat1_ptr, + int64_t mat1_ld, + const at::BFloat16* mat2_ptr, + int64_t mat2_ld, + const at::BFloat16* bias, + float* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation); + +using at::blas::ScalingType; + +void scaled_gemm( + char transa, + char transb, + int64_t m, + int64_t n, + int64_t k, + const void* mat1_ptr, + const void* mat1_scale_ptr, + int64_t mat1_ld, + ScalarType mat1_dtype, + ScalarType mat1_scale_dtype, + ScalingType mat1_scaling_type, + const void* mat2_ptr, + const void* mat2_scale_ptr, + int64_t mat2_ld, + ScalarType mat2_dtype, + ScalarType mat2_scale_dtype, + ScalingType mat2_scaling_type, + const void* bias_ptr, + ScalarType bias_dtype, + void* result_ptr, + const void *result_scale_ptr, + int64_t result_ld, + ScalarType result_dtype, + bool use_fast_accum, + const std::optional& alpha) { + // Note: see `cublasCommonArgs` for various non-intuitive manipulations + // of input arguments to this function. + const auto computeType = CUBLAS_COMPUTE_32F; + const auto scaleType = CUDA_R_32F; + // Note: alpha_val may change later depending on user-passed argument + float alpha_val = 1.0; + float beta_val = 0.0; +#ifndef USE_ROCM + // Note: unused, but cublasLtMatmul requires a C pointer that is not result_ptr or nullptr + const void* dummy_C_ptr = mat1_ptr; +#endif // ifndef USE_ROCM + CuBlasLtMatmulDescriptor computeDesc(computeType, scaleType); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSA, detail::cublasOpFromChar(transa)); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSB, detail::cublasOpFromChar(transb)); + cublasLtMatmulDescAttributes_t matmulDescA = CUBLASLT_MATMUL_DESC_A_SCALE_POINTER; + cublasLtMatmulDescAttributes_t matmulDescB = CUBLASLT_MATMUL_DESC_B_SCALE_POINTER; +#if defined(USE_ROCM) && !defined(HIPBLASLT_OUTER_VEC) && defined(HIPBLASLT_VEC_EXT) + // hipblaslt supported row-wise before cublas, and did so their own way (via + // the SCALE_POINTERSs), but then migrated to match how cublas does it (via + // the SCALE_MODEs). Here we check for this early custom mode. + bool use_rowwise = (mat1_scaling_type == ScalingType::RowWise && mat2_scaling_type == ScalingType::RowWise); + if (use_rowwise) { + matmulDescA = HIPBLASLT_MATMUL_DESC_A_SCALE_POINTER_VEC_EXT; + matmulDescB = HIPBLASLT_MATMUL_DESC_B_SCALE_POINTER_VEC_EXT; + } + else if (mat1_scale_dtype == kFloat8_e8m0fnu && mat2_scale_dtype == kFloat8_e8m0fnu) { + #if ROCM_VERSION >= 70000 + if (at::detail::getCUDAHooks().isGPUArch({"gfx950"})) { + // TODO: add constraints based on hipblaslt internals + TORCH_CHECK((m % 16 == 0) && (n % 16 == 0) && (k % 128 == 0), + "M, N must be multiples of 16 and K should be multiple of 128 for MX format. " + "Got m=", m, ", n=", n, ", k=", k); + } + #endif + } +#elif (CUDA_VERSION < 12090) && !defined(USE_ROCM) + // hipblaslt supported row-wise before cublas, and did so their own way (via + // the SCALE_POINTERSs), but then migrated to match how cublas does it (via + // the SCALE_MODEs). Here we check for this early custom mode. + bool use_rowwise = (mat1_scaling_type == ScalingType::RowWise && mat2_scaling_type == ScalingType::RowWise); + // rowwise isn't supported using older cublaslt or older hipblaslt + TORCH_INTERNAL_ASSERT(use_rowwise == false, "rowwise scaled_gemm not supported with blaslt"); +#endif // if defined(USE_ROCM) && !defined(HIPBLASLT_OUTER_VEC) && defined(HIPBLASLT_VEC_EXT) + computeDesc.setAttribute(matmulDescA, mat1_scale_ptr); + computeDesc.setAttribute(matmulDescB, mat2_scale_ptr); + if (result_scale_ptr != nullptr) { + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_D_SCALE_POINTER, result_scale_ptr); + } + auto stream = at::cuda::getCurrentCUDAStream(); +#ifndef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + computeDesc.setAttribute( + CUBLASLT_MATMUL_DESC_SM_COUNT_TARGET, + at::cuda::getCurrentDeviceProperties()->multiProcessorCount - + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + } +#else + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + stream = _getCarveoutStream( + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + _syncCurrentWithCarveoutStream(stream, true); + } +#endif // ifndef USE_ROCM +#ifndef USE_ROCM + const int8_t fastAccuMode = use_fast_accum ? 1 : 0; + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_FAST_ACCUM, fastAccuMode); +#endif // ifndef USE_ROCM + CuBlasLtMatrixLayout Adesc(ScalarTypeToCudaDataType(mat1_dtype), m, k, mat1_ld, transa == 't'); + CuBlasLtMatrixLayout Bdesc(ScalarTypeToCudaDataType(mat2_dtype), k, n, mat2_ld, transb == 't'); +#ifdef USE_ROCM + // Cdesc is unused, beta is 0. But hipblaslt needs this set to something reasonable. + CuBlasLtMatrixLayout Cdesc(ScalarTypeToCudaDataType(result_dtype), m, n, result_ld); +#else + CuBlasLtMatrixLayout Cdesc(ScalarTypeToCudaDataType(bias_dtype), m, n, result_ld); +#endif // ifdef USE_ROCM + CuBlasLtMatrixLayout Ddesc(ScalarTypeToCudaDataType(result_dtype), m, n, result_ld); + if (bias_ptr) { + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_BIAS_POINTER, bias_ptr); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_EPILOGUE, CUBLASLT_EPILOGUE_BIAS); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_BIAS_DATA_TYPE, ScalarTypeToCudaDataType(bias_dtype)); + } + + // Handle user-passed alpha + float *alpha_ptr = &alpha_val; + float *beta_ptr = &beta_val; + + if (alpha.has_value()) { + auto& a = alpha.value(); + + // if device-tensor + if (a.is_cuda()) { + // NOTE: there are lifetime requirements on device-side pointers for alpha/beta -- the value must be + // valid & correct until the cublas call finishes (not is scheduled like host-side values). Thus + // we need to use allocations for alpha/beta that have some guarantees on lifetime - a statically + // managed 4B buffer for alpha that we'll copy the passed alpha value into, and constant memory + // for beta respectively. + float *user_alpha_ptr = at::cuda::detail::get_user_alpha_ptr(); + at::Tensor user_alpha = at::from_blob(user_alpha_ptr, {1}, TensorOptions().device(kCUDA).dtype(kFloat)); + user_alpha.copy_(a); + // Tell cublasLt we're using device-side pointers for alpha/beta + auto pointer_mode = CUBLASLT_POINTER_MODE_DEVICE; + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_POINTER_MODE, pointer_mode); + alpha_ptr = user_alpha.data_ptr(); + beta_ptr = at::cuda::detail::get_cublas_device_zero(); + } else { + alpha_val = a.item(); + } + } + // For other data types, use the get_scale_mode function based on scaling type + // The SCALE_MODE attrs only exist in cuBLAS 12.8+/ROCm 7.0 or in recent hipblaslt, + // but we must invoke get_scale_mode anyways to trigger the version checks. + // Note that AMD/ROCm follows OCP Spec 1.0, which is different from NVIDIA's implementation. See get_scale_mode() for details. + [[maybe_unused]] int a_scale_mode = detail::cublasLtMatmulScaleMode(mat1_scaling_type, mat1_scale_dtype, use_fast_accum); + [[maybe_unused]] int b_scale_mode = detail::cublasLtMatmulScaleMode(mat2_scaling_type, mat2_scale_dtype, use_fast_accum); +#if CUDA_VERSION >= 12080 || (defined(USE_ROCM) && ROCM_VERSION >= 70000 && defined(HIPBLASLT_OUTER_VEC)) + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_A_SCALE_MODE, a_scale_mode); + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_B_SCALE_MODE, b_scale_mode); +#endif // if CUDA_VERSION >= 12080 || (defined(USE_ROCM) && ROCM_VERSION >= 70000 && defined(HIPBLASLT_OUTER_VEC)) + + CuBlasLtMatmulPreference preference; + auto ltworkspace = CublasLtWorkspace(); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, ltworkspace.size); + cublasLtMatmulHeuristicResult_t heuristicResult = {}; + int returnedResult = 0; + cublasLtHandle_t ltHandle = at::cuda::getCurrentCUDABlasLtHandle(); + + TORCH_CUDABLAS_CHECK(cublasLtMatmulAlgoGetHeuristic( + ltHandle, + computeDesc.descriptor(), + Adesc.descriptor(), + Bdesc.descriptor(), + Cdesc.descriptor(), + Ddesc.descriptor(), + preference.descriptor(), + 1, + &heuristicResult, + &returnedResult)); + if (returnedResult == 0) { +#ifndef USE_ROCM + TORCH_CUDABLAS_CHECK(CUBLAS_STATUS_NOT_SUPPORTED); +#else + // hipblaslt might be able to recover by returning all algos + std::vector all_algos; + TORCH_CUDABLAS_CHECK(hipblaslt_ext::getAllAlgos( + ltHandle, + hipblaslt_ext::GemmType::HIPBLASLT_GEMM, + detail::cublasOpFromChar(transa), + detail::cublasOpFromChar(transb), + ScalarTypeToCudaDataType(mat1_dtype), + ScalarTypeToCudaDataType(mat2_dtype), + // C is nullptr and beta=0, so set to something reasonable. See above. + //ScalarTypeToCudaDataType(bias_dtype), + ScalarTypeToCudaDataType(result_dtype), + ScalarTypeToCudaDataType(result_dtype), + CUBLAS_COMPUTE_32F, + all_algos)); + if (all_algos.size() == 0) { + TORCH_CUDABLAS_CHECK(CUBLAS_STATUS_NOT_SUPPORTED); + } + // pick first valid solution + bool found = false; + for (size_t i = 0; i < all_algos.size(); i++) { + size_t ret_workspace_size = 0; + auto is_valid_status = hipblaslt_ext::matmulIsAlgoSupported( + ltHandle, + computeDesc.descriptor(), + alpha_ptr, + Adesc.descriptor(), + Bdesc.descriptor(), + beta_ptr, + Cdesc.descriptor(), + Ddesc.descriptor(), + all_algos[i].algo, + ret_workspace_size); + if (is_valid_status == HIPBLAS_STATUS_SUCCESS) { + if (ret_workspace_size <= ltworkspace.size) { + heuristicResult = all_algos[i]; + found = true; + break; + } + } + } + TORCH_CHECK(found, "could not find valid hipblaslt solution"); +#endif // ifndef USE_ROCM + } + cublasStatus_t cublasStatus = cublasLtMatmul( + ltHandle, + computeDesc.descriptor(), + alpha_ptr, + mat1_ptr, + Adesc.descriptor(), + mat2_ptr, + Bdesc.descriptor(), + beta_ptr, +#ifdef USE_ROCM + result_ptr, // unused, since beta_val is 0, but hipblaslt can't handle nullptr +#else + dummy_C_ptr, // also unused, but cuBLAS can't use nullptr or result_ptr +#endif // ifdef USE_ROCM + Cdesc.descriptor(), + result_ptr, + Ddesc.descriptor(), + &heuristicResult.algo, + ltworkspace.ptr, + ltworkspace.size, + stream); +#ifdef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + _syncCurrentWithCarveoutStream(stream, false); + } +#endif + TORCH_CHECK( + cublasStatus == CUBLAS_STATUS_SUCCESS, + "CUDA error: ", + at::cuda::blas::_cublasGetErrorEnum(cublasStatus), + " when calling cublasLtMatmul with transpose_mat1 ", + transa, + " transpose_mat2 ", + transb, + " m ", + m, + " n ", + n, + " k ", + k, + " mat1_ld ", + mat1_ld, + " mat2_ld ", + mat2_ld, + " result_ld ", + result_ld, + " computeType ", + computeType, + " scaleType ", + scaleType); + return; +} + +void int8_gemm( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + const int8_t* mat1_ptr, + int64_t mat1_ld, + const int8_t* mat2_ptr, + int64_t mat2_ld, + int32_t* result_ptr, + int64_t result_ld) { + + cublasComputeType_t computeType = CUBLAS_COMPUTE_32I; + cudaDataType_t scaleType = CUDA_R_32I; + + cudaDataType_t abType = CUDA_R_8I; + cudaDataType_t cType = CUDA_R_32I; + + CuBlasLtMatmulDescriptor computeDesc(computeType, scaleType); + cublasOperation_t transa = transpose_mat1 ? CUBLAS_OP_T : CUBLAS_OP_N; + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSA, transa); + cublasOperation_t transb = transpose_mat2 ? CUBLAS_OP_T : CUBLAS_OP_N; + computeDesc.setAttribute(CUBLASLT_MATMUL_DESC_TRANSB, transb); + auto stream = at::cuda::getCurrentCUDAStream(); +#ifndef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + computeDesc.setAttribute( + CUBLASLT_MATMUL_DESC_SM_COUNT_TARGET, + at::cuda::getCurrentDeviceProperties()->multiProcessorCount - + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + } +#else + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + stream = _getCarveoutStream( + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + _syncCurrentWithCarveoutStream(stream, true); + } +#endif + + CuBlasLtMatrixLayout Adesc(abType, m, k, mat1_ld, transpose_mat1); + CuBlasLtMatrixLayout Bdesc(abType, k, n, mat2_ld, transpose_mat2); + CuBlasLtMatrixLayout Cdesc(cType, m, n, result_ld); + + // cublas team: alpha and beta need to be the same dtype as of scaleType + at::opmath_type alpha_val = 1; + int32_t beta_val = 0; + cublasLtHandle_t ltHandle = at::cuda::getCurrentCUDABlasLtHandle(); + +#ifdef USE_ROCM + CuBlasLtMatmulPreference preference; + auto ltworkspace = CublasLtWorkspace(); + preference.setAttribute(CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, ltworkspace.size); + cublasLtMatmulHeuristicResult_t heuristicResult = {}; + int returnedResult = 0; + TORCH_CUDABLAS_CHECK(cublasLtMatmulAlgoGetHeuristic( + ltHandle, + computeDesc.descriptor(), + Adesc.descriptor(), + Bdesc.descriptor(), + Cdesc.descriptor(), + Cdesc.descriptor(), + preference.descriptor(), + 1, + &heuristicResult, + &returnedResult)); + if (returnedResult == 0) { + TORCH_CUDABLAS_CHECK(CUBLAS_STATUS_NOT_SUPPORTED); + } +#endif + + cublasStatus_t cublasStatus = cublasLtMatmul( + ltHandle, + computeDesc.descriptor(), + &alpha_val, + mat1_ptr, + Adesc.descriptor(), + mat2_ptr, + Bdesc.descriptor(), + &beta_val, + result_ptr, + Cdesc.descriptor(), + result_ptr, + Cdesc.descriptor(), +#ifdef USE_ROCM + &heuristicResult.algo, +#else + nullptr, // Heuristics don't seem to work for int8 +#endif +#ifdef USE_ROCM + ltworkspace.ptr, +#else + nullptr, // Non-zero workspace doesn't seem to work. +#endif +#ifdef USE_ROCM + ltworkspace.size, +#else + 0, +#endif + stream); + TORCH_CHECK( + cublasStatus == CUBLAS_STATUS_SUCCESS, + "CUDA error: ", + at::cuda::blas::_cublasGetErrorEnum(cublasStatus), + " when calling cublasLtMatmul with transpose_mat1 ", + transpose_mat1, + " transpose_mat2 ", + transpose_mat2, + " m ", + m, + " n ", + n, + " k ", + k, + " mat1_ld ", + mat1_ld, + " mat2_ld ", + mat2_ld, + " result_ld ", + result_ld, + " abType ", + abType, + " cType ", + cType, + " computeType ", + computeType, + " scaleType ", + scaleType); +#ifdef USE_ROCM + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + _syncCurrentWithCarveoutStream(stream, false); + } +#endif +} + +template <> +void trsm(CUDABLAS_TRSM_ARGTYPES(float)) { + TORCH_CUDABLAS_CHECK(cublasStrsm( + handle, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb)); +} + +template <> +void trsm(CUDABLAS_TRSM_ARGTYPES(double)) { + TORCH_CUDABLAS_CHECK(cublasDtrsm( + handle, side, uplo, trans, diag, m, n, alpha, A, lda, B, ldb)); +} + +template <> +void trsm>(CUDABLAS_TRSM_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCtrsm( + handle, + side, + uplo, + trans, + diag, + m, + n, + reinterpret_cast(alpha), + reinterpret_cast(A), + lda, + reinterpret_cast(B), + ldb)); +} + +template <> +void trsm>(CUDABLAS_TRSM_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZtrsm( + handle, + side, + uplo, + trans, + diag, + m, + n, + reinterpret_cast(alpha), + reinterpret_cast(A), + lda, + reinterpret_cast(B), + ldb)); +} + +template <> +// NOLINTNEXTLINE(*array*) +void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(float)) { + TORCH_CUDABLAS_CHECK(cublasStrsmBatched( + handle, + side, + uplo, + trans, + diag, + m, + n, + alpha, + A, + lda, + B, + ldb, + batchCount)); +} + +template <> +// NOLINTNEXTLINE(*array*) +void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(double)) { + TORCH_CUDABLAS_CHECK(cublasDtrsmBatched( + handle, + side, + uplo, + trans, + diag, + m, + n, + alpha, + A, + lda, + B, + ldb, + batchCount)); +} + +template <> +void trsmBatched>( +// NOLINTNEXTLINE(*array*) + CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCtrsmBatched( + handle, + side, + uplo, + trans, + diag, + m, + n, + reinterpret_cast(alpha), + reinterpret_cast(A), + lda, + reinterpret_cast(B), + ldb, + batchCount)); +} + +template <> +void trsmBatched>( +// NOLINTNEXTLINE(*array*) + CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZtrsmBatched( + handle, + side, + uplo, + trans, + diag, + m, + n, + reinterpret_cast(alpha), + reinterpret_cast(A), + lda, + reinterpret_cast(B), + ldb, + batchCount)); +} + +/* LEVEL 2 BLAS FUNCTIONS */ + +#define GEMV_CHECK_ARGVALUES(Dtype) \ + do { \ + CUDABLAS_NONNEGINT_CHECK(gemv, m); \ + CUDABLAS_NONNEGINT_CHECK(gemv, n); \ + CUDABLAS_POSINT_CHECK(gemv, lda); \ + CUDABLAS_POSINT_CHECK(gemv, incx); \ + CUDABLAS_POSINT_CHECK(gemv, incy); \ + } while (0) + +template <> +void gemv>(CUDABLAS_GEMV_ARGTYPES(c10::complex)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + cublasOperation_t op = detail::cublasOpFromChar(trans); + _cublasAdjustLdLevel2(m, n, &lda); + GEMV_CHECK_ARGVALUES(c10::complex); + TORCH_CUDABLAS_CHECK( + cublasZgemv(handle, op, m, n, reinterpret_cast(&alpha), reinterpret_cast(a), + lda, reinterpret_cast(x), incx, reinterpret_cast(&beta), + reinterpret_cast(y), incy)); +} + +template <> +void gemv>(CUDABLAS_GEMV_ARGTYPES(c10::complex)) { + // gemv is bw bound, and does not benefit from TF32. But the precision + // loss still happens on TF32. So we disable it here. + NoTF32Guard disable_tf32; + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + cublasOperation_t op = detail::cublasOpFromChar(trans); + _cublasAdjustLdLevel2(m, n, &lda); + GEMV_CHECK_ARGVALUES(c10::complex); + TORCH_CUDABLAS_CHECK( + cublasCgemv(handle, op, m, n, reinterpret_cast(&alpha), reinterpret_cast(a), + lda, reinterpret_cast(x), incx, reinterpret_cast(&beta), + reinterpret_cast(y), incy)); +} + +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(double)) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + cublasOperation_t op = detail::cublasOpFromChar(trans); + _cublasAdjustLdLevel2(m, n, &lda); + GEMV_CHECK_ARGVALUES(double); + TORCH_CUDABLAS_CHECK( + cublasDgemv(handle, op, m, n, &alpha, a, lda, x, incx, &beta, y, incy)); +} + +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(float)) { + // gemv is bw bound, and does not benefit from TF32. But the precision + // loss still happens on TF32. So we disable it here. + NoTF32Guard disable_tf32; + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); + cublasOperation_t op = detail::cublasOpFromChar(trans); + _cublasAdjustLdLevel2(m, n, &lda); + GEMV_CHECK_ARGVALUES(float); + TORCH_CUDABLAS_CHECK( + cublasSgemv(handle, op, m, n, &alpha, a, lda, x, incx, &beta, y, incy)); +} + +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(at::Half)) { + // In general, cublas regards matrices as column-major. + // The cublasS/Dgemv usages in cuda::blas::gemv/ above + // require that external blas::gemv callers obey the following convention: + // + // If "a" is row-major with shape (output, summed) in blas::gemv's caller, + // caller interprets it as column-major with shape (summed, output), passes + // summed and output respectively to our local vars m, n, and requests that cublas + // internally transpose ("trans") the column-major interpretation of a. + // + // There's no such thing as "cublasHalfgemv", so here we hack gemv with a gemm. + // However, we must allow the same calling convention, because the caller shouldn't + // have to swap args based on whether it's calling blas::gemv or . + + bool trans_bool = (detail::cublasOpFromChar(trans) != CUBLAS_OP_N); + if (trans_bool) { + std::swap(m, n); + } + // After swap, local vars m, n contain the output and summed sizes respectively, + // regardless of whether "a" was row-major or column-major in gemv<>'s caller. + + // To handle the possibility incy > 1, interprets vector y as column-major matrix with one row + // (shape (1, output)) and leading dim incy. + // trans(a)*x would compute a matrix with one column (shape (output, 1)) which wouldn't match y. + // So instead, we interpret x similarly to y, as a column-major matrix with one row + // (shape (1, summed)) and leading dim incx. The gemm then carries out x*transpose(trans(a)) to + // produce a matrix with one row (shape (1, output)), matching y. + char trans_flipped = (trans_bool ? 'n' : 't'); + gemm( + 'n', trans_flipped, 1, m, n, alpha, x, incx, a, lda, beta, y, incy); +} + +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(at::BFloat16)) { + bool trans_bool = (detail::cublasOpFromChar(trans) != CUBLAS_OP_N); + if (trans_bool) { + std::swap(m, n); + } + char trans_flipped = (trans_bool ? 'n' : 't'); + gemm( + 'n', trans_flipped, 1, m, n, alpha, x, incx, a, lda, beta, y, incy); +} + +/* LEVEL 1 BLAS FUNCTIONS */ + +template <> +void dot(CUDABLAS_DOT_ARGTYPES(double)) { + TORCH_CUDABLAS_CHECK(cublasDdot(handle, n, x, incx, y, incy, result)); +} + +template <> +void dot(CUDABLAS_DOT_ARGTYPES(float)) { + TORCH_CUDABLAS_CHECK(cublasSdot(handle, n, x, incx, y, incy, result)); +} + +template <> +void dot>(CUDABLAS_DOT_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZdotu(handle, n, reinterpret_cast(x), + incx, reinterpret_cast(y), incy, + reinterpret_cast(result))); +} + +template <> +void dot>(CUDABLAS_DOT_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCdotu(handle, n, reinterpret_cast(x), + incx, reinterpret_cast(y), incy, + reinterpret_cast(result))); +} + +template <> +void dot(CUDABLAS_DOT_ARGTYPES(at::Half)) { + TORCH_CUDABLAS_CHECK(cublasDotEx( + handle, + n, + x, + CUDA_R_16F, + incx, + y, + CUDA_R_16F, + incy, + result, + CUDA_R_16F, + CUDA_R_32F)); +} + +template <> +void dot(CUDABLAS_DOT_ARGTYPES(at::BFloat16)) { + TORCH_CUDABLAS_CHECK(cublasDotEx( + handle, + n, + x, + CUDA_R_16BF, + incx, + y, + CUDA_R_16BF, + incy, + result, + CUDA_R_16BF, + CUDA_R_32F)); +} + +template <> +void vdot>(CUDABLAS_DOT_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCdotc(handle, n, reinterpret_cast(x), + incx, reinterpret_cast(y), incy, + reinterpret_cast(result))); +} + +template <> +void vdot>(CUDABLAS_DOT_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZdotc(handle, n, reinterpret_cast(x), + incx, reinterpret_cast(y), incy, + reinterpret_cast(result))); +} + +template <> +void getrsBatched(CUDABLAS_GETRS_ARGTYPES(float)) { + TORCH_CUDABLAS_CHECK(cublasSgetrsBatched( + handle, + trans, + n, + nrhs, + dA_array, + lda, + ipiv_array, + dB_array, + ldb, + info_array, + batchsize)); +} + +template <> +void getrsBatched(CUDABLAS_GETRS_ARGTYPES(double)) { + TORCH_CUDABLAS_CHECK(cublasDgetrsBatched( + handle, + trans, + n, + nrhs, + dA_array, + lda, + ipiv_array, + dB_array, + ldb, + info_array, + batchsize)); +} + +template <> +void getrsBatched>(CUDABLAS_GETRS_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCgetrsBatched( + handle, + trans, + n, + nrhs, + reinterpret_cast(dA_array), + lda, + ipiv_array, + reinterpret_cast(dB_array), + ldb, + info_array, + batchsize)); +} + +template <> +void getrsBatched>(CUDABLAS_GETRS_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZgetrsBatched( + handle, + trans, + n, + nrhs, + reinterpret_cast(dA_array), + lda, + ipiv_array, + reinterpret_cast(dB_array), + ldb, + info_array, + batchsize)); +} + +template <> +void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(float)) { + TORCH_CUDABLAS_CHECK(cublasSgeqrfBatched( + handle, m, n, A_array, lda, tau_array, info, batchsize)); +} + +template <> +void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(double)) { + TORCH_CUDABLAS_CHECK(cublasDgeqrfBatched( + handle, m, n, A_array, lda, tau_array, info, batchsize)); +} + +template <> +void geqrfBatched>( + CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCgeqrfBatched( + handle, + m, + n, + reinterpret_cast(A_array), + lda, + reinterpret_cast(tau_array), + info, + batchsize)); +} + +template <> +void geqrfBatched>( + CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZgeqrfBatched( + handle, + m, + n, + reinterpret_cast(A_array), + lda, + reinterpret_cast(tau_array), + info, + batchsize)); +} + +template <> +void getrfBatched( + int n, double** dA_array, int ldda, int* ipiv_array, int* info_array, int batchsize) { + auto handle = at::cuda::getCurrentCUDABlasHandle(); + TORCH_CUDABLAS_CHECK(cublasDgetrfBatched( + handle, n, dA_array, ldda, ipiv_array, info_array, batchsize)); +} + +template <> +void getrfBatched( + int n, float** dA_array, int ldda, int* ipiv_array, int* info_array, int batchsize) { + auto handle = at::cuda::getCurrentCUDABlasHandle(); + TORCH_CUDABLAS_CHECK(cublasSgetrfBatched( + handle, n, dA_array, ldda, ipiv_array, info_array, batchsize)); +} + +template <> +void getrfBatched>( + int n, + c10::complex** dA_array, + int ldda, + int* ipiv_array, + int* info_array, + int batchsize) { + auto handle = at::cuda::getCurrentCUDABlasHandle(); + TORCH_CUDABLAS_CHECK(cublasZgetrfBatched( + handle, + n, + reinterpret_cast(dA_array), + ldda, + ipiv_array, + info_array, + batchsize)); +} + +template <> +void getrfBatched>( + int n, + c10::complex** dA_array, + int ldda, + int* ipiv_array, + int* info_array, + int batchsize) { + auto handle = at::cuda::getCurrentCUDABlasHandle(); + TORCH_CUDABLAS_CHECK(cublasCgetrfBatched( + handle, + n, + reinterpret_cast(dA_array), + ldda, + ipiv_array, + info_array, + batchsize)); +} + + +template <> +void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(double)) { + TORCH_CUDABLAS_CHECK(cublasDgelsBatched( + handle, trans, m, n, nrhs, dA_array, ldda, dC_array, lddc, info, devInfoArray, batchSize)); +} + +template <> +void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(float)) { + TORCH_CUDABLAS_CHECK(cublasSgelsBatched( + handle, trans, m, n, nrhs, dA_array, ldda, dC_array, lddc, info, devInfoArray, batchSize)); +} + +template <> +void gelsBatched>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasZgelsBatched( + handle, trans, + m, n, nrhs, + reinterpret_cast(dA_array), + ldda, + reinterpret_cast(dC_array), + lddc, + info, + devInfoArray, + batchSize)); +} + +template <> +void gelsBatched>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex)) { + TORCH_CUDABLAS_CHECK(cublasCgelsBatched( + handle, trans, + m, n, nrhs, + reinterpret_cast(dA_array), + ldda, + reinterpret_cast(dC_array), + lddc, + info, + devInfoArray, + batchSize)); +} + +} // namespace at::cuda::blas diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDABlas.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDABlas.h new file mode 100644 index 0000000000000000000000000000000000000000..58b23b92f940536fe11fa37df00391e8438eb0df --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDABlas.h @@ -0,0 +1,393 @@ +#pragma once +/* + Provides a subset of CUDA BLAS functions as templates: + + gemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, + ldc) + + gemv(transa, m, n, alpha, a, lda, x, incx, beta, y, incy) + + dot(n, x, incx, y, incy, result) + + where Dtype is double, float, at::Half or at::BFloat16 (ROCm, NOT for dot). + The functions are available in at::cuda::blas namespace. + */ + +#include +#include +#include + +namespace at::cuda::blas { + +// RAII guard that sets the CuBLAS pointer mode and restores it to +// its previous value when the guard is destroyed +class PointerModeGuard { +public: + PointerModeGuard(cublasHandle_t handle, cublasPointerMode_t mode) : + handle(handle) { + TORCH_CUDABLAS_CHECK(cublasGetPointerMode(handle, &previous_mode)); + TORCH_CUDABLAS_CHECK(cublasSetPointerMode(handle, mode)); + } + + ~PointerModeGuard() { + cublasSetPointerMode(handle, previous_mode); + } + +private: + cublasHandle_t handle; + cublasPointerMode_t previous_mode{}; +}; + +/* LEVEL 3 BLAS FUNCTIONS */ + +#define CUDABLAS_GEMM_ARGTYPES(Dtype) CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, Dtype) + +#define CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype) \ + char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type alpha, \ + const Dtype *a, int64_t lda, const Dtype *b, int64_t ldb, at::opmath_type beta,\ + C_Dtype *c, int64_t ldc + +#define CUDABLAS_GEMM_ARGS(Dtype) transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc + +#define CUDABLAS_GEMM_DTYPE_IS_FLOAT_TYPE_AND_C_DTYPE_IS_FLOAT \ + ((std::is_same::value || std::is_same::value) && std::is_same::value) + +template ::type* = nullptr> +inline void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::gemm: not implemented"); +} + +template ::type* = nullptr> +void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)); + +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(double)); +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(float)); +template <> +void gemm>(CUDABLAS_GEMM_ARGTYPES(c10::complex)); +template <> +void gemm>(CUDABLAS_GEMM_ARGTYPES(c10::complex)); +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(at::Half)); +template <> +void gemm(CUDABLAS_GEMM_ARGTYPES(at::BFloat16)); +template<> +void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)); +template<> +void gemm(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)); + +template +inline void gemm_internal(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::gemm_internal: not implemented"); +} + +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(double)); +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(float)); +template <> +void gemm_internal>(CUDABLAS_GEMM_ARGTYPES(c10::complex)); +template <> +void gemm_internal>(CUDABLAS_GEMM_ARGTYPES(c10::complex)); +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(at::Half)); +template <> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES(at::BFloat16)); +template<> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)); +template<> +void gemm_internal(CUDABLAS_GEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)); + +enum GEMMAndBiasActivationEpilogue { + None, + RELU, + GELU, +}; + +// NOTE: GELU activation is not supported prior to CUDA 11.4 and will +// do nothing if passed in that case. +template +bool gemm_and_bias( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha_val, + const Dtype* mat1_ptr, + int64_t mat1_ld, + const Dtype* mat2_ptr, + int64_t mat2_ld, + const Dtype* bias, + C_Dtype* result_ptr, + int64_t result_ld, + GEMMAndBiasActivationEpilogue activation = GEMMAndBiasActivationEpilogue::None); + +void int8_gemm( + bool transpose_mat1, + bool transpose_mat2, + int64_t m, + int64_t n, + int64_t k, + const int8_t* mat1_ptr, + int64_t mat1_ld, + const int8_t* mat2_ptr, + int64_t mat2_ld, + int32_t* result_ptr, + int64_t result_ld); + +void scaled_gemm( + char transa, + char transb, + int64_t m, + int64_t n, + int64_t k, + const void* mat1_ptr, + const void* mat1_scale_ptr, + int64_t mat1_ld, + ScalarType mat1_dtype, + ScalarType mat1_scale_dtype, + at::blas::ScalingType mat1_scaling_type, + const void* mat2_ptr, + const void* mat2_scale_ptr, + int64_t mat2_ld, + ScalarType mat2_dtype, + ScalarType mat2_scale_dtype, + at::blas::ScalingType mat2_scaling_type, + const void* bias_ptr, + ScalarType bias_dtype, + void* result_ptr, + const void* result_scale_ptr, + int64_t result_ld, + ScalarType result_dtype, + bool use_fast_accum, + const std::optional& alpha); + +#define CUDABLAS_BGEMM_ARGTYPES(Dtype) CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, Dtype) + +#define CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype) \ + char transa, char transb, int64_t m, int64_t n, int64_t k, at::opmath_type alpha, \ + const Dtype *a, int64_t lda, int64_t stridea, \ + const Dtype *b, int64_t ldb, int64_t strideb, \ + at::opmath_type beta, C_Dtype *c, int64_t ldc, int64_t stridec, int64_t num_batches + +#define CUDABLAS_BGEMM_ARGS(Dtype) \ + transa, transb, m, n, k, alpha, a, lda, stridea, b, ldb, strideb, beta, c, ldc, stridec, num_batches + +template ::type* = nullptr> +inline void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::bgemm: not implemented"); +} + +template ::type* = nullptr> +void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)); + +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(double)); +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(float)); +template <> +void bgemm>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)); +template <> +void bgemm>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)); +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(at::Half)); +template <> +void bgemm(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16)); +template<> +void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)); +template<> +void bgemm(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)); + +template +inline void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(Dtype, C_Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::bgemm_internal: not implemented"); +} + +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(double)); +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(float)); +template <> +void bgemm_internal>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)); +template <> +void bgemm_internal>(CUDABLAS_BGEMM_ARGTYPES(c10::complex)); +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(at::Half)); +template <> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES(at::BFloat16)); +template<> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::Half, float)); +template<> +void bgemm_internal(CUDABLAS_BGEMM_ARGTYPES_AND_C_DTYPE(at::BFloat16, float)); + +#define CUDABLAS_TRSM_ARGTYPES(Dtype) \ + cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \ + cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \ + const Dtype *alpha, const Dtype *A, int lda, Dtype *B, int ldb + +template +inline void trsm(CUDABLAS_TRSM_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype), "at::cuda::blas::trsm: not implemented"); +} + +template <> +TORCH_CUDA_CU_API void trsm(CUDABLAS_TRSM_ARGTYPES(float)); +template <> +TORCH_CUDA_CU_API void trsm(CUDABLAS_TRSM_ARGTYPES(double)); +template <> +TORCH_CUDA_CU_API void trsm>(CUDABLAS_TRSM_ARGTYPES(c10::complex)); +template <> +TORCH_CUDA_CU_API void trsm>(CUDABLAS_TRSM_ARGTYPES(c10::complex)); + +#define CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype) \ + cublasHandle_t handle, cublasSideMode_t side, cublasFillMode_t uplo, \ + cublasOperation_t trans, cublasDiagType_t diag, int m, int n, \ + const Dtype *alpha, Dtype *A[], int lda, Dtype *B[], int ldb, \ + int batchCount + +template +inline void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype), "at::cuda::blas::trsmBatched: not implemented"); +} + +template <> +TORCH_CUDA_CU_API void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(float)); +template <> +TORCH_CUDA_CU_API void trsmBatched(CUDABLAS_TRSM_BATCHED_ARGTYPES(double)); +template <> +TORCH_CUDA_CU_API void trsmBatched>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex)); +template <> +TORCH_CUDA_CU_API void trsmBatched>(CUDABLAS_TRSM_BATCHED_ARGTYPES(c10::complex)); + +/* LEVEL 2 BLAS FUNCTIONS */ + +#define CUDABLAS_GEMV_ARGTYPES(Dtype) \ + char trans, int64_t m, int64_t n, Dtype alpha, const Dtype *a, int64_t lda, \ + const Dtype *x, int64_t incx, Dtype beta, Dtype *y, int64_t incy + +template +inline void gemv(CUDABLAS_GEMV_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype), "at::cuda::blas::gemv: not implemented"); +} + +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(double)); +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(float)); +template <> +void gemv>(CUDABLAS_GEMV_ARGTYPES(c10::complex)); +template <> +void gemv>(CUDABLAS_GEMV_ARGTYPES(c10::complex)); +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(at::Half)); +template <> +void gemv(CUDABLAS_GEMV_ARGTYPES(at::BFloat16)); + +/* LEVEL 1 BLAS FUNCTIONS */ + +#define CUDABLAS_DOT_ARGTYPES(Dtype) \ + cublasHandle_t handle, int n, const Dtype *x, int incx, const Dtype *y, \ + int incy, Dtype *result + +template +inline void dot(CUDABLAS_DOT_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::dot: not implemented"); +} + +template <> +void dot(CUDABLAS_DOT_ARGTYPES(double)); +template <> +void dot(CUDABLAS_DOT_ARGTYPES(float)); +template <> +void dot(CUDABLAS_DOT_ARGTYPES(at::Half)); +template <> +void dot(CUDABLAS_DOT_ARGTYPES(at::BFloat16)); +template <> +void dot>(CUDABLAS_DOT_ARGTYPES(c10::complex)); +template <> +void dot>(CUDABLAS_DOT_ARGTYPES(c10::complex)); + +template +inline void vdot(CUDABLAS_DOT_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::vdot: not implemented"); +} + +template <> +void vdot>(CUDABLAS_DOT_ARGTYPES(c10::complex)); +template <> +void vdot>(CUDABLAS_DOT_ARGTYPES(c10::complex)); + +#define CUDABLAS_GETRS_ARGTYPES(Dtype) \ + cublasHandle_t handle, cublasOperation_t trans, \ + int n, int nrhs, Dtype** dA_array, int lda, int* ipiv_array, \ + Dtype** dB_array, int ldb, int* info_array, int batchsize + +#define CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype) \ + cublasHandle_t handle, int m, int n, Dtype **A_array, int lda, \ + Dtype **tau_array, int *info, int batchsize + +#define CUDABLAS_GETRF_ARGTYPES(Dtype) \ + int n, Dtype** dA_array, int ldda, int* ipiv_array, int* info_array, int batchsize + +#define CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype) \ + cublasHandle_t handle, cublasOperation_t trans, \ + int m, int n, int nrhs, Dtype** dA_array, int ldda, \ + Dtype** dC_array, int lddc, int* info, int *devInfoArray, int batchSize + +template +void getrsBatched(CUDABLAS_GETRS_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype),"at::cuda::blas::getrsBatched: not implemented"); +} +template<> +TORCH_CUDA_CU_API void getrsBatched(CUDABLAS_GETRS_ARGTYPES(float)); +template<> +TORCH_CUDA_CU_API void getrsBatched(CUDABLAS_GETRS_ARGTYPES(double)); +template<> +TORCH_CUDA_CU_API void getrsBatched>(CUDABLAS_GETRS_ARGTYPES(c10::complex)); +template<> +TORCH_CUDA_CU_API void getrsBatched>(CUDABLAS_GETRS_ARGTYPES(c10::complex)); + +template +void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype), "at::cuda::blas::geqrfBatched: not implemented"); +} +template <> +TORCH_CUDA_CU_API void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(float)); +template <> +TORCH_CUDA_CU_API void geqrfBatched(CUDABLAS_GEQRF_BATCHED_ARGTYPES(double)); +template <> +TORCH_CUDA_CU_API void geqrfBatched>( + CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex)); +template <> +TORCH_CUDA_CU_API void geqrfBatched>( + CUDABLAS_GEQRF_BATCHED_ARGTYPES(c10::complex)); + +template +void getrfBatched(CUDABLAS_GETRF_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype), "at::cuda::blas::getrfBatched: not implemented"); +} +template<> +TORCH_CUDA_CU_API void getrfBatched(CUDABLAS_GETRF_ARGTYPES(float)); +template<> +TORCH_CUDA_CU_API void getrfBatched(CUDABLAS_GETRF_ARGTYPES(double)); +template<> +TORCH_CUDA_CU_API void getrfBatched>(CUDABLAS_GETRF_ARGTYPES(c10::complex)); +template<> +TORCH_CUDA_CU_API void getrfBatched>(CUDABLAS_GETRF_ARGTYPES(c10::complex)); + +template +void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(Dtype)) { + static_assert(false&&sizeof(Dtype), "at::cuda::blas::gelsBatched: not implemented"); +} +template<> +TORCH_CUDA_CU_API void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(double)); +template<> +TORCH_CUDA_CU_API void gelsBatched(CUDABLAS_GELS_BATCHED_ARGTYPES(float)); +template<> +TORCH_CUDA_CU_API void gelsBatched>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex)); +template<> +TORCH_CUDA_CU_API void gelsBatched>(CUDABLAS_GELS_BATCHED_ARGTYPES(c10::complex)); + +} // namespace at::cuda::blas diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAConfig.h.in b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAConfig.h.in new file mode 100644 index 0000000000000000000000000000000000000000..8d530b436894f45ed9b06193dffe2300b33a6ae7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAConfig.h.in @@ -0,0 +1,20 @@ +#pragma once + +// Test these using #if AT_CUDNN_ENABLED(), not #ifdef, so that it's +// obvious if you forgot to include Config.h +// c.f. https://stackoverflow.com/questions/33759787/generating-an-error-if-checked-boolean-macro-is-not-defined +// +// NB: This header MUST NOT be included from other headers; it should +// only be included from C++ files. +#define AT_CUDNN_ENABLED() @AT_CUDNN_ENABLED@ +#define AT_CUSPARSELT_ENABLED() @AT_CUSPARSELT_ENABLED@ +#define AT_HIPSPARSELT_ENABLED() @AT_HIPSPARSELT_ENABLED@ +#define AT_ROCM_ENABLED() @AT_ROCM_ENABLED@ +#define AT_MAGMA_ENABLED() @AT_MAGMA_ENABLED@ + +// Needed for hipMAGMA to correctly identify implementation +#if (AT_ROCM_ENABLED() && AT_MAGMA_ENABLED()) +#define HAVE_HIP 1 +#endif + +#define NVCC_FLAGS_EXTRA "@NVCC_FLAGS_EXTRA@" diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContext.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2975f2591d6c94059ed49c1efb205b8b67f67c6b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContext.cpp @@ -0,0 +1,88 @@ +#include +#include +#include + +#include +#include + +namespace at::cuda { + +namespace { + +DeviceIndex num_gpus = -1; +std::deque device_flags; +std::vector device_properties; + +void initCUDAContextVectors() { + static bool init_flag [[maybe_unused]] = []() { + num_gpus = c10::cuda::device_count(); + device_flags.resize(num_gpus); + device_properties.resize(num_gpus); + return true; + }(); +} + +void initDeviceProperty(DeviceIndex device_index) { + cudaDeviceProp device_prop{}; + AT_CUDA_CHECK(cudaGetDeviceProperties(&device_prop, device_index)); + device_properties[device_index] = device_prop; +} + +} // anonymous namespace + +// We need this function to force the linking against torch_cuda(_cpp) on Windows. +// If you need to modify this function, please specify a new function and apply +// the changes according to https://github.com/pytorch/pytorch/pull/34288. +// Related issue: https://github.com/pytorch/pytorch/issues/31611. +/* Device info */ +int warp_size() { + return getCurrentDeviceProperties()->warpSize; +} + +cudaDeviceProp* getCurrentDeviceProperties() { + auto device = c10::cuda::current_device(); + return getDeviceProperties(device); +} + +cudaDeviceProp* getDeviceProperties(c10::DeviceIndex device) { + initCUDAContextVectors(); + if (device == -1) + device = c10::cuda::current_device(); + AT_ASSERT( + device >= 0 && device < num_gpus, + "device=", + static_cast(device), + ", num_gpus=", + static_cast(num_gpus)); + c10::call_once(device_flags[device], initDeviceProperty, device); + return &device_properties[device]; +} + +bool canDeviceAccessPeer( + c10::DeviceIndex device, + c10::DeviceIndex peer_device) { + initCUDAContextVectors(); + if (device == -1) + device = c10::cuda::current_device(); + AT_ASSERT( + device >= 0 && device < num_gpus, + "device=", + static_cast(device), + ", num_gpus=", + static_cast(num_gpus)); + AT_ASSERT( + peer_device >= 0 && peer_device < num_gpus, + "peer_device=", + static_cast(peer_device), + ", num_gpus=", + static_cast(num_gpus)); + int can_access = 0; + AT_CUDA_CHECK(cudaDeviceCanAccessPeer(&can_access, device, peer_device)); + return can_access != 0; +} + +Allocator* getCUDADeviceAllocator() { + return c10::cuda::CUDACachingAllocator::get(); +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContext.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContext.h new file mode 100644 index 0000000000000000000000000000000000000000..b257e3f16b4adb5efde62dff92ed6f8fb9bc1a64 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContext.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +// Preserved for BC, as many files depend on these includes +#include +#include +#include +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContextLight.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContextLight.h new file mode 100644 index 0000000000000000000000000000000000000000..7fb5cdd307bf55e38302d19957d4e6744fc1f923 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAContextLight.h @@ -0,0 +1,112 @@ +#pragma once +// Light-weight version of CUDAContext.h with fewer transitive includes + +#include +#include +#include + +#include +#include +#include + +#include + +#ifdef CUDART_VERSION +#include +#endif + +#if defined(USE_CUDSS) +#include +#endif + +#if defined(USE_ROCM) +#include +#endif + +#include +#include + +namespace c10 { +struct Allocator; +} + +namespace at::cuda { + +/* +A common CUDA interface for ATen. + +This interface is distinct from CUDAHooks, which defines an interface that links +to both CPU-only and CUDA builds. That interface is intended for runtime +dispatch and should be used from files that are included in both CPU-only and +CUDA builds. + +CUDAContext, on the other hand, should be preferred by files only included in +CUDA builds. It is intended to expose CUDA functionality in a consistent +manner. + +This means there is some overlap between the CUDAContext and CUDAHooks, but +the choice of which to use is simple: use CUDAContext when in a CUDA-only file, +use CUDAHooks otherwise. + +Note that CUDAContext simply defines an interface with no associated class. +It is expected that the modules whose functions compose this interface will +manage their own state. There is only a single CUDA context/state. +*/ + +/** + * DEPRECATED: use device_count() instead + */ +inline int64_t getNumGPUs() { + return c10::cuda::device_count(); +} + +/** + * CUDA is available if we compiled with CUDA, and there are one or more + * devices. If we compiled with CUDA but there is a driver problem, etc., + * this function will report CUDA is not available (rather than raise an error.) + */ +inline bool is_available() { + return c10::cuda::device_count() > 0; +} + +TORCH_CUDA_CPP_API cudaDeviceProp* getCurrentDeviceProperties(); + +TORCH_CUDA_CPP_API int warp_size(); + +TORCH_CUDA_CPP_API cudaDeviceProp* getDeviceProperties(c10::DeviceIndex device); + +TORCH_CUDA_CPP_API bool canDeviceAccessPeer( + c10::DeviceIndex device, + c10::DeviceIndex peer_device); + +TORCH_CUDA_CPP_API c10::Allocator* getCUDADeviceAllocator(); + +/* Handles */ +TORCH_CUDA_CPP_API cusparseHandle_t getCurrentCUDASparseHandle(); +TORCH_CUDA_CPP_API cublasHandle_t getCurrentCUDABlasHandle(bool setup = true); +TORCH_CUDA_CPP_API cublasLtHandle_t getCurrentCUDABlasLtHandle(); + +TORCH_CUDA_CPP_API void clearCublasWorkspaces(); +TORCH_CUDA_CPP_API void clearCublasWorkspacesForStream(cudaStream_t stream); +struct WorkspaceMapWithMutex { + std::map, std::pair> map; + std::shared_mutex mutex; +}; + +TORCH_CUDA_CPP_API WorkspaceMapWithMutex& cublas_handle_stream_to_workspace(); +TORCH_CUDA_CPP_API WorkspaceMapWithMutex& cublaslt_handle_stream_to_workspace(); +TORCH_CUDA_CPP_API size_t getChosenWorkspaceSize(); +TORCH_CUDA_CPP_API size_t getCUDABlasLtWorkspaceSize(); +TORCH_CUDA_CPP_API void* getCUDABlasLtWorkspace(); +TORCH_CUDA_CPP_API void setChosenWorkspaceSize(size_t size); +TORCH_CUDA_CPP_API void setCUDABlasLtWorkspaceSize(size_t size); +TORCH_CUDA_CPP_API void resetChosenWorkspaceSize(); +TORCH_CUDA_CPP_API void resetCUDABlasLtWorkspaceSize(); + +TORCH_CUDA_CPP_API cusolverDnHandle_t getCurrentCUDASolverDnHandle(); + +#if defined(USE_CUDSS) +TORCH_CUDA_CPP_API cudssHandle_t getCurrentCudssHandle(); +#endif + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDADataType.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDADataType.h new file mode 100644 index 0000000000000000000000000000000000000000..99b1741d037c44785455c2dfc9861de125254ca6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDADataType.h @@ -0,0 +1,105 @@ +#pragma once + +#include + +#include +#include + +namespace at::cuda { + +template +cudaDataType getCudaDataType() { + static_assert(false && sizeof(scalar_t), "Cannot convert type to cudaDataType."); + return {}; +} + +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_16F; +} +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_32F; +} +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_64F; +} +template<> inline cudaDataType getCudaDataType>() { + return CUDA_C_16F; +} +template<> inline cudaDataType getCudaDataType>() { + return CUDA_C_16BF; +} +template<> inline cudaDataType getCudaDataType>() { + return CUDA_C_32F; +} +template<> inline cudaDataType getCudaDataType>() { + return CUDA_C_64F; +} + +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_8U; +} +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_8I; +} +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_32I; +} + +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_16I; +} +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_64I; +} +template<> inline cudaDataType getCudaDataType() { + return CUDA_R_16BF; +} + +inline cudaDataType ScalarTypeToCudaDataType(const c10::ScalarType& scalar_type) { + switch (scalar_type) { + case c10::ScalarType::Byte: + return CUDA_R_8U; + case c10::ScalarType::Char: + return CUDA_R_8I; + case c10::ScalarType::Int: + return CUDA_R_32I; + case c10::ScalarType::Half: + return CUDA_R_16F; + case c10::ScalarType::Float: + return CUDA_R_32F; + case c10::ScalarType::Double: + return CUDA_R_64F; + case c10::ScalarType::ComplexHalf: + return CUDA_C_16F; + case c10::ScalarType::ComplexFloat: + return CUDA_C_32F; + case c10::ScalarType::ComplexDouble: + return CUDA_C_64F; + case c10::ScalarType::Short: + return CUDA_R_16I; + case c10::ScalarType::Long: + return CUDA_R_64I; + case c10::ScalarType::BFloat16: + return CUDA_R_16BF; +#if !defined(USE_ROCM) || ROCM_VERSION >= 60300 + case c10::ScalarType::Float8_e4m3fn: + return CUDA_R_8F_E4M3; + case c10::ScalarType::Float8_e5m2: + return CUDA_R_8F_E5M2; +#endif +#if defined(USE_ROCM) + case c10::ScalarType::Float8_e4m3fnuz: + return HIP_R_8F_E4M3_FNUZ; + case c10::ScalarType::Float8_e5m2fnuz: + return HIP_R_8F_E5M2_FNUZ; +#endif +#if (defined(CUDA_VERSION) && CUDA_VERSION >= 12080) || (defined(USE_ROCM) && ROCM_VERSION >= 70000) + case c10::ScalarType::Float4_e2m1fn_x2: + return CUDA_R_4F_E2M1; +#endif + default: + TORCH_INTERNAL_ASSERT(false, "Cannot convert ScalarType ", scalar_type, " to cudaDataType.") + } +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDADevice.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDADevice.h new file mode 100644 index 0000000000000000000000000000000000000000..5353a06ca6b11f607151a0b7c64762234b617c79 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDADevice.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +#include +#include + +namespace at::cuda { + +inline Device getDeviceFromPtr(void* ptr) { + cudaPointerAttributes attr{}; + + AT_CUDA_CHECK(cudaPointerGetAttributes(&attr, ptr)); + +#if !defined(USE_ROCM) + TORCH_CHECK(attr.type != cudaMemoryTypeUnregistered, + "The specified pointer resides on host memory and is not registered with any CUDA device."); +#endif + + return {c10::DeviceType::CUDA, static_cast(attr.device)}; +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAEvent.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAEvent.h new file mode 100644 index 0000000000000000000000000000000000000000..eabd42e58c4bd73bfdac2fcb2ad2147f36151807 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAEvent.h @@ -0,0 +1,7 @@ +#pragma once + +#include +#include +#include +#include +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGeneratorImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGeneratorImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93ce17d002782e8e5fc61a782718e4ef89ac742c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGeneratorImpl.cpp @@ -0,0 +1,538 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace cuda::detail { + +namespace { + +// Total number of gpus in the system. +int64_t num_gpus; + +// Ensures default_gens_cuda is initialized once. +std::deque cuda_gens_init_flag; + +// Default, global CUDA generators, one per GPU. +std::vector default_gens_cuda; + +/* + * Populates the global variables related to CUDA generators + * Warning: this function must only be called once! + */ +void initCUDAGenVector() { + // Ensures we only call cudaGetDeviceCount only once. + static bool num_gpu_init_flag [[maybe_unused]] = []() { + num_gpus = static_cast(c10::cuda::device_count()); + cuda_gens_init_flag.resize(num_gpus); + default_gens_cuda.resize(num_gpus); + return true; + }(); +} + +} // anonymous namespace + +/** + * PyTorch maintains a collection of default generators that get + * initialized once. The purpose of these default generators is to + * maintain a global running state of the pseudo random number generation, + * when a user does not explicitly mention any generator. + * getDefaultCUDAGenerator gets the default generator for a particular + * cuda device. + */ +const Generator& getDefaultCUDAGenerator(DeviceIndex device_index) { + initCUDAGenVector(); + DeviceIndex idx = device_index; + if (idx == -1) { + idx = c10::cuda::current_device(); + } else { + TORCH_CHECK(idx >= 0 && idx < num_gpus); + } + c10::call_once(cuda_gens_init_flag[idx], [&] { + default_gens_cuda[idx] = make_generator(idx); + default_gens_cuda[idx].seed(); + }); + return default_gens_cuda[idx]; +} + +/** + * Utility to create a CUDAGeneratorImpl. Returns a shared_ptr + */ +Generator createCUDAGenerator(DeviceIndex device_index) { + initCUDAGenVector(); + DeviceIndex idx = device_index; + if (idx == -1) { + idx = c10::cuda::current_device(); + } + TORCH_CHECK(idx >= 0 && idx < num_gpus, "The device_index is invalid."); + auto gen = make_generator(idx); + auto cuda_gen = check_generator(gen); + cuda_gen->set_current_seed(default_rng_seed_val); + cuda_gen->set_philox_offset_per_thread(0); + return gen; +} + +} // namespace cuda::detail + +/** + * Allocate GPU tensors for this capture state. + * + * We allocate on the default stream so that the caching allocator routes + * these tensors to the default memory pool, not the graph's capture pool. + */ +void CUDAGeneratorCaptureState::initialize(uint64_t seed) { + if (is_initialized()) { + return; + } + + auto options = at::TensorOptions().device(at::kCUDA).dtype(at::kLong); + c10::InferenceMode inference_guard(false); + + // Allocate on the default stream so that the caching allocator routes + // these tensors to the default memory pool, not the graph's capture pool. + // The relaxed capture mode guard is needed because the thread-local capture + // mode may be Global (set by cudaStreamBeginCapture), which would block + // cudaMalloc even on a non-capturing stream. + c10::cuda::CUDAStreamCaptureModeGuard capture_mode_guard( + cudaStreamCaptureModeRelaxed); + c10::cuda::CUDAStreamGuard stream_guard(c10::cuda::getDefaultCUDAStream()); + + rng_state_seed_extragraph_ = at::empty({1}, options); + rng_state_offset_extragraph_ = at::empty({1}, options); + + // Synchronize the default stream so that any prior work completes before + // a different stream writes to this memory. + c10::cuda::getDefaultCUDAStream().synchronize(); + + offset_intragraph_ = 0; +} + +void CUDAGeneratorCaptureState::increase(uint64_t increment) { + // see Note [Why enforce RNG offset % 4 == 0?] + TORCH_INTERNAL_ASSERT( + offset_intragraph_ % 4 == 0, "RNG offset must be a multiple of 4."); + TORCH_INTERNAL_ASSERT( + offset_intragraph_ <= std::numeric_limits::max() - increment, + "Increment causes overflow in the offset value."); + offset_intragraph_ += increment; +} + +uint64_t CUDAGeneratorCaptureState::finalize() { + uint64_t result = offset_intragraph_; + offset_intragraph_ = 0; + return result; +} + +/** + * Note [RNG state tensor lifetime and recordStream] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * RNG state tensors (seed and offset) are allocated on the default stream + * so they land in the default memory pool, not the graph's capture pool. + * This avoids false positives in the CUDA graph tree memory leak checker. + * + * However, during replay these tensors are filled and then read by the + * graph on the replay stream (which may differ from the default stream). + * If the graph is deleted while a replay is still in flight, the tensors + * are freed and the allocator could recycle their memory before the replay + * finishes reading them — a use-after-free. + * + * We fix this by calling recordStream on each tensor during replay. + * This tells the caching allocator that the tensor is in use on the + * replay stream. When the tensor is later freed (in CUDAGraph::reset), + * the allocator records a CUDA event on the replay stream and defers + * recycling until that event completes. + */ +void CUDAGeneratorCaptureState::setup_for_replay(uint64_t seed, uint64_t philox_offset) { + TORCH_INTERNAL_ASSERT(is_initialized(), + "Capture state not initialized"); + rng_state_seed_extragraph_.fill_(static_cast(seed)); + rng_state_offset_extragraph_.fill_(static_cast(philox_offset)); + + // See Note [RNG state tensor lifetime and recordStream] + auto stream = c10::cuda::getCurrentCUDAStream(); + c10::cuda::CUDACachingAllocator::recordStream( + rng_state_seed_extragraph_.storage().data_ptr(), stream); + c10::cuda::CUDACachingAllocator::recordStream( + rng_state_offset_extragraph_.storage().data_ptr(), stream); +} + +c10::intrusive_ptr CUDAGeneratorState::clone() { + return make_intrusive(seed_, philox_offset_per_thread_); +} + +/** + * Get or create capture state for a capture ID. + * When create_if_not_found is true and the state doesn't exist, lazily creates + * it and registers the generator with the capturing graph. + */ +CUDAGeneratorCaptureState* CUDAGeneratorState::get_capture_state(CaptureId_t capture_id, bool create_if_not_found) { + { + std::lock_guard lock(capture_states_mutex_); + auto it = capture_states_.find(capture_id); + if (it != capture_states_.end()) { + return it->second.get(); + } + if (!create_if_not_found) { + return nullptr; + } + } + + auto* graph = cuda::get_graph_from_capture_id(capture_id); + TORCH_CHECK(graph != nullptr, + "RNG op during graph capture but could not find the CUDAGraph object."); + + auto capture_state = make_intrusive(); + capture_state->initialize(seed_); + + graph->register_generator_state( + c10::intrusive_ptr::reclaim_copy(this)); + + { + std::lock_guard lock(capture_states_mutex_); + auto it = capture_states_.find(capture_id); + if (it != capture_states_.end()) { + return it->second.get(); + } + auto* ptr = capture_state.get(); + capture_states_[capture_id] = std::move(capture_state); + return ptr; + } +} + +/** + * Function to increase the internal offset based on the specified increment. + */ +void CUDAGeneratorState::increase(uint64_t increment) { + // see Note [Why enforce RNG offset % 4 == 0?] + increment = ((increment + 3) / 4) * 4; + + auto capture_id = at::cuda::currentStreamCaptureId(); + if (capture_id.has_value()) { + auto* capture_state = get_capture_state(capture_id.value(), true); + capture_state->increase(increment); + } else { + TORCH_INTERNAL_ASSERT( + philox_offset_per_thread_ % 4 == 0, + "RNG offset must be a multiple of 4."); + philox_offset_per_thread_ += increment; + } +} + +uint64_t CUDAGeneratorState::capture_epilogue(CaptureId_t capture_id) { + auto* capture_state = get_capture_state(capture_id, false); + if (capture_state) { + return capture_state->finalize(); + } + return 0; +} + +void CUDAGeneratorState::remove_capture_state(CaptureId_t capture_id) { + std::lock_guard lock(capture_states_mutex_); + capture_states_.erase(capture_id); +} + +void CUDAGeneratorState::replay_prologue(CaptureId_t capture_id, uint64_t wholegraph_increment) { + if (wholegraph_increment == 0) { + return; + } + + auto* capture_state = get_capture_state(capture_id); + TORCH_INTERNAL_ASSERT(capture_state != nullptr, + "replay_prologue called but no capture state found for this capture_id"); + capture_state->setup_for_replay(seed_, philox_offset_per_thread_); + philox_offset_per_thread_ += wholegraph_increment; +} + +/** + * Note [Why enforce RNG offset % 4 == 0?] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Curand philox does allow offsets that aren't a multiple of 4. + * But jit kernels don't use curand, they use a custom "Philox" class (see + * torch/csrc/jit/tensorexpr/cuda_random.h or + * torch/csrc/jit/codegen/cuda/runtime/random_numbers.cu). + * The "Philox" constructor computes offset/4 (a uint64_t division) to locate its + * internal start in its virtual bitstream viewed as 128-bit chunks, then, when called + * in a thread, returns one 32-bit chunk at a time from that start in the bitstream. + * In other words, if the incoming offset is not a multiple of 4, each thread + * might repeat some previously-generated 32-bit values in the bitstream. See + * https://github.com/pytorch/pytorch/pull/50169. + */ + +/** + * CUDAGeneratorImpl class implementation + */ +CUDAGeneratorImpl::CUDAGeneratorImpl(DeviceIndex device_index) + : c10::GeneratorImpl{Device(DeviceType::CUDA, device_index), + DispatchKeySet(c10::DispatchKey::CUDA)} { + at::cuda::assertNotCapturing("Cannot construct a new CUDAGeneratorImpl"); + state_ = make_intrusive(); + no_reset_rnn_state_.clear(); +} + +CUDAGeneratorImpl::CUDAGeneratorImpl( + DeviceIndex device_index, + c10::intrusive_ptr state) + : c10:: + GeneratorImpl{Device(DeviceType::CUDA, device_index), DispatchKeySet(c10::DispatchKey::CUDA)}, + state_(std::move(state)) { + no_reset_rnn_state_.clear(); +} + +/** + * Sets the seed to be used by curandStatePhilox4_32_10 + * Resets the philox_offset_per_thread_ to 0 + * + * See Note [Acquire lock when using random generators] + */ +void CUDAGeneratorImpl::set_current_seed(uint64_t seed) { + auto capture_id = at::cuda::currentStreamCaptureId(); + if (C10_LIKELY(!capture_id.has_value())) { + state_->seed_ = seed; + state_->philox_offset_per_thread_ = 0; + no_reset_rnn_state_.clear(); + } else { + TORCH_CHECK(state_->seed_ == seed, "CUDAGeneratorImpl::set_current_seed can be called during stream capture only if new seed is the same as the original seed."); + // no-op case + } +} + +/** + * Sets the offset to be used by curandStatePhilox4_32_10 + * + * See Note [Acquire lock when using random generators] + */ +void CUDAGeneratorImpl::set_offset(uint64_t offset) { + at::cuda::assertNotCapturing("Cannot call CUDAGeneratorImpl::set_offset"); + // the set function checks if the offset is a multiple of 4. + set_philox_offset_per_thread(offset); + no_reset_rnn_state_.clear(); +} + +/** + * Gets the current offset of CUDAGeneratorImpl. + */ +uint64_t CUDAGeneratorImpl::get_offset() const { + // Debatable if get_offset() should be allowed in captured regions. + // Conservatively disallow it for now. + at::cuda::assertNotCapturing("Cannot call CUDAGeneratorImpl::get_offset"); + return state_->philox_offset_per_thread_; +} + +/** + * Gets the current seed of CUDAGeneratorImpl. + */ +uint64_t CUDAGeneratorImpl::current_seed() const { + return state_->seed_; +} + +/** + * Gets a nondeterministic random number from /dev/urandom or time, + * seeds the CPUGeneratorImpl with it and then returns that number. + * + * FIXME: You can move this function to Generator.cpp if the algorithm + * in getNonDeterministicRandom is unified for both CPU and CUDA + */ +uint64_t CUDAGeneratorImpl::seed() { + at::cuda::assertNotCapturing("Cannot call CUDAGeneratorImpl::seed"); + auto random = c10::detail::getNonDeterministicRandom(true); + this->set_current_seed(random); + return random; +} + +/** + * Gets the current internal state of CUDAGeneratorImpl. The internal + * state is returned as a CPU byte tensor. + */ +c10::intrusive_ptr CUDAGeneratorImpl::get_state() const { + // The RNG state comprises the seed, and an offset used for Philox. + constexpr size_t seed_size = sizeof(uint64_t); + constexpr size_t offset_size = sizeof(int64_t); + constexpr size_t total_size = seed_size + offset_size; + + auto state_tensor = at::detail::empty_cpu({static_cast(total_size)}, ScalarType::Byte, std::nullopt, std::nullopt, std::nullopt, std::nullopt); + auto rng_state = state_tensor.data_ptr(); + auto current_seed = this->current_seed(); + auto offset = static_cast(this->philox_offset_per_thread()); // Note that old THCGeneratorState had offset as std::atomic + memcpy(rng_state, ¤t_seed, seed_size); + memcpy(rng_state + seed_size, &offset, offset_size); + + return state_tensor.getIntrusivePtr(); +} + +/** + * Sets the internal state of CUDAGeneratorImpl. The new internal state + * must be a strided CPU byte tensor and have appropriate size. See + * comments of CUDAGeneratorImpl::state for information about the layout + * and size of the internal state. + */ +void CUDAGeneratorImpl::set_state(const c10::TensorImpl& new_state) { + constexpr size_t seed_size = sizeof(uint64_t); + constexpr size_t offset_size = sizeof(int64_t); + constexpr size_t total_size = seed_size + offset_size; + + detail::check_rng_state(new_state); + + bool no_philox_seed = false; + auto new_state_size = new_state.numel(); + if (new_state_size == total_size - offset_size) { + no_philox_seed = true; + } else { + TORCH_CHECK(new_state_size == total_size, "RNG state is wrong size"); + } + + uint64_t input_seed = 0; + auto new_rng_state = new_state.data_dtype_initialized(); + memcpy(&input_seed, new_rng_state, seed_size); + this->set_current_seed(input_seed); + int64_t philox_offset = 0; + if (!no_philox_seed) { + memcpy(&philox_offset, new_rng_state + seed_size, offset_size); + } + this->set_philox_offset_per_thread(static_cast(philox_offset)); +} + +/** + * Sets the generator's current state to + * This function allows switching between different registered states of + * the generator. + */ +void CUDAGeneratorImpl::graphsafe_set_state( + const c10::intrusive_ptr& gen) { + c10::intrusive_ptr cuda_gen = + dynamic_intrusive_pointer_cast(gen); + TORCH_CHECK(cuda_gen, "Expected a CUDA Generator"); + state_ = cuda_gen->state_; +} + +/** + * Get the GeneratorImpl that point to current state_ + */ +c10::intrusive_ptr CUDAGeneratorImpl::graphsafe_get_state() + const { + auto gen = make_intrusive(device().index(), state_); + return gen; +} + +/** + * Sets the philox_offset_per_thread_ to be used by curandStatePhilox4_32_10 + * + * See Note [Acquire lock when using random generators] + */ +void CUDAGeneratorImpl::set_philox_offset_per_thread(uint64_t offset) { + // see Note [Why enforce RNG offset % 4 == 0?] + + // Note: If you use CUDNN RNN's, calling + // set_philox_offset_per_thread instead of set_offset will cause the + // cudnn RNN rng state to become stale. + TORCH_CHECK(offset % 4 == 0, "offset must be a multiple of 4"); + auto capture_id = at::cuda::currentStreamCaptureId(); + if (C10_LIKELY(!capture_id.has_value())) { + state_->philox_offset_per_thread_ = offset; + } else { + auto* capture_state = state_->get_capture_state(capture_id.value(), true); + capture_state->offset_intragraph_ = offset; + } +} + +/** + * Gets the current philox_offset_per_thread_ of CUDAGeneratorImpl. + */ +uint64_t CUDAGeneratorImpl::philox_offset_per_thread() const { + auto capture_id = at::cuda::currentStreamCaptureId(); + if (C10_LIKELY(!capture_id.has_value())) { + return state_->philox_offset_per_thread_; + } else { + auto* capture_state = state_->get_capture_state(capture_id.value(), true); + return capture_state->offset_intragraph_; + } +} + +/** + * Gets the seed and philox offset value to be used in + * curandStatePhilox4_32_10, in an opaque PhiloxCudaState that's safe + * and can be used non-divergently in callers whether CUDA graph + * capture is underway or not. See + * Note [CUDA Graph-safe RNG states] + * + * Each kernel using philox has to sensibly increment offset + * for future users of philox. So it gets the "old" value for + * itself (before add), and tells subsequent users which offset + * they should use, since only the kernel knows how many randoms + * it intends to generate. + * + * Increment should be at least the number of curand() random numbers used in + * each thread. It is the user's responsibility to make sure the increment + * for philox is never smaller than the number of curand() calls. Increment + * value > the number of curand() calls won't harm but anything less would mean + * that you would be reusing random values from previous calls. + * + * See Note [Acquire lock when using random generators] + */ +PhiloxCudaState CUDAGeneratorImpl::philox_cuda_state(uint64_t increment) { + auto capture_id = at::cuda::currentStreamCaptureId(); + if (capture_id.has_value()) { + auto* capture_state = state_->get_capture_state(capture_id.value(), true); + uint64_t offset = capture_state->offset_intragraph_; + state_->increase(increment); + + return PhiloxCudaState( + capture_state->rng_state_seed_extragraph_.data_ptr(), + capture_state->rng_state_offset_extragraph_.data_ptr(), + offset); + } else { + uint64_t offset = state_->philox_offset_per_thread_; + state_->increase(increment); + return PhiloxCudaState(state_->seed_, offset); + } +} + +/** + * Temporarily accommodates call sites that use philox_engine_inputs. + * Allows incremental refactor of call sites to use philox_cuda_state. + */ +std::pair CUDAGeneratorImpl::philox_engine_inputs( + uint64_t increment) { + at::cuda::assertNotCapturing( + "Refactor this op to use CUDAGeneratorImpl::philox_cuda_state. Cannot call CUDAGeneratorImpl::philox_engine_inputs"); + uint64_t offset = state_->philox_offset_per_thread_; + state_->increase(increment); + return std::make_pair(state_->seed_, offset); +} + +/* + * Gets the DeviceType of CUDAGeneratorImpl. + * Used for type checking during run time. + */ +DeviceType CUDAGeneratorImpl::device_type() { + return DeviceType::CUDA; +} + +/** + * Public clone method implementation + * + * See Note [Acquire lock when using random generators] + */ +std::shared_ptr CUDAGeneratorImpl::clone() const { + return std::shared_ptr(this->clone_impl()); +} + +/** + * Private clone method implementation + * + * See Note [Acquire lock when using random generators] + */ +CUDAGeneratorImpl* CUDAGeneratorImpl::clone_impl() const { + at::cuda::assertNotCapturing("Cannot call CUDAGeneratorImpl::clone_impl"); + auto gen = new CUDAGeneratorImpl(this->device().index(), state_->clone()); + return gen; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGeneratorImpl.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGeneratorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..9703c988fe6ca8da415e714bd468310b689adc1e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGeneratorImpl.h @@ -0,0 +1,200 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { + +namespace cuda { +struct CUDAGraph; +} + +using CaptureId_t = c10::CaptureId_t; + +/** + * Note [CUDA Graph-safe RNG states] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Strategy: + * ~~~~~~~~~ + * (It helps to look at + * cuda/detail/PhiloxCudaStateRaw.cuh and + * cuda/detail/UnpackRaw.cuh + * while you read this.) + * + * A CUDA graph containing multiple RNG ops behaves like a + * single giant kernel from the perspective of ops external + * to the graph. During graph capture, logic in CUDAGeneratorImpl + * records the total of all offset increments that occur in the + * graphed region, and records the final total as the offset for + * the entire graph. + * + * When the graph reruns, the logic that reruns it + * increments this device's CUDA generator's offset + * by that total. + * + * Meanwhile, within the graph, at capture time, instead of + * populating PhiloxCudaStates with the uint64_t offset pulled + * directly from the global state, PhiloxCudaState uses a pointer + * to a one-element stream-local int64_t device tensor + * holding an initial offset value, and a uint64_t holding an + * intra-graph offset. (The intra-graph offset starts from zero + * when capture begins.) In each consumer kernel, + * at::cuda::philox::unpack computes the offset to use for this kernel + * as intra-graph offset + *initial offset. + * + * When the graph reruns, the logic that reruns it first + * fill_s the initial offset tensor with this device's + * CUDA generator's current offset. + * + * The control flow above ensures graphed execution is bitwise + * identical to eager execution as long as RNG ops are enqueued + * from a single thread, even if RNG ops and graphs containing + * RNG ops are enqueued and run simultaneously on multiple streams. + * + * Usage: + * ~~~~~~ + * PhiloxCudaState in this file, and unpack() in + * cuda/CUDAGraphsUtils.cuh allow non-divergent use of + * CUDAGeneratorImpl whether graph capture is underway or not. + * + * Each PhiloxCudaState instance should be used for one and only one + * consumer kernel. + * + * Example (see e.g. native/cuda/Dropout.cu): + * + * #include + * #include + * + * __global__ void kernel(..., PhiloxCudaState philox_args) { + * auto seeds = at::cuda::philox::unpack(philox_args); + * IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; + * curandStatePhilox4_32_10_t state; + * curand_init(std::get<0>(seeds), // seed + * idx, // per-thread subsequence + * std::get<1>(seeds), // offset in subsequence + * &state); + * ... + * } + * + * host_caller(...) { + * PhiloxCudaState rng_engine_inputs; + * { + * // See Note [Acquire lock when using random generators] + * std::lock_guard lock(gen->mutex_); + * + * // gen could be HostState or DevState here! No divergent code needed! + * rng_engine_inputs = gen->philox_cuda_state(offset_increment); + * } + * kernel<<<...>>>(..., rng_engine_inputs); + * } + * + */ + +/** + * Per-capture state for a generator. + * Each (generator, capture_id) pair gets its own CUDAGeneratorCaptureState. + * This holds the GPU tensors and offset tracking for a specific graph capture. + */ +struct CUDAGeneratorCaptureState : public c10::intrusive_ptr_target { + uint64_t offset_intragraph_{0}; + at::TensorBase rng_state_seed_extragraph_; + at::TensorBase rng_state_offset_extragraph_; + + CUDAGeneratorCaptureState() = default; + + bool is_initialized() const { return rng_state_seed_extragraph_.defined(); } + void initialize(uint64_t seed); + void increase(uint64_t increment); + uint64_t finalize(); + void setup_for_replay(uint64_t seed, uint64_t philox_offset); +}; + +/** + * Generator state that supports multiple concurrent graph captures. + * Each capture gets its own CUDAGeneratorCaptureState keyed by CaptureId_t. + */ +struct CUDAGeneratorState : public c10::intrusive_ptr_target { + uint64_t seed_; + uint64_t philox_offset_per_thread_; + + // Map from capture ID to per-capture state + ska::flat_hash_map> capture_states_; + mutable std::mutex capture_states_mutex_; + + CUDAGeneratorState( + uint64_t seed = default_rng_seed_val, + uint64_t philox_offset_per_thread = 0) + : seed_(seed), + philox_offset_per_thread_(philox_offset_per_thread) {} + + void increase(uint64_t increment); + + CUDAGeneratorCaptureState* get_capture_state(CaptureId_t capture_id, bool create_if_not_found = false); + uint64_t capture_epilogue(CaptureId_t capture_id); + void replay_prologue(CaptureId_t capture_id, uint64_t wholegraph_increment); + void remove_capture_state(CaptureId_t capture_id); + + c10::intrusive_ptr clone(); +}; + +struct TORCH_CUDA_CPP_API CUDAGeneratorImpl : public c10::GeneratorImpl { + // Constructors + CUDAGeneratorImpl(DeviceIndex device_index = -1); + CUDAGeneratorImpl( + DeviceIndex device_index, + c10::intrusive_ptr state_); + ~CUDAGeneratorImpl() override = default; + + // CUDAGeneratorImpl methods + std::shared_ptr clone() const; + void set_current_seed(uint64_t seed) override; + void set_offset(uint64_t offset) override; + uint64_t get_offset() const override; + uint64_t current_seed() const override; + uint64_t seed() override; + void set_state(const c10::TensorImpl& new_state) override; + c10::intrusive_ptr get_state() const override; + void graphsafe_set_state( + const c10::intrusive_ptr& state) override; + c10::intrusive_ptr graphsafe_get_state() const override; + + void set_philox_offset_per_thread(uint64_t offset); + uint64_t philox_offset_per_thread() const; + + // Generates a PhiloxCudaState with a specified increment, and increment + // current state + PhiloxCudaState philox_cuda_state(uint64_t increment); + + bool reset_rnn_state() { + return !no_reset_rnn_state_.test_and_set(); + } + + // Temporarily accommodates call sites that use philox_engine_inputs. + // Allows incremental refactor of call sites to use philox_cuda_state. + std::pair philox_engine_inputs(uint64_t increment); + + static c10::DeviceType device_type(); + + private: + CUDAGeneratorImpl* clone_impl() const override; + + c10::intrusive_ptr state_; + std::atomic_flag no_reset_rnn_state_; +}; + +namespace cuda::detail { + +TORCH_CUDA_CPP_API const Generator& getDefaultCUDAGenerator( + DeviceIndex device_index = -1); +TORCH_CUDA_CPP_API Generator createCUDAGenerator(DeviceIndex device_index = -1); + +} // namespace cuda::detail +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c5fbf5e9bab1f394120b1c29ba156ccce7a2e41 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.cpp @@ -0,0 +1,641 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace at::cuda { + +// To support stream capture across multiple threads, we use a global +// hashmap mapping cuda stream capture IDs to CUDAGraph objects. This +// was originally a thread_local std::stack, but that was +// not acceptable since stream capture does span threads in certain +// circumstances (in particular, during autograd). +static std::mutex _currently_capturing_graphs_mutex; +static ska::flat_hash_map _currently_capturing_graphs; + + +#if defined(USE_ROCM) +// Returns true when at least one CUDAGraph capture is currently active in this +// process. Uses the same mutex-protected capture map as capture lifecycle +// bookkeeping. +bool is_graph_capture_active() { + std::unique_lock lock(_currently_capturing_graphs_mutex); + return !_currently_capturing_graphs.empty(); +} +#endif // defined(USE_ROCM) + +CUDAGraph* get_graph_from_capture_id(CaptureId_t capture_id) { + std::lock_guard lock(_currently_capturing_graphs_mutex); + auto it = _currently_capturing_graphs.find(capture_id); + if (it != _currently_capturing_graphs.end()) { + return it->second; + } + return nullptr; +} + +MempoolId_t graph_pool_handle() { + // Sets just the second value, to distinguish it from MempoolId_ts created from + // cudaStreamGetCaptureInfo id_s in capture_begin. + return at::cuda::MemPool::graph_pool_handle(); +} + +/** + * Note [CUDA Graph Wrapper Class] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Q: Why do we need graph capture and launch bindings in Pytorch? + * Why can't they live in a user extension, for example? + * + * A1: Convenience. + * A2: To ensure valid numerics on replay, some native CUDA ops (like RNG ops with + * CPU statefulness) need cooperation from the capture and replay bindings + * (see Note [CUDA Graph-safe RNG states] in CUDAGeneratorImpl.h). + * + * We can't expect users to know about this cooperation. If users write capture + * bindings naively in an extension, they likely won't interact with the native + * ops properly. Their graphs would yield invalid numerics on replay. + */ + +/** + * Note [Interaction with CUDA graph capture] in CUDACachingAllocator.cpp + * describes memory management for captures. + */ + +CUDAGraph::CUDAGraph(bool keep_graph) + // CUDAStreams may not be default-constructed. + : capture_stream_(at::cuda::getCurrentCUDAStream()), + keep_graph_(keep_graph) { +} + +void CUDAGraph::register_generator_state( + c10::intrusive_ptr state) { + captured_generator_states_[std::move(state)] = 0; +} + +bool CUDAGraph::has_retained_pool(MempoolId_t pool) const { + for (const auto& retained_pool : retained_mempool_ids_) { + if (retained_pool == pool) { + return true; + } + } + return false; +} + +void CUDAGraph::record_retained_pool(MempoolId_t pool) { + if (!has_retained_pool(pool)) { + retained_mempool_ids_.push_back(pool); + } +} + +void CUDAGraph::retain_pool(MempoolId_t pool) { + TORCH_CHECK( + capture_id_ != 0 && !capture_ended_, + "CUDAGraph::retain_pool may only be called during capture."); + TORCH_CHECK( + pool.first != 0 || pool.second != 0, + "CUDAGraph::retain_pool expected a non-default memory pool."); + if (has_retained_pool(pool)) { + return; + } + c10::cuda::CUDACachingAllocator::createOrIncrefPool(capture_dev_, pool); + record_retained_pool(pool); +} + +template <> +std::function CUDAGraph::create_allocate_filter() const { + return [this](cudaStream_t stream) { + auto capture_id_opt = c10::cuda::captureIdMayInitCtx(stream); + return capture_id_opt.has_value() && capture_id_opt.value() == capture_id_; + }; +} + +template <> +std::function CUDAGraph::create_allocate_filter() const { + return [this](c10::Stream stream) { + cudaStream_t cuda_stream = CUDAStream(CUDAStream::UNCHECKED, stream); + auto capture_id_opt = c10::cuda::captureIdMayInitCtx(cuda_stream); + return capture_id_opt.has_value() && capture_id_opt.value() == capture_id_; + }; +} + +void CUDAGraph::capture_begin(MempoolId_t pool/*={0,0}*/, cudaStreamCaptureMode capture_mode) { + TORCH_CHECK(!has_graph_exec_, + "This CUDAGraph instance already owns a captured graph. " + "To capture a new graph, create a new instance."); + + capture_mode_ = capture_mode; + + auto stream = at::cuda::getCurrentCUDAStream(); + + TORCH_CHECK(stream != at::cuda::getDefaultCUDAStream(), + "CUDA graphs must be captured on a non-default stream. " + "(However, after capture, it's ok to replay them on the " + "default stream.)"); + + capture_stream_ = stream; + capture_dev_ = c10::cuda::current_device(); + +#if defined(USE_ROCM) + // hipBLASLt handles are per-(device, stream) on ROCm and lazily created. + // Ensure the handle for the intended capture stream exists before + // capture begins, because hipblasLtCreate performs internal allocations + // that are not allowed once stream capture is active. + if (at::globalContext().blasPreferredBackend() == at::BlasBackend::Cublaslt) { + (void)at::cuda::getCurrentCUDABlasLtHandle(); + } +#endif + + if (pool.first != 0 || pool.second != 0) { + // Either value being nonzero means the user supplied a pool to share. + // But only one should be nonzero. + // If pool was created by another graph's capture_begin, first should be nonzero. + // If pool was created by graph_pool_handle, second should be nonzero. + TORCH_INTERNAL_ASSERT(!(pool.first && pool.second)); + mempool_id_ = pool; + } else { + // User did not ask us to share a mempool. Create graph pool handle using is_user_created=false. + // Sets just the first value, to distinguish it from MempoolId_ts created by graph_pool_handle(). + mempool_id_ = at::cuda::MemPool::graph_pool_handle(false); + TORCH_INTERNAL_ASSERT(mempool_id_.first > 0); + } + + // Addendum: beginAllocateStreamToPool is now called before cudaStreamBeginCapture to prevent an + // autograd thread's free() call triggering an invalid cudaEventRecord in the caching allocator + // due to the capture status being updated _after_ a capture had already started. + c10::cuda::CUDACachingAllocator::beginAllocateToPool( + capture_dev_, mempool_id_, create_allocate_filter()); + record_retained_pool(mempool_id_); + + at::getHostAllocator(at::kCUDA)->begin_allocate_to_pool(mempool_id_, create_allocate_filter()); + + // cudaStreamCaptureModeGlobal is the most conservative option to + // prevent potentially unsafe CUDA API calls during capture. See + // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html#group__CUDART__STREAM_1g9d0535d93a214cbf126835257b16ba85 + AT_CUDA_CHECK(cudaStreamBeginCapture(capture_stream_, capture_mode)); + c10::cuda::CUDACachingAllocator::markCaptureBegin(capture_dev_); + + auto capture_id_opt = c10::cuda::captureIdMayInitCtx(stream); + TORCH_INTERNAL_ASSERT(capture_id_opt.has_value(), + "Stream should be actively capturing after cudaStreamBeginCapture"); + capture_id_ = capture_id_opt.value(); + + { + std::lock_guard lock(_currently_capturing_graphs_mutex); + _currently_capturing_graphs.emplace(capture_id_, this); + } +} + +// capture_end is split so callers can run work on the captured cudaGraph_t +// (e.g. read its id, dump it, transform it) in the window between the end of +// capture and finalization, when graph_ is live for both keep_graph modes. +// capture_end_post finalizes by destroying the template for keep_graph=false; +// instantiation is driven separately (by capture_end for C++ callers, or by the +// Python wrapper) so it has a single entry point. capture_end runs the whole +// sequence for callers that don't need the window. +void CUDAGraph::capture_end_pre() { + auto stream = at::cuda::getCurrentCUDAStream(); + + TORCH_CHECK(stream.stream() == capture_stream_.stream(), + "Capture must end on the same stream it began on."); + + // Capture is over once cudaStreamEndCapture returns (success or failure). + // Clear bookkeeping before propagating the return status so watchdog-side + // checks cannot observe stale "capture active" state on error paths. + cudaError_t endCaptureErr = cudaStreamEndCapture(capture_stream_, &graph_); + c10::cuda::CUDACachingAllocator::markCaptureEnd(capture_dev_); + { + std::unique_lock lock(_currently_capturing_graphs_mutex); + TORCH_CHECK( + _currently_capturing_graphs.count(capture_id_), + "capture_end() called before capture_begin()."); + _currently_capturing_graphs.erase(capture_id_); + } + + // End pool allocation before checking the capture error. This ensures + // captures_underway is cleaned up even if cudaStreamEndCapture failed + // (e.g. due to an illegal operation during capture). These calls are + // safe regardless of whether the capture succeeded — they simply + // remove the pool routing entry added by beginAllocateToPool. + c10::cuda::CUDACachingAllocator::endAllocateToPool(capture_dev_, mempool_id_); + at::getHostAllocator(at::kCUDA)->end_allocate_to_pool(mempool_id_); + AT_CUDA_CHECK(endCaptureErr); + + TORCH_CHECK(graph_ != nullptr, "Invalid capture."); + + for (auto& [generator_state, wholegraph_increment] : + captured_generator_states_) { + wholegraph_increment = generator_state->capture_epilogue(capture_id_); + } + + size_t numCUDAGraphNodes = 0; + AT_CUDA_CHECK(cudaGraphGetNodes(graph_, nullptr, &numCUDAGraphNodes)); + if (numCUDAGraphNodes == 0) { + TORCH_WARN("The CUDA Graph is empty. This usually means that the graph was ", + "attempted to be captured on wrong device or stream."); + } + + capture_ended_ = true; + has_graph_ = true; +} + +void CUDAGraph::capture_end_post() { + // Destroy-only: when keep_graph=false the template is not retained. The graph + // must already be instantiated (capture_end and the Python wrapper instantiate + // before calling this). + if (!keep_graph_ && has_graph_) { + AT_CUDA_CHECK(cudaGraphDestroy(graph_)); + has_graph_ = false; + } +} + +void CUDAGraph::capture_end() { + capture_end_pre(); + if (!keep_graph_) { + instantiate(); + } + capture_end_post(); +} + +void CUDAGraph::instantiate() { + TORCH_CHECK(capture_ended_, "capture_end() must have been called before calling instantiate"); + + if (has_graph_exec_) { + TORCH_CHECK(keep_graph_, "instantiate() is intended to be called by the user only when keep_graph=true"); + AT_CUDA_CHECK(cudaGraphExecDestroy(graph_exec_)); + } + // In typical graph usage some tensors (e.g. the tensors used for graph IO) are not freed + // between replays. + // If Pytorch compiles and runs with a CUDA 11.4+ toolkit, there's a chance the allocator backend + // is cudaMallocAsync. + // cudaMallocAsync is generally graph-safe, but if some tensors are not freed between replays, + // the graph's internal bookkeeping requires that we instantiate with + // cudaGraphInstantiateFlagAutoFreeOnLaunch. See + // cudaGraphLaunch + // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__GRAPH.html#group__CUDART__GRAPH_1g1accfe1da0c605a577c22d9751a09597 + // cudaGraphInstantiateWithFlags + // https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__GRAPH.html#group__CUDART__GRAPH_1ga2c652a24ba93e52b99a47bec0888233 +#if !defined(USE_ROCM) + AT_CUDA_CHECK(cudaGraphInstantiateWithFlags(&graph_exec_, + graph_, + cudaGraphInstantiateFlagAutoFreeOnLaunch | cudaGraphInstantiateFlagUseNodePriority)); +#else + AT_CUDA_CHECK(cudaGraphInstantiateWithFlags(&graph_exec_, + graph_, + cudaGraphInstantiateFlagAutoFreeOnLaunch)); +#endif + has_graph_exec_ = true; +} + +void CUDAGraph::replay() { + TORCH_CHECK(capture_ended_, + "Called CUDAGraph::replay without a preceding successful capture."); + // Instantiating on demand is handled by the Python replay() wrapper (which + // can do so for keep_graph=true). At this level the exec graph must exist. + TORCH_CHECK(has_graph_exec_, + "Called CUDAGraph::replay before the graph was instantiated; " + "call instantiate() first."); + + c10::OptionalDeviceGuard device_guard{capture_stream_.device()}; + + for (auto& [generator_state, wholegraph_increment] : + captured_generator_states_) { + generator_state->replay_prologue(capture_id_, wholegraph_increment); + } + // graph_exec_ may be replayed in any stream. + AT_CUDA_CHECK(cudaGraphLaunch(graph_exec_, at::cuda::getCurrentCUDAStream())); +} + +void CUDAGraph::enable_debug_mode() { + // Debug mode just retains the template after capture so it can be inspected + // (e.g. dumped); that is exactly what keep_graph does. Unify on keep_graph_ + // rather than a second flag. dot dumping itself lives in Python now + // (torch.cuda.CUDAGraph.debug_dump via cuda.bindings). + keep_graph_ = true; +} + +cudaGraph_t CUDAGraph::raw_cuda_graph() { + TORCH_CHECK(has_graph_, + "No cudaGraph_t is available: either capture_end() has not been called, " + "or the underlying cudaGraph_t was destroyed (keep_graph=false, and " + "capture has been finalized)."); + return graph_; +} + +cudaGraphExec_t CUDAGraph::raw_cuda_graph_exec() { + TORCH_CHECK( + has_graph_exec_, + "You cannot access the raw cudaGraphExec_t instance until instantiate() has been called"); + return graph_exec_; +} + +void CUDAGraph::reset() { + // I'd prefer these checks throw exceptions, not print warnings, + // but the destructor calls reset(), and at least one CI build + // refuses to compile with a throwing destructor. + // + // Instead of calling reset() in the destructor to clean up, I could + // call reset() in the __del__ method of a thin Python wrapper, + // in which case reset would be allowed to throw exceptions. + // But Stackoverflow does not like user-defined __del__. + // __del__ prevents Graph instances from EVER being garbage collected + // if they participate in a reference cycle. + // And exceptions thrown in __del__ only print a warning anyway. + // + // Calling reset() in the C++ destructor, with warnings instead of exceptions + // if calls fail, is the compromise we chose. + // + // If capture_begin, the capture, or capture_end failed at some point, this CUDAGraph, the generator, + // and the allocator could end up in all kinds of weird states depending where failure occurred. + // If the user catches the failure exception in a script, or is running in REPL or (god forbid) + // a Jupyter notebook, I don't see an easy way for reset() to gracefully fix all such possible error states. + + // See Note [RNG state tensor lifetime and recordStream] in + // CUDAGeneratorImpl.cpp — recordStream in setup_for_replay ensures the + // allocator won't recycle these tensors until in-flight replays finish. + if (capture_id_ != 0) { + for (auto& [generator_state, wholegraph_increment] : captured_generator_states_) { + generator_state->remove_capture_state(capture_id_); + } + } + captured_generator_states_.clear(); + + if (capture_id_ != 0) { + std::lock_guard lock(_currently_capturing_graphs_mutex); + _currently_capturing_graphs.erase(capture_id_); + capture_id_ = 0; + } + + if (capture_ended_) { + // Clean up cuBLAS workspaces allocated on the capture stream, otherwise live allocations prevent + // private pool cleanup + clearCublasWorkspacesForStream(capture_stream_.stream()); + + // notifyCaptureDestroy may throw. How should we handle this? + for (const auto& pool : retained_mempool_ids_) { + c10::cuda::CUDACachingAllocator::releasePool(capture_dev_, pool); + } + retained_mempool_ids_.clear(); + at::getHostAllocator(at::kCUDA)->release_pool(mempool_id_); + capture_ended_ = false; + } + if (has_graph_) { + C10_CUDA_CHECK_WARN(cudaGraphDestroy(graph_)); + has_graph_ = false; + } + if (has_graph_exec_) { + C10_CUDA_CHECK_WARN(cudaGraphExecDestroy(graph_exec_)); + has_graph_exec_ = false; + } +#if !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + while (!conditional_node_raw_streams_.empty()) { + conditional_node_raw_streams_.pop(); + } +#endif +} + +// Returns an id another graph's capture_begin can use to share the same memory pool as this graph. +MempoolId_t CUDAGraph::pool() { + TORCH_CHECK(capture_ended_, + "Called CUDAGraph::pool() without a preceding successful capture."); + return mempool_id_; +} + +std::vector CUDAGraph::pools() { + TORCH_CHECK(capture_ended_, + "Called CUDAGraph::pools() without a preceding successful capture."); + return retained_mempool_ids_; +} + +CUDAGraph::~CUDAGraph() { + reset(); + +// There are recent HIP changes where hipGraphExecDestroy doesn't immediately free memory. +// They wait for next sync point in order to free the memory, this is to ensure that all +// hipGraphLaunch are finished before we release any memory. This feature was enabled in rocm6.2. +// We need to ensure all async operations finish before deleting the object. +#if defined(USE_ROCM) + if (capture_dev_ != UNDEFINED_DEVICE) // check if capture_dev_ contains the real device id + { + AT_CUDA_CHECK(cudaSetDevice(capture_dev_)); + AT_CUDA_CHECK(cudaDeviceSynchronize()); + } +#endif +} + +CUDAGraph* CUDAGraph::get_currently_capturing_graph() { + std::unique_lock lock(_currently_capturing_graphs_mutex); + auto capture_id_opt = c10::cuda::currentStreamCaptureIdMayInitCtx(); + TORCH_CHECK( + capture_id_opt.has_value(), + "The current stream is not currently capturing."); + TORCH_CHECK( + _currently_capturing_graphs.count(capture_id_opt.value()), + "get_currently_capturing_graph() can be used only between capture_begin() and capture_end(). Did you use a stream without making it depend upon the original stream used for capture?"); + return _currently_capturing_graphs.at(capture_id_opt.value()); +} + +void CUDAGraph::begin_capture_to_if_node( + const at::Tensor& scalar_cuda_pred_tensor) { +#if !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + TORCH_CHECK( + !has_graph_exec_, + "This CUDAGraph instance already owns a captured graph."); + + TORCH_CHECK(!c10::cuda::CUDACachingAllocator::CUDAAllocatorConfig::graph_capture_record_stream_reuse(), "'graph_capture_record_stream_reuse:True' allocator config does not work with conditional control flow in a cuda graph today. See issue #175001 for updates"); + + cudaStreamCaptureStatus status{}; + cudaGraph_t currently_capturing_graph{}; + AT_CUDA_CHECK(cudaStreamGetCaptureInfo( + getCurrentCUDAStream(), &status, nullptr, ¤tly_capturing_graph)); + TORCH_CHECK( + status == cudaStreamCaptureStatusActive, + "capture_begin() must be called before begin_capture_to_if_node()"); + cudaGraphConditionalHandle handle{}; + AT_CUDA_CHECK(cudaGraphConditionalHandleCreate( + &handle, currently_capturing_graph, 0, 0)); + + set_conditional_handle(handle, scalar_cuda_pred_tensor); + + const cudaGraphNode_t* dependencies{}; + const cudaGraphEdgeData* dependency_edges{}; + size_t num_dependencies = 0; +#if CUDA_VERSION >= 13000 + AT_CUDA_CHECK(cudaStreamGetCaptureInfo( + getCurrentCUDAStream(), + &status, + nullptr, + ¤tly_capturing_graph, + &dependencies, + &dependency_edges, + &num_dependencies)); +#else + AT_CUDA_CHECK(cudaStreamGetCaptureInfo_v3( + getCurrentCUDAStream(), + &status, + nullptr, + ¤tly_capturing_graph, + &dependencies, + &dependency_edges, + &num_dependencies + )); +#endif + TORCH_CHECK(status == cudaStreamCaptureStatusActive); + + cudaGraphNodeParams params{}; + params.type = cudaGraphNodeTypeConditional; + params.conditional.handle = handle; + params.conditional.type = cudaGraphCondTypeIf; + params.conditional.size = 1; + + cudaGraphNode_t cond_node{}; +#if CUDA_VERSION >= 13000 + AT_CUDA_CHECK(cudaGraphAddNode( + &cond_node, + currently_capturing_graph, + dependencies, + dependency_edges, + num_dependencies, + ¶ms)); +#else + AT_CUDA_CHECK(cudaGraphAddNode_v2( + &cond_node, + currently_capturing_graph, + dependencies, + dependency_edges, + num_dependencies, + ¶ms)); +#endif + cudaGraph_t if_node_child_graph = params.conditional.phGraph_out[0]; + +#if CUDA_VERSION >= 13000 + AT_CUDA_CHECK(cudaStreamUpdateCaptureDependencies( +getCurrentCUDAStream(), &cond_node, nullptr, 1, cudaStreamSetCaptureDependencies)); +#else + AT_CUDA_CHECK(cudaStreamUpdateCaptureDependencies_v2( +getCurrentCUDAStream(), &cond_node, nullptr, 1, cudaStreamSetCaptureDependencies)); +#endif + + cudaStream_t raw_child_stream{}; + AT_CUDA_CHECK(cudaStreamCreateWithFlags( + &raw_child_stream, cudaStreamNonBlocking)); + CUDAStream child_stream = + getStreamFromExternal(raw_child_stream, capture_dev_); + conditional_node_raw_streams_.emplace(raw_child_stream); + conditional_graph_capture_ids_.push(0); + + c10::cuda::CUDACachingAllocator::endAllocateToPool(capture_dev_, mempool_id_); + at::getHostAllocator(at::kCUDA)->end_allocate_to_pool(mempool_id_); + c10::cuda::CUDACachingAllocator::beginAllocateToPool( + capture_dev_, mempool_id_, create_child_allocate_filter()); + auto filter = create_child_allocate_filter(); + at::getHostAllocator(at::kCUDA)->begin_allocate_to_pool(mempool_id_, [filter](c10::Stream stream) { + return filter(CUDAStream(CUDAStream::UNCHECKED, stream)); + }); + + AT_CUDA_CHECK(cudaStreamBeginCaptureToGraph( + child_stream, if_node_child_graph, nullptr, nullptr, 0, capture_mode_)); + c10::cuda::CUDACachingAllocator::markCaptureBegin(capture_dev_); + + auto child_capture_id_opt = c10::cuda::captureIdMayInitCtx(child_stream); + TORCH_INTERNAL_ASSERT(child_capture_id_opt.has_value(), + "Child stream should be actively capturing after cudaStreamBeginCaptureToGraph"); + conditional_graph_capture_ids_.top() = child_capture_id_opt.value(); + + conditional_node_streams_.emplace(child_stream); + + { + std::unique_lock lock(_currently_capturing_graphs_mutex); + _currently_capturing_graphs.emplace( + conditional_graph_capture_ids_.top(), this); + } + +#else // !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + AT_ERROR( + __func__, + " CUDA Graphs conditional nodes are not supported for cuda version < 12.4"); + return; +#endif +} + +void CUDAGraph::end_capture_to_conditional_node() { +#if !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + TORCH_INTERNAL_ASSERT( + !conditional_graph_capture_ids_.empty(), + "Missing capture ID for conditional node."); + + CaptureId_t child_capture_id = conditional_graph_capture_ids_.top(); + bool rng_or_generators_changed = false; + for (const auto& [generator_state, wholegraph_increment] : + captured_generator_states_) { + if (generator_state->get_capture_state(child_capture_id) != nullptr) { + rng_or_generators_changed = true; + break; + } + } + + { + std::unique_lock lock(_currently_capturing_graphs_mutex); + TORCH_CHECK( + _currently_capturing_graphs.count(child_capture_id), + "capture_end() called before capture_begin()."); + _currently_capturing_graphs.erase(child_capture_id); + } + + CUDAStream stream = conditional_node_streams_.top().current_stream(); + AT_CUDA_CHECK(cudaStreamEndCapture(stream.stream(), nullptr)); + c10::cuda::CUDACachingAllocator::markCaptureEnd(capture_dev_); + conditional_node_streams_.pop(); + conditional_graph_capture_ids_.pop(); + + TORCH_INTERNAL_ASSERT(!conditional_node_raw_streams_.empty()); + conditional_node_raw_streams_.pop(); + + c10::cuda::CUDACachingAllocator::endAllocateToPool(capture_dev_, mempool_id_); + at::getHostAllocator(at::kCUDA)->end_allocate_to_pool(mempool_id_); + if (conditional_graph_capture_ids_.empty()) { + c10::cuda::CUDACachingAllocator::beginAllocateToPool( + capture_dev_, mempool_id_, create_allocate_filter()); + at::getHostAllocator(at::kCUDA)->begin_allocate_to_pool(mempool_id_, create_allocate_filter()); + } else { + c10::cuda::CUDACachingAllocator::beginAllocateToPool( + capture_dev_, mempool_id_, create_child_allocate_filter()); + auto filter = create_child_allocate_filter(); + at::getHostAllocator(at::kCUDA)->begin_allocate_to_pool(mempool_id_, [filter](c10::Stream stream) { + return filter(CUDAStream(CUDAStream::UNCHECKED, stream)); + }); + } + constexpr const char* rng_with_conditional_nodes_error = + "RNG within data-dependent conditional nodes is not supported yet."; + TORCH_CHECK(!rng_or_generators_changed, rng_with_conditional_nodes_error); + +#else // !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + AT_ERROR( + __func__, + " CUDA Graphs conditional nodes are not supported for cuda version < 12.4"); +#endif +} + +std::function CUDAGraph::create_child_allocate_filter() { +#if !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + return [¤t_capture_id = conditional_graph_capture_ids_.top()](cudaStream_t stream) { + auto capture_id_opt = c10::cuda::captureIdMayInitCtx(stream); + return capture_id_opt.has_value() && capture_id_opt.value() == current_capture_id; + }; +#else // !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + AT_ERROR( + __func__, + " CUDA Graphs conditional nodes are not supported for cuda version < 12.4"); + return std::function(); +#endif +} + + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.cu new file mode 100644 index 0000000000000000000000000000000000000000..37efcaf04b4048ed66380eeb8f2f9508a02011f2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.cu @@ -0,0 +1,30 @@ +#include +#include + +namespace at::cuda { + +namespace { + +#if !(defined(USE_ROCM)) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) +__global__ void set_conditional_handle_kernel( + cudaGraphConditionalHandle handle, + const bool* value) { + cudaGraphSetConditional(handle, *value); +} +#endif +} + +void CUDAGraph::set_conditional_handle( + cudaGraphConditionalHandle handle, + const Tensor& scalar_cuda_pred_tensor) { +#if !(defined(USE_ROCM)) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + set_conditional_handle_kernel<<<1, 1, 0, getCurrentCUDAStream()>>>( + handle, scalar_cuda_pred_tensor.const_data_ptr()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +#else + AT_ERROR("not allowed"); + return; +#endif +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.h new file mode 100644 index 0000000000000000000000000000000000000000..c421e8067604651111c8cd0d4f4e85ac0cc8b86c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraph.h @@ -0,0 +1,200 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#if defined(USE_ROCM) || !(defined(CUDA_VERSION) && CUDA_VERSION >= 12040) +// this type is not defined until CUDA 12.4, but we use it as a +// parameter type and return type in some below functions, so we give +// it the same definition as in CUDA 12.4. +typedef unsigned long long cudaGraphConditionalHandle; +#endif // defined(USE_ROCM) || !(defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + +namespace at { + +struct Generator; +struct CUDAGeneratorImpl; +struct CUDAGeneratorState; + +namespace cuda { + +// Standalone way to get a unique mempool id usable as a pool=... argument +// to CUDAGraph::capture_begin +TORCH_CUDA_CPP_API MempoolId_t graph_pool_handle(); + +// Returns true if any CUDAGraph capture is currently active in this process. +// Used by ProcessGroupNCCL's ROCm watchdog workaround to avoid calling +// hipEventQuery during active capture on HIP runtimes without the +// event-query capture-mode fix (https://github.com/ROCm/clr/pull/3176). +// Not needed on CUDA/NVIDIA where cross-thread event query does not have this +// restriction. +#if defined(USE_ROCM) +TORCH_CUDA_CPP_API bool is_graph_capture_active(); +#endif // defined(USE_ROCM) + +struct CUDAGraph; + +TORCH_CUDA_CPP_API CUDAGraph* get_graph_from_capture_id(CaptureId_t capture_id); + +struct TORCH_CUDA_CPP_API CUDAGraph { + CUDAGraph(bool keep_graph=false); + ~CUDAGraph(); + + // Copy and move constructors and assignments are disabled. These + // were disabled because pybind11 believed that CUDAGraph was copy + // constructable because + // pybind11::is_copy_constructible::value originally + // evaluated to true. However, it cannot generate a copy constructor + // because CUDAGeneratorState, one of CUDAGraph's members, is an + // incomplete type unless CUDAGeneratorImpl.h is included. However, + // that would create a circular dependency between + // CUDAGeneratorImpl.h and CUDAGraph.h. Disabling the copy and move + // constructors is the most straightforward way to prevent pybind11 + // from trying to generate default implementations of them. + // + // We needed pybind11 to return a reference to a CUDAGraph as part + // of wrapping CUDAGraph::get_currently_capturing_graph, which + // unearthed the above problem. + CUDAGraph(const CUDAGraph&) = delete; + CUDAGraph& operator=(const CUDAGraph&) = delete; + CUDAGraph(CUDAGraph&& other) = delete; + CUDAGraph& operator=(CUDAGraph&& other) = delete; + + void register_generator_state(c10::intrusive_ptr state); + void capture_begin( + MempoolId_t pool = {0, 0}, + cudaStreamCaptureMode capture_mode = cudaStreamCaptureModeGlobal); + void capture_end(); + // Split capture_end: capture_end_pre ends capture leaving graph_ live (both + // keep_graph modes); capture_end_post finalizes (instantiate + destroy for + // keep_graph=false). capture_end() == pre() + post(). The split lets callers + // operate on the captured cudaGraph_t before finalization. + void capture_end_pre(); + void capture_end_post(); + void instantiate(); + // True once the cudaGraphExec_t has been instantiated (by capture_end when + // keep_graph=false, or by an explicit instantiate()). The Python replay() + // wrapper uses this to instantiate on demand for keep_graph=true. + bool has_graph_exec() const { + return has_graph_exec_; + } + void replay(); + void reset(); + MempoolId_t pool(); + std::vector pools(); + void retain_pool(MempoolId_t pool); + void enable_debug_mode(); + cudaGraph_t raw_cuda_graph(); + cudaGraphExec_t raw_cuda_graph_exec(); + + static CUDAGraph* get_currently_capturing_graph(); + void begin_capture_to_if_node(const Tensor& scalar_cuda_pred_tensor); + void end_capture_to_conditional_node(); + static void set_conditional_handle( + cudaGraphConditionalHandle handle, + const Tensor& scalar_cuda_pred_tensor); + + private: + template + std::function create_allocate_filter() const; + std::function create_child_allocate_filter(); + void record_retained_pool(MempoolId_t pool); + bool has_retained_pool(MempoolId_t pool) const; + + protected: + cudaGraph_t graph_ = nullptr; + cudaGraphExec_t graph_exec_ = nullptr; + + // internal states so reset() can do its best cleaning up + + // Set to true in capture_end if cudaStreamEndCapture succeeded + // Set back to false after instantiate() unless keep_graph=True or + // enable_debug_mode() was called on any CUDAGraph instance. + bool has_graph_ = false; + // Set to true in capture_end if cudaStreamEndCapture succeeded + bool capture_ended_ = false; + // Set to true in capture_end if cudaGraphInstantiate succeeded + bool has_graph_exec_ = false; + + // the ID assigned by cuda during graph capture, + // used to identify when a stream is participating in capture + CaptureId_t capture_id_ = 0; + + // uuid used to request a particular private mempool from CUDACachingAllocator. + // By default, this will be set to {id_, 0}. + // + // If capture_begin is called with "pool=other_graph.pool()", this graph's mempool_id_ + // will be set to the other graph's mempool_id_, and therefore share a mempool with the + // other graph. + // + // If capture_begin is called with "pool=handle" where "handle" came from graph_pool_handle(), + // it will share a mempool with any other captures that used "pool=handle". + // + // Sharing a mempool across graphs saves memory, and it's safe if you + // know you'll replay those graphs in the same order you captured them. + MempoolId_t mempool_id_; + std::vector retained_mempool_ids_; + + // Stream on which capture began + at::cuda::CUDAStream capture_stream_; + + // multiple generator states and their wholegraph_increments in this graph + // that are managed by the CUDA Graph + ska::flat_hash_map, uint64_t> + captured_generator_states_; + + // Device where capture occurred. Right now, for simplicity, we require all ops + // in a capture to run on the same device, but this is a limitation of CUDAGraph, + // not CUDA itself. We can straightforwardly modify CUDAGraph to support multi-device + // captures if needed. + // init capture_dev_ as UNDEFINED_DEVICE to check that it stores the real device id in the destructor + static constexpr c10::DeviceIndex UNDEFINED_DEVICE = -1; + c10::DeviceIndex capture_dev_{UNDEFINED_DEVICE}; + + bool keep_graph_; + cudaStreamCaptureMode capture_mode_{}; + +#if !defined(USE_ROCM) && (defined(CUDA_VERSION) && CUDA_VERSION >= 12040) + struct OwnedCUDAStream { + cudaStream_t stream = nullptr; + OwnedCUDAStream() = default; + explicit OwnedCUDAStream(cudaStream_t s) : stream(s) {} + ~OwnedCUDAStream() { + if (stream) + C10_CUDA_CHECK_WARN(cudaStreamDestroy(stream)); + } + OwnedCUDAStream(const OwnedCUDAStream&) = delete; + OwnedCUDAStream& operator=(const OwnedCUDAStream&) = delete; + OwnedCUDAStream(OwnedCUDAStream&& o) noexcept + : stream(std::exchange(o.stream, nullptr)) {} + OwnedCUDAStream& operator=(OwnedCUDAStream&& o) noexcept { + if (stream) + C10_CUDA_CHECK_WARN(cudaStreamDestroy(stream)); + stream = std::exchange(o.stream, nullptr); + return *this; + } + }; + + std::stack conditional_node_streams_; + std::stack conditional_graph_capture_ids_; + std::stack conditional_node_raw_streams_; +#endif // !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12040 +}; + +template <> +std::function CUDAGraph::create_allocate_filter() const; +template <> +std::function CUDAGraph::create_allocate_filter() const; + +} // namespace cuda +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraphsUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraphsUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..48d77fe14bb59b5a41aa37a00902280b803ef807 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAGraphsUtils.cuh @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +// c10/cuda/CUDAGraphsC10Utils.h has utils used by both c10 and aten. +// This file adds utils used by aten only. + +namespace at::cuda { + +using CaptureId_t = c10::cuda::CaptureId_t; +using CaptureStatus = c10::cuda::CaptureStatus; + +// Use this version where you don't want to create a CUDA context if none exists. +inline CaptureStatus currentStreamCaptureStatus() { + if (c10::cuda::hasPrimaryContext(c10::cuda::current_device())) { + return c10::cuda::currentStreamCaptureStatusMayInitCtx(); + } + return CaptureStatus::None; +} + +inline std::optional currentStreamCaptureId() { + if (c10::cuda::hasPrimaryContext(c10::cuda::current_device())) { + return c10::cuda::currentStreamCaptureIdMayInitCtx(); + } + return std::nullopt; +} + +inline void assertNotCapturing(const std::string& attempt) { + auto status = currentStreamCaptureStatus(); + TORCH_CHECK(status == CaptureStatus::None, + attempt, + " during CUDA graph capture. If you need this call to be captured, " + "please file an issue. " + "Current cudaStreamCaptureStatus: ", + status); +} + +inline void errorIfCapturingCudnnBenchmark(const std::string& version_specific) { + auto status = currentStreamCaptureStatus(); + TORCH_CHECK(status == CaptureStatus::None, + "Current cudaStreamCaptureStatus: ", + status, + "\nCapturing ", + version_specific, + "is prohibited. Possible causes of this error:\n" + "1. No warmup iterations occurred before capture.\n" + "2. The convolutions you're trying to capture use dynamic shapes, " + "in which case capturing them is generally prohibited."); +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparse.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparse.h new file mode 100644 index 0000000000000000000000000000000000000000..4e2ac2903b187bcfa4f300a458c2eb1ad45b5453 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparse.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#if defined(USE_ROCM) +#include +#define HIPSPARSE_VERSION ((hipsparseVersionMajor*100000) + (hipsparseVersionMinor*100) + hipsparseVersionPatch) +#endif + + +// cuSparse Generic API spsv function was added in CUDA 11.3.0 +// hipSparse supports SpSV as well +#if (defined(CUDART_VERSION) && defined(CUSPARSE_VERSION)) || defined(USE_ROCM) +#define AT_USE_CUSPARSE_GENERIC_SPSV() 1 +#else +#define AT_USE_CUSPARSE_GENERIC_SPSV() 0 +#endif + +// cuSparse Generic API spsm function was added in CUDA 11.3.1 +// hipSparse supports SpSM as well +#if (defined(CUDART_VERSION) && defined(CUSPARSE_VERSION)) || defined(USE_ROCM) +#define AT_USE_CUSPARSE_GENERIC_SPSM() 1 +#else +#define AT_USE_CUSPARSE_GENERIC_SPSM() 0 +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseBlas.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseBlas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12345d8747fb33b1b0fba1e99b202e8efcc08eea --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseBlas.cpp @@ -0,0 +1,885 @@ +/* + Provides the implementations of cuSPARSE function templates. +*/ + +#include + +namespace at::cuda::sparse { + +template <> +void csrgeam2_bufferSizeExt( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseScsrgeam2_bufferSizeExt( + handle, + m, + n, + alpha, + descrA, + nnzA, + csrSortedValA, + csrSortedRowPtrA, + csrSortedColIndA, + beta, + descrB, + nnzB, + csrSortedValB, + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + csrSortedValC, + csrSortedRowPtrC, + csrSortedColIndC, + pBufferSizeInBytes)); +} + +template <> +void csrgeam2_bufferSizeExt( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDcsrgeam2_bufferSizeExt( + handle, + m, + n, + alpha, + descrA, + nnzA, + csrSortedValA, + csrSortedRowPtrA, + csrSortedColIndA, + beta, + descrB, + nnzB, + csrSortedValB, + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + csrSortedValC, + csrSortedRowPtrC, + csrSortedColIndC, + pBufferSizeInBytes)); +} + +template <> +void csrgeam2_bufferSizeExt>( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCcsrgeam2_bufferSizeExt( + handle, + m, + n, + reinterpret_cast(alpha), + descrA, + nnzA, + reinterpret_cast(csrSortedValA), + csrSortedRowPtrA, + csrSortedColIndA, + reinterpret_cast(beta), + descrB, + nnzB, + reinterpret_cast(csrSortedValB), + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + reinterpret_cast(csrSortedValC), + csrSortedRowPtrC, + csrSortedColIndC, + pBufferSizeInBytes)); +} + +template <> +void csrgeam2_bufferSizeExt>( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZcsrgeam2_bufferSizeExt( + handle, + m, + n, + reinterpret_cast(alpha), + descrA, + nnzA, + reinterpret_cast(csrSortedValA), + csrSortedRowPtrA, + csrSortedColIndA, + reinterpret_cast(beta), + descrB, + nnzB, + reinterpret_cast(csrSortedValB), + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + reinterpret_cast(csrSortedValC), + csrSortedRowPtrC, + csrSortedColIndC, + pBufferSizeInBytes)); +} + +template <> +void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseScsrgeam2( + handle, + m, + n, + alpha, + descrA, + nnzA, + csrSortedValA, + csrSortedRowPtrA, + csrSortedColIndA, + beta, + descrB, + nnzB, + csrSortedValB, + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + csrSortedValC, + csrSortedRowPtrC, + csrSortedColIndC, + pBuffer)); +} + +template <> +void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDcsrgeam2( + handle, + m, + n, + alpha, + descrA, + nnzA, + csrSortedValA, + csrSortedRowPtrA, + csrSortedColIndA, + beta, + descrB, + nnzB, + csrSortedValB, + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + csrSortedValC, + csrSortedRowPtrC, + csrSortedColIndC, + pBuffer)); +} + +template <> +void csrgeam2>( + CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCcsrgeam2( + handle, + m, + n, + reinterpret_cast(alpha), + descrA, + nnzA, + reinterpret_cast(csrSortedValA), + csrSortedRowPtrA, + csrSortedColIndA, + reinterpret_cast(beta), + descrB, + nnzB, + reinterpret_cast(csrSortedValB), + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + reinterpret_cast(csrSortedValC), + csrSortedRowPtrC, + csrSortedColIndC, + pBuffer)); +} + +template <> +void csrgeam2>( + CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZcsrgeam2( + handle, + m, + n, + reinterpret_cast(alpha), + descrA, + nnzA, + reinterpret_cast(csrSortedValA), + csrSortedRowPtrA, + csrSortedColIndA, + reinterpret_cast(beta), + descrB, + nnzB, + reinterpret_cast(csrSortedValB), + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + reinterpret_cast(csrSortedValC), + csrSortedRowPtrC, + csrSortedColIndC, + pBuffer)); +} + +template <> +void bsrmm(CUSPARSE_BSRMM_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrmm( + handle, + dirA, + transA, + transB, + mb, + n, + kb, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + B, + ldb, + beta, + C, + ldc)); +} + +template <> +void bsrmm(CUSPARSE_BSRMM_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrmm( + handle, + dirA, + transA, + transB, + mb, + n, + kb, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + B, + ldb, + beta, + C, + ldc)); +} + +template <> +void bsrmm>(CUSPARSE_BSRMM_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrmm( + handle, + dirA, + transA, + transB, + mb, + n, + kb, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + reinterpret_cast(B), + ldb, + reinterpret_cast(beta), + reinterpret_cast(C), + ldc)); +} + +template <> +void bsrmm>( + CUSPARSE_BSRMM_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrmm( + handle, + dirA, + transA, + transB, + mb, + n, + kb, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + reinterpret_cast(B), + ldb, + reinterpret_cast(beta), + reinterpret_cast(C), + ldc)); +} + +template <> +void bsrmv(CUSPARSE_BSRMV_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrmv( + handle, + dirA, + transA, + mb, + nb, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + x, + beta, + y)); +} + +template <> +void bsrmv(CUSPARSE_BSRMV_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrmv( + handle, + dirA, + transA, + mb, + nb, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + x, + beta, + y)); +} + +template <> +void bsrmv>(CUSPARSE_BSRMV_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrmv( + handle, + dirA, + transA, + mb, + nb, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + reinterpret_cast(x), + reinterpret_cast(beta), + reinterpret_cast(y))); +} + +template <> +void bsrmv>( + CUSPARSE_BSRMV_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrmv( + handle, + dirA, + transA, + mb, + nb, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + reinterpret_cast(x), + reinterpret_cast(beta), + reinterpret_cast(y))); +} + +template <> +void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrsv2_bufferSize( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrsv2_bufferSize( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsv2_bufferSize>( + CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrsv2_bufferSize( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsv2_bufferSize>( + CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrsv2_bufferSize( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrsv2_analysis( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrsv2_analysis( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsv2_analysis>( + CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrsv2_analysis( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsv2_analysis>( + CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrsv2_analysis( + handle, + dirA, + transA, + mb, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrsv2_solve( + handle, + dirA, + transA, + mb, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + x, + y, + policy, + pBuffer)); +} + +template <> +void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrsv2_solve( + handle, + dirA, + transA, + mb, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + x, + y, + policy, + pBuffer)); +} + +template <> +void bsrsv2_solve>( + CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrsv2_solve( + handle, + dirA, + transA, + mb, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + reinterpret_cast(x), + reinterpret_cast(y), + policy, + pBuffer)); +} + +template <> +void bsrsv2_solve>( + CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrsv2_solve( + handle, + dirA, + transA, + mb, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + reinterpret_cast(x), + reinterpret_cast(y), + policy, + pBuffer)); +} + +template <> +void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrsm2_bufferSize( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrsm2_bufferSize( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsm2_bufferSize>( + CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrsm2_bufferSize( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsm2_bufferSize>( + CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrsm2_bufferSize( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + pBufferSizeInBytes)); +} + +template <> +void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrsm2_analysis( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrsm2_analysis( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsm2_analysis>( + CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrsm2_analysis( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsm2_analysis>( + CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrsm2_analysis( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + policy, + pBuffer)); +} + +template <> +void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(float)) { + TORCH_CUDASPARSE_CHECK(cusparseSbsrsm2_solve( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + B, + ldb, + X, + ldx, + policy, + pBuffer)); +} + +template <> +void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(double)) { + TORCH_CUDASPARSE_CHECK(cusparseDbsrsm2_solve( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + alpha, + descrA, + bsrValA, + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + B, + ldb, + X, + ldx, + policy, + pBuffer)); +} + +template <> +void bsrsm2_solve>( + CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseCbsrsm2_solve( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + reinterpret_cast(B), + ldb, + reinterpret_cast(X), + ldx, + policy, + pBuffer)); +} + +template <> +void bsrsm2_solve>( + CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex)) { + TORCH_CUDASPARSE_CHECK(cusparseZbsrsm2_solve( + handle, + dirA, + transA, + transX, + mb, + n, + nnzb, + reinterpret_cast(alpha), + descrA, + reinterpret_cast(bsrValA), + bsrRowPtrA, + bsrColIndA, + blockDim, + info, + reinterpret_cast(B), + ldb, + reinterpret_cast(X), + ldx, + policy, + pBuffer)); +} + +} // namespace at::cuda::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseBlas.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseBlas.h new file mode 100644 index 0000000000000000000000000000000000000000..937cf9ff64c2c98ff8677d660b8093c5de4bd768 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseBlas.h @@ -0,0 +1,318 @@ +#pragma once + +/* + Provides a subset of cuSPARSE functions as templates: + + csrgeam2(...) + + where scalar_t is double, float, c10::complex or c10::complex. + The functions are available in at::cuda::sparse namespace. +*/ + +#include +#include + +// NOLINTBEGIN(misc-misplaced-const) +namespace at::cuda::sparse { + +#define CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, int m, int n, const scalar_t *alpha, \ + const cusparseMatDescr_t descrA, int nnzA, \ + const scalar_t *csrSortedValA, const int *csrSortedRowPtrA, \ + const int *csrSortedColIndA, const scalar_t *beta, \ + const cusparseMatDescr_t descrB, int nnzB, \ + const scalar_t *csrSortedValB, const int *csrSortedRowPtrB, \ + const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \ + const scalar_t *csrSortedValC, const int *csrSortedRowPtrC, \ + const int *csrSortedColIndC, size_t *pBufferSizeInBytes + +template +inline void csrgeam2_bufferSizeExt( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::csrgeam2_bufferSizeExt: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void csrgeam2_bufferSizeExt( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(float)); +template <> +void csrgeam2_bufferSizeExt( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(double)); +template <> +void csrgeam2_bufferSizeExt>( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex)); +template <> +void csrgeam2_bufferSizeExt>( + CUSPARSE_CSRGEAM2_BUFFERSIZE_ARGTYPES(c10::complex)); + +#define CUSPARSE_CSRGEAM2_NNZ_ARGTYPES() \ + cusparseHandle_t handle, int m, int n, const cusparseMatDescr_t descrA, \ + int nnzA, const int *csrSortedRowPtrA, const int *csrSortedColIndA, \ + const cusparseMatDescr_t descrB, int nnzB, const int *csrSortedRowPtrB, \ + const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \ + int *csrSortedRowPtrC, int *nnzTotalDevHostPtr, void *workspace + +template +inline void csrgeam2Nnz(CUSPARSE_CSRGEAM2_NNZ_ARGTYPES()) { + TORCH_CUDASPARSE_CHECK(cusparseXcsrgeam2Nnz( + handle, + m, + n, + descrA, + nnzA, + csrSortedRowPtrA, + csrSortedColIndA, + descrB, + nnzB, + csrSortedRowPtrB, + csrSortedColIndB, + descrC, + csrSortedRowPtrC, + nnzTotalDevHostPtr, + workspace)); +} + +#define CUSPARSE_CSRGEAM2_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, int m, int n, const scalar_t *alpha, \ + const cusparseMatDescr_t descrA, int nnzA, \ + const scalar_t *csrSortedValA, const int *csrSortedRowPtrA, \ + const int *csrSortedColIndA, const scalar_t *beta, \ + const cusparseMatDescr_t descrB, int nnzB, \ + const scalar_t *csrSortedValB, const int *csrSortedRowPtrB, \ + const int *csrSortedColIndB, const cusparseMatDescr_t descrC, \ + scalar_t *csrSortedValC, int *csrSortedRowPtrC, int *csrSortedColIndC, \ + void *pBuffer + +template +inline void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::csrgeam2: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(float)); +template <> +void csrgeam2(CUSPARSE_CSRGEAM2_ARGTYPES(double)); +template <> +void csrgeam2>( + CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex)); +template <> +void csrgeam2>( + CUSPARSE_CSRGEAM2_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRMM_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, cusparseOperation_t transB, int mb, int n, \ + int kb, int nnzb, const scalar_t *alpha, \ + const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \ + const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \ + const scalar_t *B, int ldb, const scalar_t *beta, scalar_t *C, int ldc + +template +inline void bsrmm(CUSPARSE_BSRMM_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrmm: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrmm(CUSPARSE_BSRMM_ARGTYPES(float)); +template <> +void bsrmm(CUSPARSE_BSRMM_ARGTYPES(double)); +template <> +void bsrmm>(CUSPARSE_BSRMM_ARGTYPES(c10::complex)); +template <> +void bsrmm>(CUSPARSE_BSRMM_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRMV_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, int mb, int nb, int nnzb, \ + const scalar_t *alpha, const cusparseMatDescr_t descrA, \ + const scalar_t *bsrValA, const int *bsrRowPtrA, const int *bsrColIndA, \ + int blockDim, const scalar_t *x, const scalar_t *beta, scalar_t *y + +template +inline void bsrmv(CUSPARSE_BSRMV_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrmv: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrmv(CUSPARSE_BSRMV_ARGTYPES(float)); +template <> +void bsrmv(CUSPARSE_BSRMV_ARGTYPES(double)); +template <> +void bsrmv>(CUSPARSE_BSRMV_ARGTYPES(c10::complex)); +template <> +void bsrmv>(CUSPARSE_BSRMV_ARGTYPES(c10::complex)); + + +#define CUSPARSE_BSRSV2_BUFFER_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, int mb, int nnzb, \ + const cusparseMatDescr_t descrA, scalar_t *bsrValA, \ + const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \ + bsrsv2Info_t info, int *pBufferSizeInBytes + +template +inline void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrsv2_bufferSize: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(float)); +template <> +void bsrsv2_bufferSize(CUSPARSE_BSRSV2_BUFFER_ARGTYPES(double)); +template <> +void bsrsv2_bufferSize>( + CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex)); +template <> +void bsrsv2_bufferSize>( + CUSPARSE_BSRSV2_BUFFER_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, int mb, int nnzb, \ + const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \ + const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \ + bsrsv2Info_t info, cusparseSolvePolicy_t policy, void *pBuffer + +template +inline void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrsv2_analysis: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(float)); +template <> +void bsrsv2_analysis(CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(double)); +template <> +void bsrsv2_analysis>( + CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex)); +template <> +void bsrsv2_analysis>( + CUSPARSE_BSRSV2_ANALYSIS_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRSV2_SOLVE_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, int mb, int nnzb, const scalar_t *alpha, \ + const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \ + const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \ + bsrsv2Info_t info, const scalar_t *x, scalar_t *y, \ + cusparseSolvePolicy_t policy, void *pBuffer + +template +inline void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrsv2_solve: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(float)); +template <> +void bsrsv2_solve(CUSPARSE_BSRSV2_SOLVE_ARGTYPES(double)); +template <> +void bsrsv2_solve>( + CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex)); +template <> +void bsrsv2_solve>( + CUSPARSE_BSRSV2_SOLVE_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRSM2_BUFFER_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \ + int nnzb, const cusparseMatDescr_t descrA, scalar_t *bsrValA, \ + const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \ + bsrsm2Info_t info, int *pBufferSizeInBytes + +template +inline void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrsm2_bufferSize: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(float)); +template <> +void bsrsm2_bufferSize(CUSPARSE_BSRSM2_BUFFER_ARGTYPES(double)); +template <> +void bsrsm2_bufferSize>( + CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex)); +template <> +void bsrsm2_bufferSize>( + CUSPARSE_BSRSM2_BUFFER_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \ + int nnzb, const cusparseMatDescr_t descrA, const scalar_t *bsrValA, \ + const int *bsrRowPtrA, const int *bsrColIndA, int blockDim, \ + bsrsm2Info_t info, cusparseSolvePolicy_t policy, void *pBuffer + +template +inline void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrsm2_analysis: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(float)); +template <> +void bsrsm2_analysis(CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(double)); +template <> +void bsrsm2_analysis>( + CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex)); +template <> +void bsrsm2_analysis>( + CUSPARSE_BSRSM2_ANALYSIS_ARGTYPES(c10::complex)); + +#define CUSPARSE_BSRSM2_SOLVE_ARGTYPES(scalar_t) \ + cusparseHandle_t handle, cusparseDirection_t dirA, \ + cusparseOperation_t transA, cusparseOperation_t transX, int mb, int n, \ + int nnzb, const scalar_t *alpha, const cusparseMatDescr_t descrA, \ + const scalar_t *bsrValA, const int *bsrRowPtrA, const int *bsrColIndA, \ + int blockDim, bsrsm2Info_t info, const scalar_t *B, int ldb, \ + scalar_t *X, int ldx, cusparseSolvePolicy_t policy, void *pBuffer + +template +inline void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::cuda::sparse::bsrsm2_solve: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(float)); +template <> +void bsrsm2_solve(CUSPARSE_BSRSM2_SOLVE_ARGTYPES(double)); +template <> +void bsrsm2_solve>( + CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex)); +template <> +void bsrsm2_solve>( + CUSPARSE_BSRSM2_SOLVE_ARGTYPES(c10::complex)); + + +} // namespace at::cuda::sparse +// NOLINTEND(misc-misplaced-const) diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseDescriptors.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseDescriptors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1eec52b483d0c0b6b0d6255114fb7d8fab50ac16 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseDescriptors.cpp @@ -0,0 +1,209 @@ +#include +#include +#include +#include + +namespace at::cuda::sparse { + +cusparseStatus_t destroyConstDnMat(const cusparseDnMatDescr* dnMatDescr) { + // NOLINTNEXTLINE(*const-cast) + return cusparseDestroyDnMat(const_cast(dnMatDescr)); +} + +namespace { + +// If a specific GPU model does not provide native support for a given data +// type, cuSparse routines return CUSPARSE_STATUS_ARCH_MISMATCH error +void check_supported_cuda_type(cudaDataType cuda_type) { + if (cuda_type == CUDA_R_16F) { + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + TORCH_CHECK( + prop->major >= 5 && ((10 * prop->major + prop->minor) >= 53), + "Sparse operations with CUDA tensors of Float16 type are not supported on GPUs with compute capability < 5.3 (current: ", + prop->major, + ".", + prop->minor, + ")"); + } +#if !defined(USE_ROCM) + if (cuda_type == CUDA_R_16BF) { + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + TORCH_CHECK( + prop->major >= 8, + "Sparse operations with CUDA tensors of BFloat16 type are not supported on GPUs with compute capability < 8.0 (current: ", + prop->major, + ".", + prop->minor, + ")"); + } +#endif +} + +} // anonymous namespace + +cusparseIndexType_t getCuSparseIndexType(const c10::ScalarType& scalar_type) { + if (scalar_type == c10::ScalarType::Int) { + return CUSPARSE_INDEX_32I; + } else if (scalar_type == c10::ScalarType::Long) { + return CUSPARSE_INDEX_64I; + } else { + TORCH_INTERNAL_ASSERT( + false, "Cannot convert type ", scalar_type, " to cusparseIndexType."); + } +} + +cusparseDnMatDescr_t createRawDnMatDescriptor(const Tensor& input, int64_t batch_offset, bool is_const=false) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.layout() == kStrided); + IntArrayRef input_strides = input.strides(); + IntArrayRef input_sizes = input.sizes(); + auto ndim = input.dim(); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2); + auto rows = input_sizes[ndim - 2]; + auto cols = input_sizes[ndim - 1]; + + bool is_column_major = + at::native::is_blas_compatible_column_major_order(input); + bool is_row_major = at::native::is_blas_compatible_row_major_order(input); + TORCH_INTERNAL_ASSERT( + is_column_major || is_row_major, + "Expected either row or column major contiguous input."); + + auto leading_dimension = + is_row_major ? input_strides[ndim - 2] : input_strides[ndim - 1]; + + auto order = is_row_major ? CUSPARSE_ORDER_ROW : CUSPARSE_ORDER_COL; + + auto batch_stride = ndim > 2 && batch_offset >= 0 ? input_strides[ndim - 3] : 0; + // NOLINTNEXTLINE(*const-cast) + void* data_ptr = is_const ? const_cast(input.const_data_ptr()) : input.data_ptr(); + void* values_ptr = static_cast(data_ptr) + + batch_offset * batch_stride * input.itemsize(); + + cudaDataType value_type = ScalarTypeToCudaDataType(input.scalar_type()); + check_supported_cuda_type(value_type); + + // NOTE: Ideally, in the const case, we would use cusparseConstDnMatDescr_t + // and cusparseCreateConstDnMat, but those were introduced in CUDA 12, and we + // still need to support CUDA 11 + cusparseDnMatDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateDnMat( + &raw_descriptor, + rows, + cols, + leading_dimension, + values_ptr, + value_type, + order)); + + if (ndim >= 3 && batch_offset == -1) { + int batch_count = + at::native::cuda_int_cast(at::native::batchCount(input), "batch_count"); + TORCH_CUDASPARSE_CHECK(cusparseDnMatSetStridedBatch( + raw_descriptor, batch_count, input_strides[ndim - 3])); + } + return raw_descriptor; +} + +CuSparseDnMatDescriptor::CuSparseDnMatDescriptor(const Tensor& input, int64_t batch_offset) { + descriptor_.reset(createRawDnMatDescriptor(input, batch_offset)); +} + +CuSparseConstDnMatDescriptor::CuSparseConstDnMatDescriptor(const Tensor& input, int64_t batch_offset) { + descriptor_.reset(createRawDnMatDescriptor(input, batch_offset, /*is_const*/true)); +} + +CuSparseDnVecDescriptor::CuSparseDnVecDescriptor(const Tensor& input) { + // cuSPARSE doesn't support batched vectors + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + input.dim() == 1 || (input.dim() == 2 && input.size(-1) == 1)); + + // cuSPARSE doesn't support non-contiguous vectors + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.is_contiguous()); + + cudaDataType value_type = ScalarTypeToCudaDataType(input.scalar_type()); + check_supported_cuda_type(value_type); + + cusparseDnVecDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateDnVec( + &raw_descriptor, input.numel(), input.data_ptr(), value_type)); + descriptor_.reset(raw_descriptor); +} + +CuSparseSpMatCsrDescriptor::CuSparseSpMatCsrDescriptor(const Tensor& input, int64_t batch_offset) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.is_sparse_csr()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.dim() >= 2); + + IntArrayRef input_sizes = input.sizes(); + auto ndim = input.dim(); + auto rows = input_sizes[ndim - 2]; + auto cols = input_sizes[ndim - 1]; + + auto crow_indices = input.crow_indices(); + auto col_indices = input.col_indices(); + auto values = input.values(); + auto nnz = values.size(-1); + c10::MaybeOwned values_ = values.expect_contiguous(); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(crow_indices.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(col_indices.is_contiguous()); + + cusparseIndexType_t index_type = + getCuSparseIndexType(crow_indices.scalar_type()); + cudaDataType value_type = ScalarTypeToCudaDataType(input.scalar_type()); + check_supported_cuda_type(value_type); + + auto crow_indices_batch_stride = crow_indices.dim() >= 2 && batch_offset >= 0 + ? crow_indices.stride(-2) + : 0; + auto col_indices_batch_stride = + col_indices.dim() >= 2 && batch_offset >= 0 ? col_indices.stride(-2) : 0; + auto values_batch_stride = + values.dim() >= 2 && batch_offset >= 0 ? values_->stride(-2) : 0; + + cusparseSpMatDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateCsr( + &raw_descriptor, // output descriptor + rows, + cols, + nnz, + // row offsets of the sparse matrix, size = rows + 1 + static_cast(crow_indices.data_ptr()) + + batch_offset * crow_indices_batch_stride * crow_indices.itemsize(), + // column indices of the sparse matrix, size = nnz + static_cast(col_indices.data_ptr()) + + batch_offset * col_indices_batch_stride * col_indices.itemsize(), + // values of the sparse matrix, size = nnz + static_cast(values_->data_ptr()) + + batch_offset * values_batch_stride * values.itemsize(), + index_type, // data type of row offsets index + index_type, // data type of col indices + CUSPARSE_INDEX_BASE_ZERO, // base index of row offset and col index + value_type // data type of values + )); + + if (ndim == 3 && batch_offset == -1) { + int batch_count = + at::native::cuda_int_cast(at::native::batchCount(input), "batch_count"); + if (crow_indices.dim() >= 2 || values.dim() >= 2 || + col_indices.dim() >= 2) { + // cuSPARSE ignores the strides and uses only the first batch + TORCH_INTERNAL_ASSERT( + false, + "Support for batched CSR indices and values is not implemented."); + TORCH_CUDASPARSE_CHECK(cusparseCsrSetStridedBatch( + raw_descriptor, + batch_count, + crow_indices.stride(-2), + values_->stride(-2))); + } else { + // cuSPARSE allows broadcasting of indices and values across batches for + // batched matmul + TORCH_CUDASPARSE_CHECK( + cusparseCsrSetStridedBatch(raw_descriptor, batch_count, 0, 0)); + } + } + + descriptor_.reset(raw_descriptor); +} + +} // namespace at::cuda::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseDescriptors.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseDescriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..6585894395daa8ad2449f651932740572bd180bf --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDASparseDescriptors.h @@ -0,0 +1,250 @@ +#pragma once + +#include +#include +#include + +#include + +#if defined(USE_ROCM) +#include +#endif + +namespace at::cuda::sparse { + +template +struct CuSparseDescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_CUDASPARSE_CHECK(destructor(x)); + } + } +}; + +template +class CuSparseDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; + +template +struct ConstCuSparseDescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_CUDASPARSE_CHECK(destructor(x)); + } + } +}; + +template +class ConstCuSparseDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; + +#if defined(USE_ROCM) +using cusparseMatDescr = std::remove_pointer_t; +using cusparseDnMatDescr = std::remove_pointer_t; +using cusparseDnVecDescr = std::remove_pointer_t; +using cusparseSpMatDescr = std::remove_pointer_t; +using cusparseSpMatDescr = std::remove_pointer_t; +using cusparseSpGEMMDescr = std::remove_pointer_t; +using cusparseSpSVDescr = std::remove_pointer_t; +using cusparseSpSMDescr = std::remove_pointer_t; +using bsrsv2Info = std::remove_pointer_t; +using bsrsm2Info = std::remove_pointer_t; +#endif + +// NOTE: This is only needed for CUDA 11 and earlier, since CUDA 12 introduced +// API for const descriptors +cusparseStatus_t destroyConstDnMat(const cusparseDnMatDescr* dnMatDescr); + +class TORCH_CUDA_CPP_API CuSparseMatDescriptor + : public CuSparseDescriptor { + public: + CuSparseMatDescriptor() { + cusparseMatDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } + + CuSparseMatDescriptor(bool upper, bool unit) { + cusparseFillMode_t fill_mode = + upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER; + cusparseDiagType_t diag_type = + unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT; + cusparseMatDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateMatDescr(&raw_descriptor)); + TORCH_CUDASPARSE_CHECK(cusparseSetMatFillMode(raw_descriptor, fill_mode)); + TORCH_CUDASPARSE_CHECK(cusparseSetMatDiagType(raw_descriptor, diag_type)); + descriptor_.reset(raw_descriptor); + } +}; + + +class TORCH_CUDA_CPP_API CuSparseBsrsv2Info + : public CuSparseDescriptor { + public: + CuSparseBsrsv2Info() { + bsrsv2Info_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsv2Info(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; + +class TORCH_CUDA_CPP_API CuSparseBsrsm2Info + : public CuSparseDescriptor { + public: + CuSparseBsrsm2Info() { + bsrsm2Info_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseCreateBsrsm2Info(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; + + +cusparseIndexType_t getCuSparseIndexType(const c10::ScalarType& scalar_type); + + class TORCH_CUDA_CPP_API CuSparseDnMatDescriptor + : public ConstCuSparseDescriptor< + cusparseDnMatDescr, + &cusparseDestroyDnMat> { + public: + explicit CuSparseDnMatDescriptor( + const Tensor& input, + int64_t batch_offset = -1); + }; + + class TORCH_CUDA_CPP_API CuSparseConstDnMatDescriptor + : public ConstCuSparseDescriptor< + const cusparseDnMatDescr, + &destroyConstDnMat> { + public: + explicit CuSparseConstDnMatDescriptor( + const Tensor& input, + int64_t batch_offset = -1); + cusparseDnMatDescr* unsafe_mutable_descriptor() const { + return const_cast(descriptor()); + } + cusparseDnMatDescr* unsafe_mutable_descriptor() { + return const_cast(descriptor()); + } + }; + + class TORCH_CUDA_CPP_API CuSparseDnVecDescriptor + : public ConstCuSparseDescriptor< + cusparseDnVecDescr, + &cusparseDestroyDnVec> { + public: + explicit CuSparseDnVecDescriptor(const Tensor& input); + }; + + class TORCH_CUDA_CPP_API CuSparseSpMatDescriptor + : public ConstCuSparseDescriptor< + cusparseSpMatDescr, + &cusparseDestroySpMat> {}; + +class TORCH_CUDA_CPP_API CuSparseSpMatCsrDescriptor + : public CuSparseSpMatDescriptor { + public: + explicit CuSparseSpMatCsrDescriptor(const Tensor& input, int64_t batch_offset = -1); + + std::tuple get_size() { + int64_t rows = 0, cols = 0, nnz = 0; + TORCH_CUDASPARSE_CHECK(cusparseSpMatGetSize( + this->descriptor(), + &rows, + &cols, + &nnz)); + return std::make_tuple(rows, cols, nnz); + } + + void set_tensor(const Tensor& input) { + auto crow_indices = input.crow_indices(); + auto col_indices = input.col_indices(); + auto values = input.values(); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(crow_indices.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(col_indices.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.is_contiguous()); + TORCH_CUDASPARSE_CHECK(cusparseCsrSetPointers( + this->descriptor(), + crow_indices.data_ptr(), + col_indices.data_ptr(), + values.data_ptr())); + } + +#if AT_USE_CUSPARSE_GENERIC_SPSV() + void set_mat_fill_mode(bool upper) { + cusparseFillMode_t fill_mode = + upper ? CUSPARSE_FILL_MODE_UPPER : CUSPARSE_FILL_MODE_LOWER; + TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute( + this->descriptor(), + CUSPARSE_SPMAT_FILL_MODE, + &fill_mode, + sizeof(fill_mode))); + } + + void set_mat_diag_type(bool unit) { + cusparseDiagType_t diag_type = + unit ? CUSPARSE_DIAG_TYPE_UNIT : CUSPARSE_DIAG_TYPE_NON_UNIT; + TORCH_CUDASPARSE_CHECK(cusparseSpMatSetAttribute( + this->descriptor(), + CUSPARSE_SPMAT_DIAG_TYPE, + &diag_type, + sizeof(diag_type))); + } +#endif +}; + +#if AT_USE_CUSPARSE_GENERIC_SPSV() +class TORCH_CUDA_CPP_API CuSparseSpSVDescriptor + : public CuSparseDescriptor { + public: + CuSparseSpSVDescriptor() { + cusparseSpSVDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseSpSV_createDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; +#endif + +#if AT_USE_CUSPARSE_GENERIC_SPSM() +class TORCH_CUDA_CPP_API CuSparseSpSMDescriptor + : public CuSparseDescriptor { + public: + CuSparseSpSMDescriptor() { + cusparseSpSMDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseSpSM_createDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; +#endif + +class TORCH_CUDA_CPP_API CuSparseSpGEMMDescriptor + : public CuSparseDescriptor { + public: + CuSparseSpGEMMDescriptor() { + cusparseSpGEMMDescr_t raw_descriptor = nullptr; + TORCH_CUDASPARSE_CHECK(cusparseSpGEMM_createDescr(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } +}; + +} // namespace at::cuda::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDATensorMethods.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDATensorMethods.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e3c8526a0004cde8198965f3aea34af25ac5c452 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDATensorMethods.cuh @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace at { +template <> +inline __half* Tensor::data() const { + return reinterpret_cast<__half*>(data()); +} +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAUtils.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..f41fae69ea89d078d61ebb3f698d0e24904761a0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CUDAUtils.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace at::cuda { + +// Check if every tensor in a list of tensors matches the current +// device. +inline bool check_device(ArrayRef ts) { + if (ts.empty()) { + return true; + } + Device curDevice = Device(kCUDA, current_device()); + for (const Tensor& t : ts) { + if (t.device() != curDevice) return false; + } + return true; +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CachingHostAllocator.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CachingHostAllocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd8a52d7c2fa2791435d836d5e178a8d31d81dc3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CachingHostAllocator.cpp @@ -0,0 +1,282 @@ +#include + +#include +#include +#include +#include +#include + +#include +#include + +namespace at::cuda { +namespace { + +using Block = HostBlock; + +struct CUDACachingHostAllocatorImpl + : public CachingHostAllocatorImpl { + void free(void* ctx) override { + using Base = CachingHostAllocatorImpl; + try { + Base::free(ctx); + } catch (...) { + if (!c10::cuda::CUDACachingAllocator::CUDAAllocatorConfig:: + pinned_free_catch_all()) { + TORCH_WARN("Exception in pinned allocator free(), rethrowing"); + throw; + } + // pinned_free_catch_all is enabled: suppress the exception to prevent + // it from escaping through ~StorageImpl() (implicitly noexcept), which + // would cause std::terminate. Allows graceful shutdown to proceed. + STATIC_GAUGE(pytorch.CUDACachingHostAllocator.free_fail_catch_all) + .record(1); + TORCH_WARN("Suppressed exception in pinned allocator free()"); + } + } + + private: + ska::flat_hash_map use_host_register; + + void allocate_host_memory(size_t size, void** ptr) override { + // try allocating from reserve segment first before calling into expensive APIs + if (get_reserve_segment().initialized()) { + *ptr = get_reserve_segment().allocate(size); + if (*ptr != nullptr) { + return; + } + } + allocate_host_memory_slowpath(size, ptr); + } + + void allocate_host_memory_slowpath(size_t size, void** ptr) { + // Pinned memory pointers allocated by any device can be directly used by + // any other device, regardless of the current device at the time of + // allocation, since we assume unified addressing. So we grab any existing + // primary context, if available. See pytorch/pytorch#21081. + // This can be a large performance hit if we cross NUMA nodes by allocating + // and pinning memory on one side of the NUMA node and then using it on the + // other side. Thankfully, we use one process per GPU, so we don't run into + // this issue. + at::OptionalDeviceGuard device_guard; + auto primary_ctx_device_index = + c10::cuda::getDeviceIndexWithPrimaryContext(); + if (primary_ctx_device_index.has_value()) { + device_guard.reset_device( + at::Device(at::DeviceType::CUDA, *primary_ctx_device_index)); + } + + auto start = std::chrono::steady_clock::now(); + bool use_register = c10::cuda::CUDACachingAllocator::CUDAAllocatorConfig::pinned_use_cuda_host_register(); + if (use_register) { + allocWithCudaHostRegister(ptr, size); + } else { + // Use cudaHostAlloc for allocating pinned memory (global lock in driver) + if (current_stream_is_capturing_fast_path()) { + at::cuda::CUDAStreamCaptureModeGuard g{cudaStreamCaptureModeRelaxed}; + C10_CUDA_CHECK(cudaHostAlloc(ptr, size, cudaHostAllocDefault)); + } else { + C10_CUDA_CHECK(cudaHostAlloc(ptr, size, cudaHostAllocDefault)); + } + } + + auto end = std::chrono::steady_clock::now(); + auto duration = std::chrono::duration_cast(end - start); + + // Update the statistics on the time spent on cudaHostAlloc/hostRegister + { + std::lock_guard g(stats_.timing_mutex_); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(use_host_register.count(*ptr) == 0); + use_host_register[*ptr] = use_register; + stats_.host_alloc_time.increase(duration.count()); + } + } + + void free_block(Block* block) override { + // We never free blocks from the reserve segment + if (get_reserve_segment().initialized()) { + // Check if the block is from the reserve segment + if (get_reserve_segment().owns(block->ptr_)) { + return; + } + } + + free_block_slowpath(block); + } + + void free_block_slowpath(Block* block) { + auto start = std::chrono::steady_clock::now(); + // Users may change the allocator config at will. torch unit tests do this. + // However, allocations using cudaHostRegister should use corresponding + // cudaHostUnregister and similarly for cudaHostAlloc / cudaFreeHost. + void* ptr = block->ptr_; + bool use_register = false; + { + std::lock_guard g(stats_.timing_mutex_); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(use_host_register.count(ptr) == 1); + use_register = use_host_register[ptr]; + } + if (use_register) { + AT_CUDA_CHECK(cudaHostUnregister(ptr)); + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + std::free(ptr); + } else { + AT_CUDA_CHECK(cudaFreeHost(ptr)); + } + auto end = std::chrono::steady_clock::now(); + auto duration = std::chrono::duration_cast(end - start); + + // Update the statistics on the time spent on cudaFreeHost/hostUnregister + { + std::lock_guard g(stats_.timing_mutex_); + use_host_register.erase(ptr); + stats_.host_free_time.increase(duration.count()); + } + } + + void record_stream( + std::optional>& events, + CUDAStream stream) override { + auto event = create_event_internal(stream.device_index()); + event->record(stream); + events->push_back(std::move(event)); + } + + bool query_event(CUDAEventPool::Event& event) override { + return event->query(); + } + + CUDAEventPool::Event create_event_internal(DeviceIndex idx) { + // Leak the event pool to avoid shutdown issue. + static auto* event_pool = new CUDAEventPool(); + return event_pool->get(idx); + } + + PinnedReserveSegment& get_reserve_segment() { + static auto reserve_segment = [&]() { + if (c10::cuda::CUDACachingAllocator::CUDAAllocatorConfig::pinned_reserve_segment_size_mb() > 0) { + void *ptr; + size_t sz = c10::cuda::CUDACachingAllocator::CUDAAllocatorConfig::pinned_reserve_segment_size_mb() * 1024 * 1024; + allocate_host_memory_slowpath(sz, &ptr); + return PinnedReserveSegment(ptr, sz); + } else { + return PinnedReserveSegment(); + } + } (); + return reserve_segment; + } + + TaskThreadPool* getThreadPool() { + static TaskThreadPool* pool = new TaskThreadPool( + static_cast(c10::cuda::CUDACachingAllocator::CUDAAllocatorConfig:: + pinned_max_register_threads())); + return pool; + } + + void mapPagesForRegister( + const void* ptr, + size_t size, + size_t i, + size_t numThreads, + size_t pageSize) { + uintptr_t start = (uintptr_t)ptr + (size * i / numThreads); + uintptr_t end = start + (size / numThreads); + if (i == (numThreads - 1)) { + end = (uintptr_t)ptr + size; + } + + // pre-fault/map the pages by setting the first byte of the page + uintptr_t alignedStart = + ((start + pageSize - 1) & ~(pageSize - 1)); + for (uintptr_t p = alignedStart; p < end; p += pageSize) { + // NOLINTNEXTLINE(performance-no-int-to-ptr) + memset((void*)p, 0, 1); + } + } + + void allocWithCudaHostRegister(void** ptr, size_t roundSize) { + // Here we do regular allocation, pre-fault/map the pages, and then do + // cudaHostRegister with GPU mapping flags to lock the pages, so we + // can minimize the cost for the cuda global lock. + // NOLINTNEXTLINE(cppcoreguidelines-no-malloc) + *ptr = std::malloc(roundSize); + + // Parallelize the mapping/registering of pages to reduce wall time + size_t pageSize = (1 << 12); // 4kB pages + size_t numMapThreads = c10::cuda::CUDACachingAllocator:: + CUDAAllocatorConfig::pinned_num_register_threads(); + if ((numMapThreads > 1) && (roundSize >= (pageSize * numMapThreads))) { + // parallelize the mapping of pages with a threadpool + auto* pool = getThreadPool(); + std::vector> promises; + std::vector> futures; + promises.reserve(numMapThreads); + futures.reserve(numMapThreads); + + for (size_t i = 0; i < numMapThreads; i++) { + promises.emplace_back(); + futures.push_back(promises[i].get_future()); + auto task = [this, + i, + ptr, + roundSize, + numMapThreads, + pageSize, + &promises]() mutable { + mapPagesForRegister( + *ptr, + roundSize, + i, // thread task-id + numMapThreads, + pageSize); + // set the promise when mapping pages are done + promises[i].set_value(); + }; + pool->run(task); + } + for (auto& future : futures) { + future.wait(); + } + } else { + // Map pages in the same thread + mapPagesForRegister(*ptr, roundSize, 0, 1, pageSize); + } + + // Register the mapped pages using cudaHostRegister + if (current_stream_is_capturing_fast_path()) { + at::cuda::CUDAStreamCaptureModeGuard g{cudaStreamCaptureModeRelaxed}; + AT_CUDA_CHECK(cudaHostRegister(*ptr, roundSize, cudaHostRegisterDefault)); + } else { + AT_CUDA_CHECK(cudaHostRegister(*ptr, roundSize, cudaHostRegisterDefault)); + } + } + + CUDAStream get_current_stream() const override { + // get_current_stream() is called in contexts (such as allocation) + // where a device may not already be set. Set it before + // continuing. + at::OptionalDeviceGuard device_guard; + auto primary_ctx_device_index = + c10::cuda::getDeviceIndexWithPrimaryContext(); + if (primary_ctx_device_index.has_value()) { + device_guard.reset_device( + at::Device(at::DeviceType::CUDA, *primary_ctx_device_index)); + } + return at::cuda::getCurrentCUDAStream(); + } + + bool stream_is_capturing(CUDAStream s) const override { + return s.is_capturing(); + } +}; + +DECLARE_HOST_ALLOCATOR( + CUDACachingHostAllocator, + CUDACachingHostAllocatorImpl, + raw_local_deleter, + caching_host_allocator) + +REGISTER_HOST_ALLOCATOR(at::kCUDA, &caching_host_allocator) + +} // anonymous namespace +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CachingHostAllocator.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/CachingHostAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..c40f0cfc79754a8503c7e8f7fbba21f5c09fcc69 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CachingHostAllocator.h @@ -0,0 +1,70 @@ +#pragma once + +#include +#include +#include +#include + +namespace at::cuda { + +// +// A caching allocator for CUDA host allocations (pinned memory). +// +// This provides a drop-in replacement for THCudaHostAllocator, which reuses +// freed pinned (page-locked) memory allocations. This avoids device +// synchronizations due to cudaFreeHost calls. +// +// To ensure correct behavior, THCCachingHostAllocator_recordEvent must be +// called anytime a pointer from this allocator is used in a cudaMemcpyAsync +// call between host and device, and passed the corresponding context from the +// allocation. This is currently invoked by at::native::copy_kernel_cuda. +// +C10_DEPRECATED_MESSAGE( + "at::cuda::getCachingHostAllocator() is deprecated. Please use at::getHostAllocator(at::kCUDA) instead.") +inline TORCH_CUDA_CPP_API at::HostAllocator* getCachingHostAllocator() { + return at::getHostAllocator(at::kCUDA); +} + +// Records an event in the specified stream. The allocation corresponding to the +// input `ptr`/`ctx` will not be reused until the event has occurred. +C10_DEPRECATED_MESSAGE( + "at::cuda::CachingHostAllocator_recordEvent(...) is deprecated. Please use at::getHostAllocator(at::kCUDA)->record_event(...) instead.") +inline TORCH_CUDA_CPP_API bool CachingHostAllocator_recordEvent( + void* ptr, + void* ctx, + c10::cuda::CUDAStream stream) { + return getHostAllocator(at::kCUDA)->record_event(ptr, ctx, stream.unwrap()); +} + +// Releases cached pinned memory allocations via cudaHostFree +C10_DEPRECATED_MESSAGE( + "at::cuda::CachingHostAllocator_emptyCache() is deprecated. Please use at::getHostAllocator(at::kCUDA)->empty_cache() instead.") +inline TORCH_CUDA_CPP_API void CachingHostAllocator_emptyCache() { + getHostAllocator(at::kCUDA)->empty_cache(); +} + +C10_DEPRECATED_MESSAGE( + "at::cuda::HostAlloc(...) is deprecated. Please use at::getHostAllocator(at::kCUDA)->allocate(...) instead.") +inline TORCH_CUDA_CPP_API at::DataPtr HostAlloc(size_t size) { + return getHostAllocator(at::kCUDA)->allocate(size); +} + +C10_DEPRECATED_MESSAGE( + "at::cuda::CachingHostAllocator_getStats() is deprecated. Please use at::getHostAllocator(at::kCUDA)->get_stats() instead.") +inline TORCH_CUDA_CPP_API at::HostStats CachingHostAllocator_getStats() { + return getHostAllocator(at::kCUDA)->get_stats(); +} + +C10_DEPRECATED_MESSAGE( + "at::cuda::CachingHostAllocator_resetAccumulatedStats() is deprecated. Please use at::getHostAllocator(at::kCUDA)->reset_accumulated_stats() instead.") +inline TORCH_CUDA_CPP_API void CachingHostAllocator_resetAccumulatedStats() { + getHostAllocator(at::kCUDA)->reset_accumulated_stats(); +} + +C10_DEPRECATED_MESSAGE( + "at::cuda::CachingHostAllocator_resetPeakStats() is deprecated. Please use at::getHostAllocator(at::kCUDA)->reset_peak_stats() instead.") +inline TORCH_CUDA_CPP_API void CachingHostAllocator_resetPeakStats() { + getHostAllocator(at::kCUDA)->reset_peak_stats(); +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CuSparseHandlePool.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CuSparseHandlePool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef443cddb94bd19b347345a57164512a8a12b3f3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CuSparseHandlePool.cpp @@ -0,0 +1,46 @@ +#include +#include + +namespace at::cuda { +namespace { + +void createCusparseHandle(cusparseHandle_t *handle) { + TORCH_CUDASPARSE_CHECK(cusparseCreate(handle)); +} + +void destroyCusparseHandle(cusparseHandle_t handle) { +// this is because of something dumb in the ordering of +// destruction. Sometimes atexit, the cuda context (or something) +// would already be destroyed by the time this gets destroyed. It +// happens in fbcode setting. @colesbury and @soumith decided to not destroy +// the handle as a workaround. +// - Comments of @soumith copied from cuDNN handle pool implementation +#ifdef NO_CUDNN_DESTROY_HANDLE +#else + cusparseDestroy(handle); +#endif +} + +using CuSparsePoolType = DeviceThreadHandlePool; + +} // namespace + +cusparseHandle_t getCurrentCUDASparseHandle() { + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + + // Thread local PoolWindows are lazily-initialized + // to avoid initialization issues that caused hangs on Windows. + // See: https://github.com/pytorch/pytorch/pull/22405 + // This thread local unique_ptrs will be destroyed when the thread terminates, + // releasing its reserved handles back to the pool. + static auto pool = std::make_shared(); + thread_local std::unique_ptr myPoolWindow( + pool->newPoolWindow()); + + auto handle = myPoolWindow->reserve(device); + TORCH_CUDASPARSE_CHECK(cusparseSetStream(handle, c10::cuda::getCurrentCUDAStream())); + return handle; +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/CublasHandlePool.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/CublasHandlePool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..038112f41bc4d41cce4db73d2a8c3f62585b08d4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/CublasHandlePool.cpp @@ -0,0 +1,499 @@ +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#if defined(USE_ROCM) +#include +#endif + +/** + * Note [hipblaslt handles] + * ~~~~~~~~~~~~~~~~~~~~~~~~ + * The cublas documentation states: + * cuBLAS handle (cublasHandle_t) encapsulates a cuBLASLt handle. + * Any valid cublasHandle_t can be used in place of cublasLtHandle_t with a simple cast. + * + * hipblaslt does not behave in this way. + * A hipblas handle does not encapsulate a hipblaslt handle. + * + * To work around this difference in behavior, a separate handle pool is available for ROCm builds. + * For CUDA builds, getCurrentCUDABlasLtHandle will alias for getCurrentCUDABlasHandle, + * whereas for ROCm builds, it is a distinct function. + * + * Additionally, hipblaslt cannot share a single handle across multiple streams. + * On ROCm, getCurrentCUDABlasLtHandle returns a handle unique to each (device, stream) + * pair, rather than just per-device like the cublas handle pool. + * + * The workspace pools are separate for ROCm. On CUDA, the env var + * TORCH_CUBLASLT_UNIFIED_WORKSPACE can be used to opt-in to unifying the workspace pools. + */ + +namespace at::cuda { + +namespace { +// -1 means no override; use env var / default +std::atomic cublas_workspace_override{-1}; +std::atomic cublaslt_workspace_override{-1}; +} // namespace + +namespace { + +#if defined(USE_ROCM) +void createCublasLtHandle(cublasLtHandle_t *handle) { + TORCH_CUDABLAS_CHECK(cublasLtCreate(handle)); +} + +void destroyCublasLtHandle(cublasLtHandle_t handle) { +// this is because of something dumb in the ordering of +// destruction. Sometimes atexit, the cuda context (or something) +// would already be destroyed by the time this gets destroyed. It +// happens in fbcode setting. @colesbury and @soumith decided to not destroy +// the handle as a workaround. +// - Comments of @soumith copied from cuDNN handle pool implementation +#ifdef NO_CUDNN_DESTROY_HANDLE +#else + cublasLtDestroy(handle); +#endif +} + +using CuBlasLtPoolType = DeviceThreadHandlePool; + +// ugly hack until hipblasSetWorkspace exists +static hipblasStatus_t rocBLASStatusToHIPStatus(rocblas_status error) { + switch(error) { + case rocblas_status_size_unchanged: + case rocblas_status_size_increased: + case rocblas_status_success: + return HIPBLAS_STATUS_SUCCESS; + case rocblas_status_invalid_handle: + return HIPBLAS_STATUS_NOT_INITIALIZED; + case rocblas_status_not_implemented: + return HIPBLAS_STATUS_NOT_SUPPORTED; + case rocblas_status_invalid_pointer: + case rocblas_status_invalid_size: + case rocblas_status_invalid_value: + return HIPBLAS_STATUS_INVALID_VALUE; + case rocblas_status_memory_error: + return HIPBLAS_STATUS_ALLOC_FAILED; + case rocblas_status_internal_error: + return HIPBLAS_STATUS_INTERNAL_ERROR; + } + TORCH_CHECK(false, "HIPBLAS_STATUS_INVALID_ENUM"); +} + +static hipblasStatus_t hipblasSetWorkspace_replacement(hipblasHandle_t handle, void* addr, size_t size) { + return rocBLASStatusToHIPStatus(rocblas_set_workspace((rocblas_handle)handle, addr, size)); +} + +// hipify mappings file correctly maps this but the function doesn't exist yet +#define hipblasSetWorkspace hipblasSetWorkspace_replacement + +#endif + +void createCublasHandle(cublasHandle_t *handle) { + TORCH_CUDABLAS_CHECK(cublasCreate(handle)); +} + +void destroyCublasHandle(cublasHandle_t handle) { +// this is because of something dumb in the ordering of +// destruction. Sometimes atexit, the cuda context (or something) +// would already be destroyed by the time this gets destroyed. It +// happens in fbcode setting. @colesbury and @soumith decided to not destroy +// the handle as a workaround. +// - Comments of @soumith copied from cuDNN handle pool implementation +#ifdef NO_CUDNN_DESTROY_HANDLE +#else + cublasDestroy(handle); +#endif +} + +using CuBlasPoolType = DeviceThreadHandlePool; + +} // namespace + +WorkspaceMapWithMutex& cublas_handle_stream_to_workspace() { + static auto& instance = *new WorkspaceMapWithMutex; + return instance; +} + +WorkspaceMapWithMutex& cublaslt_handle_stream_to_workspace() { + static auto& instance = *new WorkspaceMapWithMutex; + return instance; +} + +void clearCublasWorkspaces() { + { + auto& workspace = cublas_handle_stream_to_workspace(); + std::unique_lock lock(workspace.mutex); + workspace.map.clear(); + } + { + auto& workspace = cublaslt_handle_stream_to_workspace(); + std::unique_lock lock(workspace.mutex); + workspace.map.clear(); + } +} + +void clearCublasWorkspacesForStream(cudaStream_t stream) { + void* stream_ptr = static_cast(stream); + { + auto& workspace = cublas_handle_stream_to_workspace(); + std::unique_lock lock(workspace.mutex); + std::erase_if(workspace.map, [stream_ptr](const auto& entry) { + return std::get<1>(entry.first) == stream_ptr; + }); + } + { + auto& workspace = cublaslt_handle_stream_to_workspace(); + std::unique_lock lock(workspace.mutex); + std::erase_if(workspace.map, [stream_ptr](const auto& entry) { + return std::get<1>(entry.first) == stream_ptr; + }); + } +} + +size_t parseChosenWorkspaceSize() { + auto val = c10::utils::get_env("CUBLAS_WORKSPACE_CONFIG"); +#ifdef USE_ROCM + if (!val) { + val = c10::utils::get_env("HIPBLAS_WORKSPACE_CONFIG"); + } + if (!val) { + // for extra convenience + val = c10::utils::get_env("ROCBLAS_WORKSPACE_CONFIG"); + } + /* 32MiB default, 128MiB for gfx94x/gfx95x */ + const bool gfx94_95 = at::detail::getCUDAHooks().isGPUArch({"gfx94", "gfx95"}); + const size_t default_size = gfx94_95 ? 1024 * 128 * 1024 : 1024 * 32 * 1024; +#else + /* :4096:2:16:8 default, 32MiB for Hopper and Blackwell */ + cudaDeviceProp* properties = at::cuda::getCurrentDeviceProperties(); + const bool use32mb = properties != nullptr && (properties->major == 9 || properties->major == 10 || properties->major == 12); + const size_t default_size = use32mb ? 4096 * 8 * 1024 : 4096 * 1024 * 2 + 16 * 1024 * 8; +#endif + + if (val) { + size_t total_size = 0; + const std::string& config(val.value()); + std::regex exp(":([0-9]+):([0-9]+)"); + std::sregex_iterator next(config.begin(), config.end(), exp); + std::sregex_iterator end; + if (next == end) { + TORCH_WARN("Could not parse CUBLAS_WORKSPACE_CONFIG, using default workspace size of ", default_size, " bytes."); + return default_size; + } + while (next != end) { + std::smatch match = *next; + TORCH_CHECK(match.size() == 3, "Expected CUBLAS_WORKSPACE_SPACE_CONFIG match of size 3 (Format :SIZE:COUNT)"); + size_t curr_size = std::stoull(match.str(1)); + size_t count = std::stoull(match.str(2)); + total_size += curr_size * 1024 * count; + next++; + } + return total_size; + } else { + return default_size; + } +} + +#define TORCH_CUBLASLT_UNIFIED_WORKSPACE "TORCH_CUBLASLT_UNIFIED_WORKSPACE" +#ifndef USE_ROCM +inline bool unified_cublas_and_lt_workspaces() { + static auto unified_env_var = c10::utils::check_env(TORCH_CUBLASLT_UNIFIED_WORKSPACE); +#if !defined(FBCODE) + static bool unified = (unified_env_var == std::nullopt) || (unified_env_var == true); +#else + static bool unified = unified_env_var == true; +#endif + return unified; +} +#endif + +size_t parseCUDABlasLtWorkspaceSize() { + auto val = c10::utils::get_env("CUBLASLT_WORKSPACE_SIZE"); +#ifdef USE_ROCM + if (!val.has_value()) { + // accept either env var + val = c10::utils::get_env("HIPBLASLT_WORKSPACE_SIZE"); + } + size_t workspace_size = 76*1024; /* Use 76 MB for hipBLASLt */ +#else + size_t workspace_size = 1024; /* default size in KiB according to #73328 */ +#endif + + if (val.has_value()) { + try { + workspace_size = std::stoi(val.value()); + } catch (std::invalid_argument const&) { + TORCH_WARN( + "invalid CUBLASLT_WORKSPACE_SIZE,", + " using default workspace size of ", + workspace_size, + " KiB."); + } catch (std::out_of_range const&) { + TORCH_WARN( + "CUBLASLT_WORKSPACE_SIZE out of range,", + " using default workspace size of ", + workspace_size, + " KiB."); + } + } + return workspace_size * 1024; +} + +size_t getChosenWorkspaceSize() { + int64_t ov = cublas_workspace_override.load(std::memory_order_relaxed); + if (ov >= 0) { + return static_cast(ov); + } + static size_t pool_size = parseChosenWorkspaceSize(); + return pool_size; +} + +void setChosenWorkspaceSize(size_t size) { + cublas_workspace_override.store(static_cast(size), std::memory_order_relaxed); +} + +void setCUDABlasLtWorkspaceSize(size_t size) { + cublaslt_workspace_override.store(static_cast(size), std::memory_order_relaxed); +} + +void resetChosenWorkspaceSize() { + cublas_workspace_override.store(-1, std::memory_order_relaxed); +} + +void resetCUDABlasLtWorkspaceSize() { + cublaslt_workspace_override.store(-1, std::memory_order_relaxed); +} + +size_t getCUDABlasLtWorkspaceSize() { + int64_t ov = cublaslt_workspace_override.load(std::memory_order_relaxed); + const size_t pool_size = [&] { + if (ov >= 0) { + return static_cast(ov); + } + static size_t parsed_pool_size = parseCUDABlasLtWorkspaceSize(); + return parsed_pool_size; + }(); +#ifndef USE_ROCM + if (unified_cublas_and_lt_workspaces()) { + size_t cublasWorkspaceSize = getChosenWorkspaceSize(); + if (cublasWorkspaceSize < pool_size) { + TORCH_WARN_ONCE("Requested unified CUBLASLT workspace size of ", pool_size, + " bytes exceeds CUBLAS workspace size of ", cublasWorkspaceSize, + " bytes. Please increase CUBLAS workspace size", + " via CUBLAS_WORKSPACE_CONFIG or decrease requested" + " CUBLASLT_WORKSPACE_SIZE. Otherwise CUBLASLT workspace" + " size will be limited to the CUBLAS workspace size."); + return cublasWorkspaceSize; + } + } +#endif + return pool_size; +} + +at::DataPtr getNewWorkspace() { + return c10::cuda::CUDACachingAllocator::get()->allocate(getChosenWorkspaceSize()); +} + +at::DataPtr getNewCUDABlasLtWorkspace() { + return c10::cuda::CUDACachingAllocator::get()->allocate(getCUDABlasLtWorkspaceSize()); +} + +void setWorkspaceForHandle(cublasHandle_t handle, c10::cuda::CUDAStream stream) { + cudaStream_t _stream = stream; + auto key = std::make_tuple(static_cast(handle), static_cast(_stream)); + + auto& workspace = cublas_handle_stream_to_workspace(); + + size_t workspace_size = getChosenWorkspaceSize(); + + // Fast path: check if workspace already exists and is large enough + { + std::shared_lock lock(workspace.mutex); + auto workspace_it = workspace.map.find(key); + if (workspace_it != workspace.map.end() && workspace_it->second.second >= workspace_size) { + TORCH_CUDABLAS_CHECK(cublasSetWorkspace( + handle, workspace_it->second.first.get(), workspace_size)); + return; + } + } + + // Slow path: allocate workspace outside the lock + auto new_workspace = getNewWorkspace(); + + // Insert with lock, replacing any undersized entry + { + std::unique_lock lock(workspace.mutex); + workspace.map.insert_or_assign(key, std::make_pair(std::move(new_workspace), workspace_size)); + auto workspace_it = workspace.map.find(key); + TORCH_CUDABLAS_CHECK( + cublasSetWorkspace(handle, workspace_it->second.first.get(), workspace_size)); + } +} + +void* getCUDABlasLtWorkspace() { +#ifndef USE_ROCM + if (unified_cublas_and_lt_workspaces()) { + cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(/*setup=*/false); + auto stream = c10::cuda::getCurrentCUDAStream(); + cudaStream_t _stream = stream; + auto key = std::make_tuple(static_cast(handle), static_cast(_stream)); + auto& workspace = at::cuda::cublas_handle_stream_to_workspace(); + { + std::shared_lock lock(workspace.mutex); + auto workspace_it = workspace.map.find(key); + if (workspace_it != workspace.map.end()) { + return workspace_it->second.first.mutable_get(); + } + } + // First use for this handle+stream pair — allocate and insert directly. + // No need to call cublasSetWorkspace; Lt passes workspace explicitly. + auto new_workspace = getNewWorkspace(); + { + std::unique_lock lock(workspace.mutex); + auto workspace_it = workspace.map.try_emplace(key, std::make_pair(std::move(new_workspace), getChosenWorkspaceSize())).first; + return workspace_it->second.first.mutable_get(); + } + } +#endif + cublasLtHandle_t handle = getCurrentCUDABlasLtHandle(); + auto stream = c10::cuda::getCurrentCUDAStream(); + cudaStream_t _stream = stream; + auto key = std::make_tuple(static_cast(handle), static_cast(_stream)); + + auto& workspace = cublaslt_handle_stream_to_workspace(); + + size_t workspace_size = getCUDABlasLtWorkspaceSize(); + + // Fast path: check if workspace already exists and is large enough + { + std::shared_lock lock(workspace.mutex); + auto workspace_it = workspace.map.find(key); + if (workspace_it != workspace.map.end() && workspace_it->second.second >= workspace_size) { + return workspace_it->second.first.mutable_get(); + } + } + + // Slow path: allocate workspace outside the lock + auto new_workspace = getNewCUDABlasLtWorkspace(); + + // Insert with lock, replacing any undersized entry + { + std::unique_lock lock(workspace.mutex); + workspace.map.insert_or_assign(key, std::make_pair(std::move(new_workspace), workspace_size)); + auto workspace_it = workspace.map.find(key); + return workspace_it->second.first.mutable_get(); + } +} + +cublasHandle_t getCurrentCUDABlasHandle(bool setup) { + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + +#if !defined(USE_ROCM) + CUcontext pctx = nullptr; + at::globalContext().getNVRTC().cuCtxGetCurrent(&pctx); + if (C10_UNLIKELY(!pctx)) { + TORCH_WARN_ONCE("Attempting to run cuBLAS, but there was no current CUDA context! Attempting to set the primary context..."); + at::globalContext().getNVRTC().cuDevicePrimaryCtxRetain(&pctx, device); + at::globalContext().getNVRTC().cuCtxSetCurrent(pctx); + } +#endif + + // Thread local PoolWindows are lazily-initialized + // to avoid initialization issues that caused hangs on Windows. + // See: https://github.com/pytorch/pytorch/pull/22405 + // This thread local unique_ptrs will be destroyed when the thread terminates, + // releasing its reserved handles back to the pool. + + // Use a leaky singleton for the pool following standard practice around + // singletons: https://isocpp.org/wiki/faq/ctors#construct-on-first-use-v2 + static auto pool = std::shared_ptr( + new CuBlasPoolType(), [](CuBlasPoolType* p) { + // Leak the memory. + }); + thread_local std::unique_ptr myPoolWindow( + pool->newPoolWindow()); + + auto handle = myPoolWindow->reserve(device); + + if (!setup) { + return handle; + } + + auto stream = c10::cuda::getCurrentCUDAStream(); + TORCH_CUDABLAS_CHECK(cublasSetStream(handle, stream)); + // We explicitly set the cublas workspace even though CUDA 12.2+ fixed the + // issue where memory usage increased during graph capture. + // original issue: https://github.com/pytorch/pytorch/pull/83461 + // This is because in CUDA 12.2+, the use of cudaMallocAsync in cublas + // will allocate memory dynamically (even if they're cheap) outside + // PyTorch's CUDA caching allocator. It's possible that CCA used up + // all the memory and cublas's cudaMallocAsync will return OOM + setWorkspaceForHandle(handle, stream); + +#if !defined(USE_ROCM) + // On CUDA >= 11, and architecture >= Ampere, cuBLAS can use TF32 to speedup + // FP32 data type calculations based on the value of the allow_tf32 flag. + // To enable TF32, set the math mode of the handle to CUBLAS_TF32_TENSOR_OP_MATH. + if (!NoTF32Guard::should_disable_tf32() && + at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) == at::Float32Precision::TF32) { + TORCH_CUDABLAS_CHECK(cublasSetMathMode(handle, CUBLAS_TF32_TENSOR_OP_MATH)); + } else { + TORCH_CUDABLAS_CHECK(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); + } +#else + hipblasAtomicsMode_t hipblas_mode; + if (at::globalContext().deterministicAlgorithms()) { + hipblas_mode = HIPBLAS_ATOMICS_NOT_ALLOWED; + } else { + hipblas_mode = HIPBLAS_ATOMICS_ALLOWED; + } + TORCH_CUDABLAS_CHECK(hipblasSetAtomicsMode(handle, hipblas_mode)); +#endif + return handle; +} + +cublasLtHandle_t getCurrentCUDABlasLtHandle() { +#ifdef USE_ROCM + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + + // Thread local PoolWindows are lazily-initialized + // to avoid initialization issues that caused hangs on Windows. + // See: https://github.com/pytorch/pytorch/pull/22405 + // This thread local unique_ptrs will be destroyed when the thread terminates, + // releasing its reserved handles back to the pool. + + // Use a leaky singleton for the pool following standard practice around + // singletons: https://isocpp.org/wiki/faq/ctors#construct-on-first-use-v2 + static auto pool = std::shared_ptr( + new CuBlasLtPoolType(), [](CuBlasLtPoolType* p) { + // Leak the memory. + }); + thread_local std::unique_ptr myPoolWindow( + pool->newPoolWindow()); + + // hipblaslt cannot share a single handle across multiple streams, + // so reserve a handle unique to each (device, stream) pair. + auto stream = c10::cuda::getCurrentCUDAStream(); + cudaStream_t _stream = stream; + auto handle = myPoolWindow->reserve(device, static_cast(_stream)); + return handle; +#else + return reinterpret_cast(getCurrentCUDABlasHandle(/*setup=*/false)); +#endif +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/DeviceUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/DeviceUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..55cf2d9e1f4248576f5c3ea618f07baf4f6a50b8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/DeviceUtils.cuh @@ -0,0 +1,121 @@ +#pragma once + +#include +#include +#include + +__device__ __forceinline__ unsigned int ACTIVE_MASK() +{ +#if !defined(USE_ROCM) + return __activemask(); +#else +// will be ignored anyway + return 0xffffffff; +#endif +} + +__device__ __forceinline__ void WARP_SYNC(unsigned mask = 0xffffffff) { +#if !defined(USE_ROCM) + return __syncwarp(mask); +#endif +} + +#if defined(USE_ROCM) +__device__ __forceinline__ unsigned long long int WARP_BALLOT(int predicate) +{ +return __ballot(predicate); +} +#else +__device__ __forceinline__ unsigned int WARP_BALLOT(int predicate, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __ballot_sync(mask, predicate); +#else + return __ballot(predicate); +#endif +} +#endif + +template +__device__ __forceinline__ T WARP_SHFL_XOR(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_xor_sync(mask, value, laneMask, width); +#else + return __shfl_xor(value, laneMask, width); +#endif +} + +template +__device__ __forceinline__ T WARP_SHFL(T value, int srcLane, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_sync(mask, value, srcLane, width); +#else + return __shfl(value, srcLane, width); +#endif +} + +template +__device__ __forceinline__ T WARP_SHFL_UP(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_up_sync(mask, value, delta, width); +#else + return __shfl_up(value, delta, width); +#endif +} + +template +__device__ __forceinline__ T WARP_SHFL_DOWN(T value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return __shfl_down_sync(mask, value, delta, width); +#else + return __shfl_down(value, delta, width); +#endif +} + +#if defined(USE_ROCM) +template<> +__device__ __forceinline__ int64_t WARP_SHFL_DOWN(int64_t value, unsigned int delta, int width , unsigned int mask) +{ + //(HIP doesn't support int64_t). Trick from https://devblogs.nvidia.com/faster-parallel-reductions-kepler/ + int2 a = *reinterpret_cast(&value); + a.x = __shfl_down(a.x, delta); + a.y = __shfl_down(a.y, delta); + return *reinterpret_cast(&a); +} +#endif + +template<> +__device__ __forceinline__ c10::Half WARP_SHFL_DOWN(c10::Half value, unsigned int delta, int width, unsigned int mask) +{ + return c10::Half(WARP_SHFL_DOWN(value.x, delta, width, mask), c10::Half::from_bits_t{}); +} + +template +__device__ __forceinline__ c10::complex WARP_SHFL_DOWN(c10::complex value, unsigned int delta, int width = warpSize, unsigned int mask = 0xffffffff) +{ +#if !defined(USE_ROCM) + return c10::complex( + __shfl_down_sync(mask, value.real_, delta, width), + __shfl_down_sync(mask, value.imag_, delta, width)); +#else + return c10::complex( + __shfl_down(value.real_, delta, width), + __shfl_down(value.imag_, delta, width)); +#endif +} + +/** + * For CC 3.5+, perform a load using __ldg + */ +template +__device__ __forceinline__ T doLdg(const T* p) { +#if !defined(USE_ROCM) + return __ldg(p); +#else + return *p; +#endif +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/EmptyTensor.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/EmptyTensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ddc5a1e2462526836a4a0717465313b593b112c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/EmptyTensor.cpp @@ -0,0 +1,94 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::detail { + +TensorBase empty_cuda( + IntArrayRef size, + ScalarType dtype, + std::optional device_opt, + std::optional memory_format_opt) { + at::globalContext().lazyInitDevice(c10::DeviceType::CUDA); + const auto device = device_or_default(device_opt); + TORCH_INTERNAL_ASSERT(device.is_cuda()); + const DeviceGuard device_guard(device); + auto* allocator = at::cuda::getCUDADeviceAllocator(); + constexpr c10::DispatchKeySet cuda_dks(c10::DispatchKey::CUDA); + return at::detail::empty_generic( + size, allocator, cuda_dks, dtype, memory_format_opt); +} + +TensorBase empty_cuda( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt) { + TORCH_CHECK(!pin_memory_opt.has_value() || !*pin_memory_opt, "Only dense CPU tensors can be pinned"); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout_or_default(layout_opt) == Layout::Strided); + + const auto dtype = dtype_or_default(dtype_opt); + return at::detail::empty_cuda(size, dtype, device_opt, memory_format_opt); +} + +TensorBase empty_cuda( + IntArrayRef size, const TensorOptions &options) { + return at::detail::empty_cuda( + size, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt(), + options.memory_format_opt()); +} + +TensorBase empty_strided_cuda( + IntArrayRef size, + IntArrayRef stride, + ScalarType dtype, + std::optional device_opt) { + at::globalContext().lazyInitDevice(c10::DeviceType::CUDA); + const auto device = device_or_default(device_opt); + TORCH_INTERNAL_ASSERT(device.is_cuda()); + const DeviceGuard device_guard(device); + auto* allocator = at::cuda::getCUDADeviceAllocator(); + constexpr c10::DispatchKeySet cuda_dks(c10::DispatchKey::CUDA); + return at::detail::empty_strided_generic( + size, stride, allocator, cuda_dks, dtype); +} + +TensorBase empty_strided_cuda( + IntArrayRef size, + IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt) { + TORCH_CHECK(!pin_memory_opt.has_value() || !*pin_memory_opt, "Only dense CPU tensors can be pinned"); +#ifndef NDEBUG + // TODO: remove check for jagged, see https://github.com/pytorch/pytorch/issues/130073 + const auto layout = layout_or_default(layout_opt); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(layout == Layout::Strided || layout == Layout::Jagged); +#endif + + const auto dtype = dtype_or_default(dtype_opt); + return at::detail::empty_strided_cuda(size, stride, dtype, device_opt); +} + +TensorBase empty_strided_cuda( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions &options) { + return at::detail::empty_strided_cuda( + size, + stride, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt()); +} + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/EmptyTensor.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/EmptyTensor.h new file mode 100644 index 0000000000000000000000000000000000000000..ba70c1f8f6a30ea40f4f71d93bb99b7b8e4d401e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/EmptyTensor.h @@ -0,0 +1,44 @@ +#pragma once +#include + +namespace at::detail { + +TORCH_CUDA_CPP_API TensorBase empty_cuda( + IntArrayRef size, + ScalarType dtype, + std::optional device_opt, + std::optional memory_format_opt); + +TORCH_CUDA_CPP_API TensorBase empty_cuda( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt); + +TORCH_CUDA_CPP_API TensorBase empty_cuda( + IntArrayRef size, + const TensorOptions &options); + +TORCH_CUDA_CPP_API TensorBase empty_strided_cuda( + IntArrayRef size, + IntArrayRef stride, + ScalarType dtype, + std::optional device_opt); + +TORCH_CUDA_CPP_API TensorBase empty_strided_cuda( + IntArrayRef size, + IntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt); + +TORCH_CUDA_CPP_API TensorBase empty_strided_cuda( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions &options); + + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/Exceptions.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/Exceptions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..397893ad6dcf5b78c9e08bc193624bb5554165c5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/Exceptions.cpp @@ -0,0 +1,106 @@ +//NS: CUDACachingAllocator must be included before to get CUDART_VERSION definedi + +#include + +namespace at::cuda { +namespace blas { + +C10_EXPORT const char* _cublasGetErrorEnum(cublasStatus_t error) { + if (error == CUBLAS_STATUS_SUCCESS) { + return "CUBLAS_STATUS_SUCCESS"; + } + if (error == CUBLAS_STATUS_NOT_INITIALIZED) { + return "CUBLAS_STATUS_NOT_INITIALIZED"; + } + if (error == CUBLAS_STATUS_ALLOC_FAILED) { + return "CUBLAS_STATUS_ALLOC_FAILED"; + } + if (error == CUBLAS_STATUS_INVALID_VALUE) { + return "CUBLAS_STATUS_INVALID_VALUE"; + } + if (error == CUBLAS_STATUS_ARCH_MISMATCH) { + return "CUBLAS_STATUS_ARCH_MISMATCH"; + } + if (error == CUBLAS_STATUS_MAPPING_ERROR) { + return "CUBLAS_STATUS_MAPPING_ERROR"; + } + if (error == CUBLAS_STATUS_EXECUTION_FAILED) { + return "CUBLAS_STATUS_EXECUTION_FAILED"; + } + if (error == CUBLAS_STATUS_INTERNAL_ERROR) { + return "CUBLAS_STATUS_INTERNAL_ERROR"; + } + if (error == CUBLAS_STATUS_NOT_SUPPORTED) { + return "CUBLAS_STATUS_NOT_SUPPORTED"; + } +#ifdef CUBLAS_STATUS_LICENSE_ERROR + if (error == CUBLAS_STATUS_LICENSE_ERROR) { + return "CUBLAS_STATUS_LICENSE_ERROR"; + } +#endif + return ""; +} + +} // namespace blas + +namespace solver { +#if !defined(USE_ROCM) + +C10_EXPORT const char* cusolverGetErrorMessage(cusolverStatus_t status) { + switch (status) { + case CUSOLVER_STATUS_SUCCESS: return "CUSOLVER_STATUS_SUCCESS"; + case CUSOLVER_STATUS_NOT_INITIALIZED: return "CUSOLVER_STATUS_NOT_INITIALIZED"; + case CUSOLVER_STATUS_ALLOC_FAILED: return "CUSOLVER_STATUS_ALLOC_FAILED"; + case CUSOLVER_STATUS_INVALID_VALUE: return "CUSOLVER_STATUS_INVALID_VALUE"; + case CUSOLVER_STATUS_ARCH_MISMATCH: return "CUSOLVER_STATUS_ARCH_MISMATCH"; + case CUSOLVER_STATUS_EXECUTION_FAILED: return "CUSOLVER_STATUS_EXECUTION_FAILED"; + case CUSOLVER_STATUS_INTERNAL_ERROR: return "CUSOLVER_STATUS_INTERNAL_ERROR"; + case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: return "CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED"; + default: return "Unknown cusolver error number"; + } +} + +#else + +C10_EXPORT const char* hipsolverGetErrorMessage(hipsolverStatus_t status) { + switch (status) { + case HIPSOLVER_STATUS_SUCCESS: return "HIPSOLVER_STATUS_SUCCESS"; + case HIPSOLVER_STATUS_NOT_INITIALIZED: return "HIPSOLVER_STATUS_NOT_INITIALIZED"; + case HIPSOLVER_STATUS_ALLOC_FAILED: return "HIPSOLVER_STATUS_ALLOC_FAILED"; + case HIPSOLVER_STATUS_INVALID_VALUE: return "HIPSOLVER_STATUS_INVALID_VALUE"; + case HIPSOLVER_STATUS_MAPPING_ERROR: return "HIPSOLVER_STATUS_MAPPING_ERROR"; + case HIPSOLVER_STATUS_EXECUTION_FAILED: return "HIPSOLVER_STATUS_EXECUTION_FAILED"; + case HIPSOLVER_STATUS_INTERNAL_ERROR: return "HIPSOLVER_STATUS_INTERNAL_ERROR"; + case HIPSOLVER_STATUS_NOT_SUPPORTED: return "HIPSOLVER_STATUS_NOT_SUPPORTED"; + case HIPSOLVER_STATUS_ARCH_MISMATCH: return "HIPSOLVER_STATUS_ARCH_MISMATCH"; + case HIPSOLVER_STATUS_HANDLE_IS_NULLPTR: return "HIPSOLVER_STATUS_HANDLE_IS_NULLPTR"; + case HIPSOLVER_STATUS_INVALID_ENUM: return "HIPSOLVER_STATUS_INVALID_ENUM"; + case HIPSOLVER_STATUS_UNKNOWN: return "HIPSOLVER_STATUS_UNKNOWN"; + case HIPSOLVER_STATUS_ZERO_PIVOT: return "HIPSOLVER_STATUS_ZERO_PIVOT"; + default: return "Unknown hipsolver error number"; + } +} + +#endif +} // namespace solver + +#if defined(USE_CUDSS) +namespace cudss { + +C10_EXPORT const char* cudssGetErrorMessage(cudssStatus_t status) { + switch (status) { + case CUDSS_STATUS_SUCCESS: return "CUDSS_STATUS_SUCCESS"; + case CUDSS_STATUS_NOT_INITIALIZED: return "CUDSS_STATUS_NOT_INITIALIZED"; + case CUDSS_STATUS_ALLOC_FAILED: return "CUDSS_STATUS_ALLOC_FAILED"; + case CUDSS_STATUS_INVALID_VALUE: return "CUDSS_STATUS_INVALID_VALUE"; + case CUDSS_STATUS_NOT_SUPPORTED: return "CUDSS_STATUS_NOT_SUPPORTED"; + case CUDSS_STATUS_EXECUTION_FAILED: return "CUDSS_STATUS_EXECUTION_FAILED"; + case CUDSS_STATUS_INTERNAL_ERROR: return "CUDSS_STATUS_INTERNAL_ERROR"; + default: return "Unknown cudss error number"; + } +} + +} // namespace cudss +#endif + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/Exceptions.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/Exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..c23d21a7e02dfba1e68d85a80add078f97757980 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/Exceptions.h @@ -0,0 +1,228 @@ +#pragma once + +#include +#include +#include + +#if !defined(USE_ROCM) +#include +#else +#include +#endif + +#if defined(USE_CUDSS) +#include +#endif + +#include +#include +#include + + +namespace c10 { + +class CuDNNError : public c10::Error { + using Error::Error; +}; + +} // namespace c10 + +#define AT_CUDNN_FRONTEND_CHECK(EXPR, ...) \ + do { \ + auto error_object = EXPR; \ + if (!error_object.is_good()) { \ + TORCH_CHECK_WITH(CuDNNError, false, \ + "cuDNN Frontend error: ", error_object.get_message()); \ + } \ + } while (0) \ + +#define AT_CUDNN_CHECK_WITH_SHAPES(EXPR, ...) AT_CUDNN_CHECK(EXPR, "\n", ##__VA_ARGS__) + +// See Note [CHECK macro] +#define AT_CUDNN_CHECK(EXPR, ...) \ + do { \ + cudnnStatus_t status = EXPR; \ + if (status != CUDNN_STATUS_SUCCESS) { \ + if (status == CUDNN_STATUS_NOT_SUPPORTED) { \ + TORCH_CHECK_WITH(CuDNNError, false, \ + "cuDNN error: ", \ + cudnnGetErrorString(status), \ + ". This error may appear if you passed in a non-contiguous input.", ##__VA_ARGS__); \ + } else { \ + TORCH_CHECK_WITH(CuDNNError, false, \ + "cuDNN error: ", cudnnGetErrorString(status), ##__VA_ARGS__); \ + } \ + } \ + } while (0) + +namespace at::cuda::blas { +C10_EXPORT const char* _cublasGetErrorEnum(cublasStatus_t error); +} // namespace at::cuda::blas + +#define TORCH_CUDABLAS_CHECK(EXPR) \ + do { \ + cublasStatus_t __err = EXPR; \ + TORCH_CHECK(__err == CUBLAS_STATUS_SUCCESS, \ + "CUDA error: ", \ + at::cuda::blas::_cublasGetErrorEnum(__err), \ + " when calling `" #EXPR "`"); \ + } while (0) + +#define TORCH_CUDASPARSE_CHECK(EXPR) \ + do { \ + cusparseStatus_t __err = EXPR; \ + TORCH_CHECK(__err == CUSPARSE_STATUS_SUCCESS, \ + "CUDA error: ", \ + cusparseGetErrorString(__err), \ + " when calling `" #EXPR "`"); \ + } while (0) + +#if defined(USE_CUDSS) +namespace at::cuda::cudss { +C10_EXPORT const char* cudssGetErrorMessage(cudssStatus_t error); +} // namespace at::cuda::solver + +#define TORCH_CUDSS_CHECK(EXPR) \ + do { \ + cudssStatus_t __err = EXPR; \ + if (__err == CUDSS_STATUS_EXECUTION_FAILED) { \ + TORCH_CHECK_LINALG( \ + false, \ + "cudss error: ", \ + at::cuda::cudss::cudssGetErrorMessage(__err), \ + ", when calling `" #EXPR "`", \ + ". This error may appear if the input matrix contains NaN. ");\ + } else { \ + TORCH_CHECK( \ + __err == CUDSS_STATUS_SUCCESS, \ + "cudss error: ", \ + at::cuda::cudss::cudssGetErrorMessage(__err), \ + ", when calling `" #EXPR "`. "); \ + } \ + } while (0) +#else +#define TORCH_CUDSS_CHECK(EXPR) EXPR +#endif + +namespace at::cuda::solver { +#if !defined(USE_ROCM) + +C10_EXPORT const char* cusolverGetErrorMessage(cusolverStatus_t status); + +constexpr const char* _cusolver_backend_suggestion = \ + "If you keep seeing this error, you may use " \ + "`torch.backends.cuda.preferred_linalg_library()` to try " \ + "linear algebra operators with other supported backends. " \ + "See https://pytorch.org/docs/stable/backends.html#torch.backends.cuda.preferred_linalg_library"; + +// When cuda >= 11.5, cusolver normally finishes execution and sets info array indicating convergence issue. +#define TORCH_CUSOLVER_CHECK(EXPR) \ + do { \ + cusolverStatus_t __err = EXPR; \ + if (__err == CUSOLVER_STATUS_INVALID_VALUE) { \ + TORCH_CHECK_LINALG( \ + false, \ + "cusolver error: ", \ + at::cuda::solver::cusolverGetErrorMessage(__err), \ + ", when calling `" #EXPR "`", \ + ". This error may appear if the input matrix contains NaN. ", \ + at::cuda::solver::_cusolver_backend_suggestion); \ + } else { \ + TORCH_CHECK( \ + __err == CUSOLVER_STATUS_SUCCESS, \ + "cusolver error: ", \ + at::cuda::solver::cusolverGetErrorMessage(__err), \ + ", when calling `" #EXPR "`. ", \ + at::cuda::solver::_cusolver_backend_suggestion); \ + } \ + } while (0) + +#else // defined(USE_ROCM) + +C10_EXPORT const char* hipsolverGetErrorMessage(hipsolverStatus_t status); + +constexpr const char* _hipsolver_backend_suggestion = \ + "If you keep seeing this error, you may use " \ + "`torch.backends.cuda.preferred_linalg_library()` to try " \ + "linear algebra operators with other supported backends. " \ + "See https://pytorch.org/docs/stable/backends.html#torch.backends.cuda.preferred_linalg_library"; + +#define TORCH_CUSOLVER_CHECK(EXPR) \ + do { \ + hipsolverStatus_t __err = EXPR; \ + if (__err == HIPSOLVER_STATUS_INVALID_VALUE) { \ + TORCH_CHECK_LINALG( \ + false, \ + "hipsolver error: ", \ + at::cuda::solver::hipsolverGetErrorMessage(__err), \ + ", when calling `" #EXPR "`", \ + ". This error may appear if the input matrix contains NaN. ", \ + at::cuda::solver::_hipsolver_backend_suggestion); \ + } else { \ + TORCH_CHECK( \ + __err == HIPSOLVER_STATUS_SUCCESS, \ + "hipsolver error: ", \ + at::cuda::solver::hipsolverGetErrorMessage(__err), \ + ", when calling `" #EXPR "`. ", \ + at::cuda::solver::_hipsolver_backend_suggestion); \ + } \ + } while (0) +#endif +} // namespace at::cuda::solver + +#define AT_CUDA_CHECK(EXPR) C10_CUDA_CHECK(EXPR) + +// For CUDA Driver API +// +// This is here instead of in c10 because NVRTC is loaded dynamically via a stub +// in ATen, and we need to use its nvrtcGetErrorString. +// See NOTE [ USE OF NVRTC AND DRIVER API ]. +#if !defined(USE_ROCM) + +#define AT_CUDA_DRIVER_CHECK(EXPR) \ + do { \ + CUresult __err = EXPR; \ + if (__err != CUDA_SUCCESS) { \ + const char* err_str; \ + [[maybe_unused]] CUresult get_error_str_err = \ + at::globalContext().getNVRTC().cuGetErrorString(__err, &err_str); \ + if (get_error_str_err != CUDA_SUCCESS) { \ + TORCH_CHECK(false, "CUDA driver error: unknown error"); \ + } else { \ + TORCH_CHECK(false, "CUDA driver error: ", err_str); \ + } \ + } \ + } while (0) + +#else + +#define AT_CUDA_DRIVER_CHECK(EXPR) \ + do { \ + CUresult __err = EXPR; \ + if (__err != CUDA_SUCCESS) { \ + TORCH_CHECK(false, "CUDA driver error: ", static_cast(__err)); \ + } \ + } while (0) + +#endif + +// For CUDA NVRTC +// +// Note: As of CUDA 10, nvrtc error code 7, NVRTC_ERROR_BUILTIN_OPERATION_FAILURE, +// incorrectly produces the error string "NVRTC unknown error." +// The following maps it correctly. +// +// This is here instead of in c10 because NVRTC is loaded dynamically via a stub +// in ATen, and we need to use its nvrtcGetErrorString. +// See NOTE [ USE OF NVRTC AND DRIVER API ]. +#define AT_CUDA_NVRTC_CHECK(EXPR) \ + do { \ + nvrtcResult __err = EXPR; \ + if (__err != NVRTC_SUCCESS) { \ + if (static_cast(__err) != 7) { \ + TORCH_CHECK(false, "CUDA NVRTC error: ", at::globalContext().getNVRTC().nvrtcGetErrorString(__err)); \ + } else { \ + TORCH_CHECK(false, "CUDA NVRTC error: NVRTC_ERROR_BUILTIN_OPERATION_FAILURE"); \ + } \ + } \ + } while (0) diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/MemPool.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/MemPool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4995936860e656d8c24481364893f02cddc5061a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/MemPool.cpp @@ -0,0 +1,70 @@ +#include + +namespace at::cuda { + +// uid_ is incremented when a user creates a MemPool, +// for example: using graph_pool_handle() or c10::cuda::MemPool(). +// +// uuid_ is incremented when CUDAGraph creates a MemPool +// as a result of a user not providing a pool. +// +// MempoolId_t of {0, 0} is used to denote when no MemPool has been +// passed to a function, either by user or CUDAGraphs. For example, +// default value of MempoolId_t for capture_begin function is {0, 0}. +// That's why uid_ and uuid_ start at 1. +std::atomic MemPool::uid_{1}; +std::atomic MemPool::uuid_{1}; + +MemPool::MemPool( + std::shared_ptr allocator, + bool is_user_created, + bool use_on_oom, + bool no_split) + : is_user_created_(is_user_created) { + if (is_user_created_) { + id_ = {0, uid_++}; + } else { + id_ = {uuid_++, 0}; + } + device_ = c10::cuda::current_device(); + CUDACachingAllocator::createOrIncrefPool( + device_, id_, std::move(allocator)); + if (use_on_oom) { + CUDACachingAllocator::setUseOnOOM(device_, id_, true); + } + if (no_split) { + CUDACachingAllocator::setNoSplit(device_, id_); + } +} + +MemPool::~MemPool() { + // TORCH_INTERNAL_ASSERT(use_count() == 1); + // We used to assert that TORCH_INTERNAL_ASSERT(use_count() == 1); + // However, this assertion is not true if a memory pool is shared + // with a cuda graph. That CUDAGraph will increase the use count + // until it is reset. + CUDACachingAllocator::setUseOnOOM(device_, id_, false); + CUDACachingAllocator::releasePool(device_, id_); + c10::cuda::CUDACachingAllocator::emptyCache(id_); +} + +MempoolId_t MemPool::id() { + return id_; +} + +int MemPool::use_count() { + return CUDACachingAllocator::getPoolUseCount(device_, id_); +} + +c10::DeviceIndex MemPool::device() { + return device_; +} + +MempoolId_t MemPool::graph_pool_handle(bool is_user_created) { + if (is_user_created) { + return {0, uid_++}; + } + return {uuid_++, 0}; +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/MemPool.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/MemPool.h new file mode 100644 index 0000000000000000000000000000000000000000..e2f827c4591b8a77fd440a3db4dab1301724a92d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/MemPool.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +#include + +namespace at::cuda { + +// Keep BC only +using c10::CaptureId_t; +using c10::MempoolId_t; + +// MemPool represents a pool of memory in a caching allocator. Currently, +// it's just the ID of the pool object maintained in the CUDACachingAllocator. +// +// An allocator pointer can be passed to the MemPool to define how the +// allocations should be done in the pool. For example: using a different +// system allocator such as ncclMemAlloc. +struct TORCH_CUDA_CPP_API MemPool { + MemPool( + std::shared_ptr allocator = + nullptr, + bool is_user_created = true, + bool use_on_oom = false, + bool no_split = false); + MemPool(const MemPool&) = delete; + MemPool(MemPool&&) = default; + MemPool& operator=(const MemPool&) = delete; + MemPool& operator=(MemPool&&) = default; + ~MemPool(); + + MempoolId_t id(); + int use_count(); + c10::DeviceIndex device(); + static MempoolId_t graph_pool_handle(bool is_user_created = true); + + private: + static std::atomic uid_; + static std::atomic uuid_; + bool is_user_created_; + MempoolId_t id_; + c10::DeviceIndex device_; +}; + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/NumericLimits.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/NumericLimits.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f88ec7e1ff2d05c2573e06267cc3cba978924ef3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/NumericLimits.cuh @@ -0,0 +1,46 @@ +#pragma once + +#include + +// at::numeric_limits is a historical artifact which was needed for ROCm HIP +// because std::numeric_limits functions are not marked __device__ and did not +// work with ROCm. This is no longer the case according to the discussion on +// #50902 and #52058. +// +// This header cannot be removed because lower_bound/upper_bound functions are +// not present in std::numeric_limits. +// +// The lower_bound and upper_bound constants are same as lowest and max for +// integral types, but are -inf and +inf for floating point types. They are +// useful in implementing min, max, etc. + +namespace at { + +template +struct numeric_limits { + static inline __host__ __device__ T lowest() { + return std::numeric_limits::lowest(); + } + + static inline __host__ __device__ T max() { + return std::numeric_limits::max(); + } + + static inline __host__ __device__ T lower_bound() { + if constexpr (std::numeric_limits::has_infinity) { + return -std::numeric_limits::infinity(); + } else { + return std::numeric_limits::lowest(); + } + } + + static inline __host__ __device__ T upper_bound() { + if constexpr (std::numeric_limits::has_infinity) { + return std::numeric_limits::infinity(); + } else { + return std::numeric_limits::max(); + } + } +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/PeerToPeerAccess.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/PeerToPeerAccess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5012217645d89b7834a59ca4d3e22b5a06c903af --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/PeerToPeerAccess.cpp @@ -0,0 +1,20 @@ +#include + +#include +#include + +namespace at::cuda { + +bool get_p2p_access(c10::DeviceIndex dev, c10::DeviceIndex dev_to_access) { + // Ensure CUDA is lazily initialized before forwarding to c10 + at::globalContext().lazyInitDevice(c10::DeviceType::CUDA); + return c10::cuda::get_p2p_access(dev, dev_to_access); +} + +bool get_fabric_access(c10::DeviceIndex dev) { + // Ensure CUDA is lazily initialized before forwarding to c10 + at::globalContext().lazyInitDevice(c10::DeviceType::CUDA); + return c10::cuda::get_fabric_access(dev); +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/PeerToPeerAccess.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/PeerToPeerAccess.h new file mode 100644 index 0000000000000000000000000000000000000000..c9eecf65bc7f27bcbeeba3bbbd3c3bdb4471cb0d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/PeerToPeerAccess.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include + +#include + +namespace at::cuda { + +namespace detail { + +/// Initialize the peer-to-peer and fabric access caches. +/// Forwards to c10::cuda::detail::init_p2p_access_cache. +/// @param num_devices The number of CUDA devices in the system. +inline void init_p2p_access_cache(int64_t num_devices) { + c10::cuda::detail::init_p2p_access_cache(num_devices); +} + +} // namespace detail + +/// Query if peer-to-peer access is available between two devices. +/// This wrapper ensures CUDA lazy initialization before forwarding to c10. +/// @param source_dev The source device index. +/// @param dest_dev The destination device index. +/// @return true if P2P access is available, false otherwise. +TORCH_CUDA_CPP_API bool get_p2p_access( + c10::DeviceIndex source_dev, + c10::DeviceIndex dest_dev); + +/// Query if GPU fabric (high-speed interconnect) is available for a device. +/// This wrapper ensures CUDA lazy initialization before forwarding to c10. +/// @param device The device index to check. +/// @return true if fabric access is available, false otherwise. +TORCH_CUDA_CPP_API bool get_fabric_access(c10::DeviceIndex device); + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/PhiloxCudaState.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/PhiloxCudaState.h new file mode 100644 index 0000000000000000000000000000000000000000..257ac6bbb896ab2883e7e85011ddee1426f53d15 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/PhiloxCudaState.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/PhiloxUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/PhiloxUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ea072eaed3bf2e5615d27349f9768b60b4e435d8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/PhiloxUtils.cuh @@ -0,0 +1,5 @@ +#pragma once + +#include +#include +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/PinnedMemoryAllocator.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/PinnedMemoryAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..4f539c6dab9960832cdbcc736270e0f81f27573f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/PinnedMemoryAllocator.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace at::cuda { + +inline TORCH_CUDA_CPP_API at::HostAllocator* getPinnedMemoryAllocator() { + return at::getHostAllocator(at::kCUDA); +} +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/ScanUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/ScanUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..f81f560b4b523f8bc81423183cbbccca9c9d45e2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/ScanUtils.cuh @@ -0,0 +1,78 @@ +#pragma once + +#include +#include +#include +#include + +// Collection of in-kernel scan / prefix sum utilities + +namespace at::cuda { + +// Inclusive prefix sum for binary vars using intra-warp voting + +// shared memory +template +__device__ void inclusiveBinaryPrefixScan(T* smem, bool in, T* out, BinaryFunction binop) { + // Within-warp, we use warp voting. +#if defined (USE_ROCM) + unsigned long long int vote = WARP_BALLOT(in); + T index = __popcll(getLaneMaskLe() & vote); + T carry = __popcll(vote); +#else + T vote = WARP_BALLOT(in); + T index = __popc(getLaneMaskLe() & vote); + T carry = __popc(vote); +#endif + + int warp = threadIdx.x / C10_WARP_SIZE; + + // Per each warp, write out a value + if (getLaneId() == 0) { + smem[warp] = carry; + } + + __syncthreads(); + + // Sum across warps in one thread. This appears to be faster than a + // warp shuffle scan for CC 3.0+ + if (threadIdx.x == 0) { + int current = 0; + for (int i = 0; i < blockDim.x / C10_WARP_SIZE; ++i) { + T v = smem[i]; + smem[i] = binop(smem[i], current); + current = binop(current, v); + } + } + + __syncthreads(); + + // load the carry from the preceding warp + if (warp >= 1) { + index = binop(index, smem[warp - 1]); + } + + *out = index; + + if (KillWARDependency) { + __syncthreads(); + } +} + +// Exclusive prefix sum for binary vars using intra-warp voting + +// shared memory +template +__device__ void exclusiveBinaryPrefixScan(T* smem, bool in, T* out, T* carry, BinaryFunction binop) { + inclusiveBinaryPrefixScan(smem, in, out, binop); + + // Inclusive to exclusive + *out -= (T) in; + + // The outgoing carry for all threads is the last warp's sum + *carry = smem[at::ceil_div(blockDim.x, C10_WARP_SIZE) - 1]; + + if (KillWARDependency) { + __syncthreads(); + } +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/Sleep.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/Sleep.cu new file mode 100644 index 0000000000000000000000000000000000000000..020c3f0afea56bd2723068538d8310b510845b36 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/Sleep.cu @@ -0,0 +1,69 @@ +#include +#include + +#include +#include + +namespace at::cuda { +namespace { +__global__ void spin_kernel(int64_t cycles) { + // Few AMD specific GPUs have different clock intrinsic +#if defined(__GFX11__) && defined(USE_ROCM) && !defined(__CUDA_ARCH__) + int64_t start_clock = wall_clock64(); +#else + // see concurrentKernels CUDA sampl + int64_t start_clock = clock64(); +#endif + int64_t clock_offset = 0; + while (clock_offset < cycles) + { +#if defined(__GFX11__) && defined(USE_ROCM) && !defined(__CUDA_ARCH__) + clock_offset = wall_clock64() - start_clock; +#else + clock_offset = clock64() - start_clock; +#endif + } +} +} + +void sleep(int64_t cycles) { + dim3 grid(1); + dim3 block(1); + spin_kernel<<>>(cycles); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +#ifdef USE_ROCM +__global__ void flush_icache_kernel() +{ + asm __volatile__("s_icache_inv \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" + "s_nop 0 \n\t" :: + :); +} +#endif + +void flush_icache() { +#ifdef USE_ROCM + dim3 grid(at::cuda::getCurrentDeviceProperties()->multiProcessorCount * 60); + dim3 block(64); + flush_icache_kernel<<>>(); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +#endif +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/Sleep.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/Sleep.h new file mode 100644 index 0000000000000000000000000000000000000000..2ce5941af8390e17d15d060b5e1bfe94936969a1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/Sleep.h @@ -0,0 +1,13 @@ +#pragma once +#include +#include + +namespace at::cuda { + +// enqueues a kernel that spins for the specified number of cycles +TORCH_CUDA_CU_API void sleep(int64_t cycles); + +// flushes instruction cache for ROCm; no-op for CUDA +TORCH_CUDA_CU_API void flush_icache(); + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/StatelessPhilox4x32.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/StatelessPhilox4x32.cuh new file mode 100644 index 0000000000000000000000000000000000000000..6788ff6bdd46fd24b8901ea83858cfd8c60aef10 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/StatelessPhilox4x32.cuh @@ -0,0 +1,61 @@ +// Stateless Philox-4x32 PRNG implementation. +// +// Unlike PhiloxRNGEngine (PhiloxUtils.cuh), this is a pure function: given +// (seed, offset) it returns 4 pseudo-random uint32 values with no mutable +// state. This makes it suitable for use in stateless random APIs. +// +// The Philox-4x32 cipher operates on a 128-bit counter. The full counter +// is (offset_lo, offset_hi, subsequence_lo, subsequence_hi), but we fix +// subsequence=0 so that the entire 128-bit counter space is addressed by +// the 64-bit offset alone. This keeps the API simple and maintains +// cross-device consistency. For example, utilizing thread ID-based subsequence +// numbers and SM-based thread count causes different random values to +// be generated across GPU types. We avoid this situation by always setting +// subsequence=0. + +#pragma once + +#include + +namespace at::cuda { + +__device__ __forceinline__ uint2 mulhilo32(uint32_t a, uint32_t b) { + return {a * b, __umulhi(a, b)}; +} + +__device__ __forceinline__ uint4 philox_round(uint4 ctr, uint2 key) { + constexpr uint32_t kPhiloxSA = 0xD2511F53; + constexpr uint32_t kPhiloxSB = 0xCD9E8D57; + uint2 r0 = mulhilo32(kPhiloxSA, ctr.x); + uint2 r1 = mulhilo32(kPhiloxSB, ctr.z); + return {r1.y ^ ctr.y ^ key.x, r1.x, r0.y ^ ctr.w ^ key.y, r0.x}; +} + +// Stateless Philox-4x32. Returns 4 pseudo-random uint32 values (128 bits) +// determined entirely by (seed, offset). Each unique offset produces a +// distinct 128-bit output. +template +__device__ __forceinline__ uint4 philox_4x32( + uint64_t seed, uint64_t offset) { + uint2 key = { + static_cast(seed), + static_cast(seed >> 32)}; + uint4 ctr = { + static_cast(offset), + static_cast(offset >> 32), + // restrict subsequence=0 + 0, 0}; + + constexpr uint32_t kPhilox10A = 0x9E3779B9; + constexpr uint32_t kPhilox10B = 0xBB67AE85; + + #pragma unroll + for (int i = 0; i < N_ROUNDS - 1; i++) { + ctr = philox_round(ctr, key); + key.x += kPhilox10A; + key.y += kPhilox10B; + } + return philox_round(ctr, key); +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/ThrustAllocator.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/ThrustAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..e7f56bd455e5a71bef001908cd55f0e40a45f6ad --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/ThrustAllocator.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +namespace at::cuda { + +/// Allocator for Thrust to re-route its internal device allocations +/// to the THC allocator +class ThrustAllocator { +public: + typedef char value_type; + + char* allocate(std::ptrdiff_t size) { + return static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(size)); + } + + void deallocate(char* p, size_t size) { + c10::cuda::CUDACachingAllocator::raw_delete(p); + } +}; + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortKeys.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortKeys.cu new file mode 100644 index 0000000000000000000000000000000000000000..fdab804d96aea45bc0297457b5c41147f06c0f0d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortKeys.cu @@ -0,0 +1,58 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include + +namespace at::cuda::cub { + +template +void radix_sort_keys( + const key_t* keys_in, + key_t* keys_out, + int64_t n, + bool descending, + int64_t begin_bit, + int64_t end_bit) { + TORCH_CHECK( + n <= std::numeric_limits::max(), + "cub sort does not support sorting more than INT_MAX elements"); + using key_t_ = typename detail::cuda_type::type; + + const key_t_* keys_in_ = reinterpret_cast(keys_in); + key_t_* keys_out_ = reinterpret_cast(keys_out); + + if (descending) { + CUB_WRAPPER( + NO_ROCM(at_cuda_detail)::cub::DeviceRadixSort::SortKeysDescending, + keys_in_, + keys_out_, + n, + begin_bit, + end_bit, + c10::cuda::getCurrentCUDAStream()); + } else { + CUB_WRAPPER( + NO_ROCM(at_cuda_detail)::cub::DeviceRadixSort::SortKeys, + keys_in_, + keys_out_, + n, + begin_bit, + end_bit, + c10::cuda::getCurrentCUDAStream()); + } +} + +#define AT_INSTATIATE_CUB_TEMPLATES(scalar_t, ScalarType) \ + template void radix_sort_keys( \ + const scalar_t* keys_in, \ + scalar_t* keys_out, \ + int64_t n, \ + bool descending, \ + int64_t begin_bit, \ + int64_t end_bit); + +AT_FORALL_SCALAR_TYPES_AND3(Bool, BFloat16, Half, AT_INSTATIATE_CUB_TEMPLATES) +AT_INSTATIATE_CUB_TEMPLATES(uint16_t, UInt16) +AT_INSTATIATE_CUB_TEMPLATES(uint32_t, UInt32) +AT_INSTATIATE_CUB_TEMPLATES(uint64_t, UInt64) + +} // namespace at::cuda::cub diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-f16-8.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-f16-8.cu new file mode 100644 index 0000000000000000000000000000000000000000..bb465fa845aa295deafc6045743c9c71c2743353 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-f16-8.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(c10::BFloat16, 8) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-1.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-1.cu new file mode 100644 index 0000000000000000000000000000000000000000..cba0df3ece3cae66af442dcea5cb5813c18d050a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-1.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(int32_t, 1) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-2.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-2.cu new file mode 100644 index 0000000000000000000000000000000000000000..7f1bcfb1e2c464b470f193eb7d0ed9a3a401aee5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-2.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(int32_t, 2) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-4.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-4.cu new file mode 100644 index 0000000000000000000000000000000000000000..70c1754c041b1d7ed5e24b00cd078703822acc5f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int32-4.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(int32_t, 4) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-1.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-1.cu new file mode 100644 index 0000000000000000000000000000000000000000..79270914c411a9a03bd5c6a0b96a957bb6b883fd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-1.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(int64_t, 1) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-2.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-2.cu new file mode 100644 index 0000000000000000000000000000000000000000..d6e87db70f0c9758754ec612e2374f0a9800639b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-2.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(int64_t, 2) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-4.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-4.cu new file mode 100644 index 0000000000000000000000000000000000000000..eba425453b1413bf9f348b485bc0a78d7acf572b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-int64-4.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(int64_t, 4) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-scalars.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-scalars.cu new file mode 100644 index 0000000000000000000000000000000000000000..af874c1a640af631bfefea9942c30ddb587e9908 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-scalars.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_FORALL_SCALAR_TYPES_AND2(Bool, Half, AT_INSTANTIATE_SORT_PAIRS_8) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint16-8.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint16-8.cu new file mode 100644 index 0000000000000000000000000000000000000000..35a1930dbdb866c2ccfd05516c68514249cc9b72 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint16-8.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(uint16_t, 8) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint32-8.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint32-8.cu new file mode 100644 index 0000000000000000000000000000000000000000..9497c7c4072f6f088b69f08c8d7cdc4964ef63f6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint32-8.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(uint32_t, 8) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint64-8.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint64-8.cu new file mode 100644 index 0000000000000000000000000000000000000000..47929dd98ecb4e1e1daf8208e70b4f07c6bc1bda --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs-uint64-8.cu @@ -0,0 +1,7 @@ +#include + +namespace at::cuda::cub::detail { + +AT_INSTANTIATE_SORT_PAIRS(uint64_t, 8) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs.cuh new file mode 100644 index 0000000000000000000000000000000000000000..bfe9c4a708ba10ad3d6c52813ea480914e2b77d1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub-RadixSortPairs.cuh @@ -0,0 +1,74 @@ +#pragma once + +#define TORCH_ASSERT_NO_OPERATORS +#include +#include + +namespace at::cuda::cub::detail { + +template +void radix_sort_pairs_impl( + const key_t* keys_in, + key_t* keys_out, + const OpaqueType* values_in, + OpaqueType* values_out, + int64_t n, + bool descending, + int64_t begin_bit, + int64_t end_bit) { + TORCH_CHECK( + n <= std::numeric_limits::max(), + "cub sort does not support sorting more than INT_MAX elements"); + using key_t_ = typename detail::cuda_type::type; + + auto allocator = c10::cuda::CUDACachingAllocator::get(); + c10::DataPtr keys_out_owner; + + if (keys_out == nullptr) { + keys_out_owner = allocator->allocate(n * sizeof(key_t)); + keys_out = reinterpret_cast(keys_out_owner.get()); + } + + const key_t_* keys_in_ = reinterpret_cast(keys_in); + key_t_* keys_out_ = reinterpret_cast(keys_out); + + if (descending) { + CUB_WRAPPER( + NO_ROCM(at_cuda_detail)::cub::DeviceRadixSort::SortPairsDescending, + keys_in_, + keys_out_, + values_in, + values_out, + n, + begin_bit, + end_bit, + c10::cuda::getCurrentCUDAStream()); + } else { + CUB_WRAPPER( + NO_ROCM(at_cuda_detail)::cub::DeviceRadixSort::SortPairs, + keys_in_, + keys_out_, + values_in, + values_out, + n, + begin_bit, + end_bit, + c10::cuda::getCurrentCUDAStream()); + } +} + +#define AT_INSTANTIATE_SORT_PAIRS(key_t, value_size) \ + template void radix_sort_pairs_impl( \ + const key_t* keys_in, \ + key_t* keys_out, \ + const OpaqueType* values_in, \ + OpaqueType* values_out, \ + int64_t n, \ + bool descending, \ + int64_t begin_bit, \ + int64_t end_bit); + +#define AT_INSTANTIATE_SORT_PAIRS_8(scalar_t, ScalarType) \ + AT_INSTANTIATE_SORT_PAIRS(scalar_t, 8) + +} // namespace at::cuda::cub::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.cu new file mode 100644 index 0000000000000000000000000000000000000000..bb93dbd2c89eb44ce7bfbb2b06bfeb17c2c7e69d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.cu @@ -0,0 +1,48 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include + +namespace at::cuda::cub { + +namespace { +template +struct SumOp { + __device__ scalar_t operator () (scalar_t a, scalar_t b) const { + return a + b; + } +}; +} + +template +void inclusive_sum_truncating(const input_t *input, output_t *output, int64_t num_items) { + inclusive_scan(input, output, NO_ROCM(::cuda)::std::plus<>{}, num_items); +} + +template void inclusive_sum_truncating(const int32_t *input, int32_t *output, int64_t num_items); +template void inclusive_sum_truncating(const int64_t *input, int64_t *output, int64_t num_items); +template void inclusive_sum_truncating(const int32_t *input, int64_t *output, int64_t num_items); + +template +void exclusive_sum_in_common_type(const input_t *input, output_t *output, int64_t num_items) { + using scalar_t = std::common_type_t; + exclusive_scan(input, output, SumOp{}, scalar_t(0), num_items); +} + +template void exclusive_sum_in_common_type(const int32_t *input, int32_t *output, int64_t num_items); +template void exclusive_sum_in_common_type(const int64_t *input, int64_t *output, int64_t num_items); + +namespace { +struct CountMaskOp { + __device__ int64_t operator() (const uint8_t &x) const { + return x != 0; + } +}; +} + +void mask_exclusive_sum(const uint8_t *mask, int64_t *output_idx, int64_t n) { + CountMaskOp op{}; + auto iter = ATEN_CUB_TRANSFORM_ITERATOR(bool, decltype(op), decltype(mask))(mask, op); + exclusive_scan(iter, output_idx, SumOp{}, int64_t{0}, n); +} + +} // namespace at::cuda::cub diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.cuh new file mode 100644 index 0000000000000000000000000000000000000000..4335e286b4a836e76873f5b969a12195fb3ece52 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.cuh @@ -0,0 +1,583 @@ +#pragma once +#include + +#include +#include +#include +#include + +#ifndef USE_ROCM +#include +#endif + +#include +#include + +#include + +#include +#include +#include + +// handle the temporary storage and 'twice' calls for cub API +#define CUB_WRAPPER(func, ...) do { \ + size_t temp_storage_bytes = 0; \ + AT_CUDA_CHECK(func(nullptr, temp_storage_bytes, __VA_ARGS__)); \ + auto& caching_allocator = *::c10::cuda::CUDACachingAllocator::get(); \ + auto temp_storage = caching_allocator.allocate(temp_storage_bytes); \ + AT_CUDA_CHECK(func(temp_storage.get(), temp_storage_bytes, __VA_ARGS__));\ +} while (false) + +#ifdef USE_ROCM +#define NO_ROCM(x) +#define ROCM_HIPCUB(x) ::hipcub +#else +#define NO_ROCM(x) x +#define ROCM_HIPCUB(x) x +#endif + +#if CUB_V3_4_PLUS() +#include +#include +#include +#define ATEN_CUB_TRANSFORM_ITERATOR(ValueType, ...) ::cuda::transform_iterator<__VA_ARGS__> +#define ATEN_CUB_COUNTING_ITERATOR(...) ::cuda::counting_iterator<__VA_ARGS__> +#define ATEN_CUB_CONSTANT_ITERATOR(...) ::cuda::constant_iterator<__VA_ARGS__> +#define ATEN_CUB_MAXIMUM() ::cuda::maximum<>() +template +using cccl_constant_iterator = ::cuda::constant_iterator; +template +using cccl_counting_iterator = ::cuda::counting_iterator; +using cccl_discard_iterator = ::cuda::discard_iterator; +template +auto cccl_make_reverse_iterator(Iter it) { return ::cuda::std::make_reverse_iterator(it); } +#elif CUB_V3_PLUS() +#include +#include +#include +#include +#include +#define ATEN_CUB_TRANSFORM_ITERATOR(ValueType, ...) ::thrust::transform_iterator<__VA_ARGS__> +#define ATEN_CUB_COUNTING_ITERATOR(...) ::thrust::counting_iterator<__VA_ARGS__> +#define ATEN_CUB_CONSTANT_ITERATOR(...) ::thrust::constant_iterator<__VA_ARGS__> +#define ATEN_CUB_MAXIMUM() ::cuda::maximum<>() +template +using cccl_constant_iterator = ::thrust::constant_iterator; +template +using cccl_counting_iterator = ::thrust::counting_iterator; +using cccl_discard_iterator = ::thrust::discard_iterator<>; +template +auto cccl_make_reverse_iterator(Iter it) { return ::thrust::make_reverse_iterator(it); } +#else +#include +#include +#include +#include +#include +#define ATEN_CUB_TRANSFORM_ITERATOR(...) NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::TransformInputIterator<__VA_ARGS__> +#define ATEN_CUB_COUNTING_ITERATOR(...) NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::CountingInputIterator<__VA_ARGS__> +#define ATEN_CUB_CONSTANT_ITERATOR(...) NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::ConstantInputIterator<__VA_ARGS__> +#define ATEN_CUB_MAXIMUM() NO_ROCM(at_cuda_detail)ROCM_HIPCUB(::cub)::Max() +template +using cccl_constant_iterator = ::thrust::constant_iterator; +template +using cccl_counting_iterator = ::thrust::counting_iterator; +using cccl_discard_iterator = ::thrust::discard_iterator<>; +template +auto cccl_make_reverse_iterator(Iter it) { return ::thrust::make_reverse_iterator(it); } +#endif + +#if defined(USE_ROCM) + +// backport https://github.com/NVIDIA/cub/pull/306 for c10::BFloat16 + +template <> +struct ROCM_HIPCUB(cub)::FpLimits +{ + static __host__ __device__ __forceinline__ c10::BFloat16 Max() { + unsigned short max_word = 0x7F7F; + return reinterpret_cast(max_word); + } + + static __host__ __device__ __forceinline__ c10::BFloat16 Lowest() { + unsigned short lowest_word = 0xFF7F; + return reinterpret_cast(lowest_word); + } +}; + +template <> +struct ROCM_HIPCUB(cub)::NumericTraits: + ROCM_HIPCUB(cub)::BaseTraits {}; + +#endif + +#if !defined(USE_ROCM) +namespace at::native { +namespace cub = ::at_cuda_detail::cub; +} // namespace at::native +#endif + +namespace at::cuda::cub { + +namespace detail { + +template +struct cuda_type { + using type = T; +}; +template<> +struct cuda_type { + using type = __half; +}; + +#if !defined(USE_ROCM) + +template<> +struct cuda_type { + using type = __nv_bfloat16; +}; + +#elif defined(USE_ROCM) + +template<> +struct cuda_type { + using type = hip_bfloat16; +}; + +#endif + +} // namespace detail + +template +inline void segmented_sort_pairs( + const key_t *keys_in, key_t *keys_out, + const value_t *values_in, value_t *values_out, + int64_t num_elements, int64_t num_segments, + OffsetIteratorT begin_offsets, OffsetIteratorT end_offsets, + bool descending=false, int64_t begin_bit=0, int64_t end_bit=sizeof(key_t)*8 +) { + TORCH_CHECK(num_elements <= std::numeric_limits::max(), + "cub sort does not support sorting more than INT_MAX elements"); + TORCH_CHECK(num_segments <= std::numeric_limits::max(), + "cub sort does not support sorting more than INT_MAX elements"); + using key_t_ = typename detail::cuda_type::type; + + auto allocator = c10::cuda::CUDACachingAllocator::get(); + c10::DataPtr keys_out_owner; + + if (keys_out == nullptr) { + keys_out_owner = allocator->allocate(num_elements * sizeof(key_t)); + keys_out = reinterpret_cast(keys_out_owner.get()); + } + + const key_t_ *keys_in_ = reinterpret_cast(keys_in); + key_t_ *keys_out_ = reinterpret_cast(keys_out); + + if (descending) { + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSegmentedRadixSort::SortPairsDescending, + keys_in_, keys_out_, values_in, values_out, + num_elements, num_segments, begin_offsets, end_offsets, + begin_bit, end_bit, c10::cuda::getCurrentCUDAStream()); + } else { + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSegmentedRadixSort::SortPairs, + keys_in_, keys_out_, values_in, values_out, + num_elements, num_segments, begin_offsets, end_offsets, + begin_bit, end_bit, c10::cuda::getCurrentCUDAStream()); + } +} + +template +inline void unique_by_key( + KeysInputIteratorT keys_in, ValuesInputIteratorT values_in, + ValuesOutputIteratorT values_out, + NumSelectedIteratorT num_selected, int64_t num_input_items) +{ + // TODO: use thrust::discard_iterator to handle null keys_out when https://github.com/NVIDIA/cub/issues/406 is fixed. + using KeyT = typename std::iterator_traits::value_type; + auto allocator = c10::cuda::CUDACachingAllocator::get(); + c10::DataPtr keys_out_owner; + keys_out_owner = allocator->allocate(num_input_items * sizeof(KeyT)); + auto keys_out_ = static_cast(keys_out_owner.get()); + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSelect::UniqueByKey, + keys_in, values_in, keys_out_, values_out, num_selected, num_input_items, c10::cuda::getCurrentCUDAStream()); +} + +namespace impl { + +template +C10_LAUNCH_BOUNDS_1(1) +__global__ void transform_vals(InputIteratorT1 a, InputIteratorT2 b, OutputIteratorT out, ScanOpT scan_op){ + // NOTE: out here not the final scan output, but an intermediate of the accumulation type. + using acc_t = typename std::iterator_traits::value_type; + *out = scan_op(static_cast(*a), static_cast(*b)); +} + +// even though cub is supposed to support tensors with int_max elements, in reality it doesn't, +// so split at int_max/2 +constexpr int max_cub_size = std::numeric_limits::max() / 2 + 1; // 2**30 +} + +// non synchronizing cub call +// even though cub is supposed to support tensors with int_max elements, in reality it doesn't, +// so split at int_max/2 +template +inline void inclusive_scan(InputIteratorT input, OutputIteratorT output, ScanOpT scan_op, int64_t num_items) { +#if defined(USE_ROCM) + //For ROCm, use hipCUB chained iterators + CUB_WRAPPER(NO_ROCM(detail)::hipcub::DeviceScan::InclusiveScan, + input, + output, + scan_op, + num_items, + at::cuda::getCurrentCUDAStream()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +#else + // non synchronizing cub call + // even though cub is supposed to support tensors with int_max elements, in reality it doesn't, + // so split at int_max/2 + int size_cub = std::min(num_items, max_cub_size); + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::InclusiveScan, + input, + output, + scan_op, + size_cub, + at::cuda::getCurrentCUDAStream()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + using input_t = typename std::iterator_traits::value_type; + for (int64_t i = max_cub_size; i < num_items; i += max_cub_size) { + auto allocator = c10::cuda::CUDACachingAllocator::get(); + c10::DataPtr first_elem = allocator->allocate(sizeof(input_t)); + auto first_elem_ptr = reinterpret_cast(first_elem.get()); + + size_cub = std::min(num_items - i, max_cub_size); + impl::transform_vals<<<1, 1, 0, at::cuda::getCurrentCUDAStream()>>>( + output + i - 1, + input + i, + first_elem_ptr, + scan_op); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::ExclusiveScan, + input + i + 1, + output + i, + scan_op, + ::at_cuda_detail::cub::FutureValue(first_elem_ptr), + size_cub, + at::cuda::getCurrentCUDAStream()); + } +#endif +} + +template +struct BlockPrefixCallbackOp +{ + public: + T running_total; + + __host__ __device__ BlockPrefixCallbackOp(T running_total) : running_total(running_total) {} + + // Callback operator to be entered by the first warp of threads in the block. + // Thread-0 is responsible for returning a value for seeding the block-wide scan. + __host__ __device__ T operator()(T block_aggregate) + { + T old_prefix = running_total; + running_total += block_aggregate; + return old_prefix; + } +}; + +template +__global__ void final_scan_kernel(const T* d_in, T* d_out, T* agg, int64_t nelem, int iters_per_cta) { + int64_t offset = BLOCK_THREADS * ITEMS_PER_THREAD * iters_per_cta * (int64_t)blockIdx.x; + int64_t remaining = nelem - offset; + if (remaining <= 0) { + return; + } + + d_in += offset; + d_out += offset; + + using BlockLoadT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockLoad; + + // Specialize BlockStore type for our thread block (uses warp-striped loads for coalescing, then transposes in shared + // memory to a blocked arrangement) + using BlockStoreT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockStore; + + // Specialize BlockScan type for our thread block + using BlockScanT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockScan; + using BlockReduceT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockReduce; + + + // Shared memory + __shared__ union TempStorage + { + typename BlockLoadT::TempStorage load; + typename BlockStoreT::TempStorage store; + typename BlockScanT::TempStorage scan; + typename BlockReduceT::TempStorage reduce; + } temp_storage; + + // load agg and reduce my starting value + T agg_data; + agg_data = threadIdx.x >= blockIdx.x ? T(0) : agg[threadIdx.x]; + // In case there are fewer threads than previous block aggregates to be read, add more aggregates (should be at most 2-3 aggregates per thread) + for (unsigned int i=threadIdx.x + blockDim.x; i= BLOCK_THREADS * ITEMS_PER_THREAD) { + BlockLoadT(temp_storage.load).Load(d_in, data); + } else { + #pragma unroll + for (int j=0; j= BLOCK_THREADS * ITEMS_PER_THREAD) { + BlockStoreT(temp_storage.store).Store(d_out, data); + } else { + BlockStoreT(temp_storage.store).Store(d_out, data, remaining); + } + d_in += BLOCK_THREADS * ITEMS_PER_THREAD; + d_out += BLOCK_THREADS * ITEMS_PER_THREAD; + remaining -= BLOCK_THREADS * ITEMS_PER_THREAD; + if (remaining <= 0) return; + __syncthreads(); + } + +} + +template +struct TransformFunctor { + __device__ aggT operator()(T value) const { + if constexpr (!nonzero) { + return value; + } else { + return (value != T(0)) ? 1 : 0; + } + } +}; + +template +__global__ void calc_block_sums(const T * d_in, aggT * agg, int64_t nelem, int iters_per_cta){ + int64_t offset = BLOCK_THREADS * ITEMS_PER_THREAD * iters_per_cta * (int64_t)blockIdx.x; + int64_t remaining = nelem - offset; + if (remaining <= 0) { + return; + } + d_in += offset; + + using BlockLoadT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockLoad; + using BlockReduceT = ROCM_HIPCUB(at_cuda_detail::cub)::BlockReduce; + // Shared memory + __shared__ union TempStorage + { + typename BlockLoadT::TempStorage load; + typename BlockReduceT::TempStorage reduce; + } temp_storage; + aggT data[ITEMS_PER_THREAD]; + aggT agg_val = 0; + TransformFunctor transform_functor; + auto iter_in = ATEN_CUB_TRANSFORM_ITERATOR(aggT, TransformFunctor, const T*)(d_in, transform_functor); + for (int i=0; i= BLOCK_THREADS * ITEMS_PER_THREAD) { + BlockLoadT(temp_storage.load).Load(iter_in, data); + __syncthreads(); + agg_val += BlockReduceT(temp_storage.reduce).Sum(data); + + } else { + BlockLoadT(temp_storage.load).Load(iter_in, data, remaining, aggT(0)); + __syncthreads(); + agg_val += BlockReduceT(temp_storage.reduce).Sum(data); + } + iter_in += BLOCK_THREADS * ITEMS_PER_THREAD; + remaining -= BLOCK_THREADS * ITEMS_PER_THREAD; + if (remaining <= 0) { + // for nonzeros we need to write out last blocks + // accumulated value to be able to compute + // total number of nonzeros + if (nonzero && threadIdx.x == 0) { + agg[blockIdx.x] = agg_val; + } + return; + } + __syncthreads(); + + } + if (threadIdx.x == 0) { + agg[blockIdx.x] = agg_val; + } + +} + +template +struct NonZeroOp { + __host__ __device__ __forceinline__ int operator()(const T& a) const { + return (a != T(0)); + } +}; + +template +constexpr int block_threads(){ + if constexpr (size >=16) { + return 128; + } else if constexpr (size >=8) { + return 256; + } else { + return 512; + } +} + +template +inline void inclusive_deterministic_scan(const scalar_t * input, scalar_t * output, ScanOpT scan_op, int64_t num_items) { + static_assert(std::is_same_v>, ""); + constexpr int BLOCK_THREADS = block_threads(); + constexpr int ITEMS_PER_THREAD = 16; + auto grid_size = (num_items + BLOCK_THREADS * ITEMS_PER_THREAD - 1) / (BLOCK_THREADS * ITEMS_PER_THREAD); + const int64_t num_sms = at::cuda::getCurrentDeviceProperties()->multiProcessorCount; + + const int iters_per_cta = (grid_size + num_sms - 1)/num_sms; + grid_size = std::min(num_sms, grid_size); + auto& allocator = *c10::cuda::CUDACachingAllocator::get(); + auto agg = allocator.allocate(grid_size * sizeof(scalar_t)); + calc_block_sums + <<>>( + input, (scalar_t*)agg.get(), num_items, iters_per_cta); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + final_scan_kernel + <<>>( + input, output, (scalar_t*)agg.get(), num_items, iters_per_cta); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + + +template +inline void exclusive_scan(InputIteratorT input, OutputIteratorT output, ScanOpT scan_op, InitValueT init_value, int64_t num_items) { +#if defined(USE_ROCM) + //For ROCm, use hipCUB chained iterators + CUB_WRAPPER(NO_ROCM(detail)::hipcub::DeviceScan::ExclusiveScan, + input, + output, + scan_op, + init_value, + num_items, + at::cuda::getCurrentCUDAStream()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +#else + // non synchronizing cub call + // even though cub is supposed to support tensors with int_max elements, in reality it doesn't, + // so split at int_max/2 + int size_cub = std::min(num_items, max_cub_size); + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::ExclusiveScan, + input, + output, + scan_op, + init_value, + size_cub, + at::cuda::getCurrentCUDAStream()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + for (int64_t i = max_cub_size; i < num_items; i += max_cub_size) { + auto allocator = c10::cuda::CUDACachingAllocator::get(); + c10::DataPtr first_elem = allocator->allocate(sizeof(InitValueT)); + auto first_elem_ptr = reinterpret_cast(first_elem.get()); + + size_cub = std::min(num_items - i, max_cub_size); + impl::transform_vals<<<1, 1, 0, at::cuda::getCurrentCUDAStream()>>>( + output + i - 1, + input + i - 1, + first_elem_ptr, + scan_op); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceScan::ExclusiveScan, + input + i, + output + i, + scan_op, + ::at_cuda_detail::cub::FutureValue(first_elem_ptr), + size_cub, + at::cuda::getCurrentCUDAStream()); + } +#endif +} + + +template +inline void inclusive_sum_by_key(KeysInputIteratorT keys, ValuesInputIteratorT input, ValuesOutputIteratorT output, int64_t num_items) { + TORCH_CHECK(num_items <= std::numeric_limits::max(), + "cub InclusiveSumByKey does not support more than INT_MAX elements"); +#if !defined(USE_ROCM) + CUB_WRAPPER(at_cuda_detail::cub::DeviceScan::InclusiveSumByKey, + keys, input, output, num_items, NO_ROCM(::cuda)::std::equal_to<>(), at::cuda::getCurrentCUDAStream()); +#else + CUB_WRAPPER(cub::DeviceScan::InclusiveSumByKey, + keys, input, output, num_items, hipcub::Equality(), at::cuda::getCurrentCUDAStream()); +#endif +} + +template +inline void inclusive_scan_by_key(KeysInputIteratorT keys, ValuesInputIteratorT input, ValuesOutputIteratorT output, ScanOpT scan_op, int64_t num_items) { + TORCH_CHECK(num_items <= std::numeric_limits::max(), + "cub InclusiveSumByKey does not support more than INT_MAX elements"); +#if !defined(USE_ROCM) + CUB_WRAPPER(at_cuda_detail::cub::DeviceScan::InclusiveScanByKey, + keys, input, output, scan_op, num_items, NO_ROCM(::cuda)::std::equal_to<>(), at::cuda::getCurrentCUDAStream()); +#else + CUB_WRAPPER(cub::DeviceScan::InclusiveScanByKey, + keys, input, output, scan_op, num_items, hipcub::Equality(), at::cuda::getCurrentCUDAStream()); +#endif +} + + +template +void unique(InputIteratorT input, OutputIteratorT output, + NumSelectedIteratorT num_selected_out, int64_t num_items) { + TORCH_CHECK(num_items <= std::numeric_limits::max(), + "cub unique does not support more than INT_MAX elements"); + CUB_WRAPPER(NO_ROCM(at_cuda_detail)::cub::DeviceSelect::Unique, + input, output, num_selected_out, num_items, at::cuda::getCurrentCUDAStream()); +} + +template +void run_length_encode(InputIteratorT input, OutputIteratorT output, CountsOutputIteratorT counts_out, + LengthOutputIteratorT length_out, int64_t num_items) { + TORCH_CHECK(num_items <= std::numeric_limits::max(), + "cub run_length_encode does not support more than INT_MAX elements"); + CUB_WRAPPER( + NO_ROCM(at_cuda_detail)::cub::DeviceRunLengthEncode::Encode, + input, output, counts_out, length_out, num_items, + at::cuda::getCurrentCUDAStream()); +} + +template +void reduce(InputIteratorT input, OutputIteratorT output, int64_t num_items, ReductionOpT op, T init) { + TORCH_CHECK(num_items <= std::numeric_limits::max(), + "cub reduce does not support more than INT_MAX elements"); + CUB_WRAPPER( + NO_ROCM(at_cuda_detail)::cub::DeviceReduce::Reduce, + input, output, num_items, op, init, + at::cuda::getCurrentCUDAStream()); + +} + +} // namespace at::cuda::cub diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.h new file mode 100644 index 0000000000000000000000000000000000000000..1d34106b5d83c0f4794443f90ec98924fac42bd6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub.h @@ -0,0 +1,93 @@ +#pragma once +#include +#include +#include + +// NOTE: These templates are intentionally not defined in this header, +// which avoids re-compiling them for each translation unit. If you get +// a link error, you need to add an explicit instantiation for your +// types in cub.cu + +namespace at::cuda::cub { + +inline int get_num_bits(uint64_t max_key) { + int num_bits = 1; + while (max_key > 1) { + max_key >>= 1; + num_bits++; + } + return num_bits; +} + +namespace detail { + +// radix_sort_pairs doesn't interact with value_t other than to copy +// the data, so we can save template instantiations by reinterpreting +// it as an opaque type. +// We use native integer types for 1/2/4/8-byte values to reduce +// register usage in CUDA kernels. For sizes > 8 fall back to char array. +template struct alignas(N) OpaqueType { char data[N]; }; +template <> struct alignas(1) OpaqueType<1> { uint8_t data; }; +template <> struct alignas(2) OpaqueType<2> { uint16_t data; }; +template <> struct alignas(4) OpaqueType<4> { uint32_t data; }; +template <> struct alignas(8) OpaqueType<8> { uint64_t data; }; + +template +void radix_sort_pairs_impl( + const key_t *keys_in, key_t *keys_out, + const OpaqueType *values_in, OpaqueType *values_out, + int64_t n, bool descending, int64_t begin_bit, int64_t end_bit); + +} // namespace detail + +template +void radix_sort_pairs( + const key_t *keys_in, key_t *keys_out, + const value_t *values_in, value_t *values_out, + int64_t n, bool descending=false, int64_t begin_bit=0, int64_t end_bit=sizeof(key_t)*8) { + static_assert(std::is_trivially_copyable_v || + AT_ROCM_ENABLED(), // ROCm incorrectly fails this check for vector types + "radix_sort_pairs value type must be trivially copyable"); + // Make value type opaque, so all inputs of a certain size use the same template instantiation + using opaque_t = detail::OpaqueType; + static_assert(sizeof(value_t) <= 8 && (sizeof(value_t) & (sizeof(value_t) - 1)) == 0, + "This size of value_t is not instantiated. Please instantiate it in cub.cu" + " and modify this check."); + static_assert(sizeof(value_t) == alignof(value_t), "Expected value_t to be size-aligned"); + detail::radix_sort_pairs_impl( + keys_in, keys_out, + reinterpret_cast(values_in), + reinterpret_cast(values_out), + n, descending, begin_bit, end_bit); +} + +template +void radix_sort_keys( + const key_t *keys_in, key_t *keys_out, + int64_t n, bool descending=false, int64_t begin_bit=0, int64_t end_bit=sizeof(key_t)*8); + +// NOTE: Intermediate sums will be truncated to input_t precision +template +void inclusive_sum_truncating(const input_t *input, output_t *output, int64_t n); + +template +void inclusive_sum(const scalar_t *input, scalar_t *output, int64_t n) { + return inclusive_sum_truncating(input, output, n); +} + +// NOTE: Sums are done is common_type +template +void exclusive_sum_in_common_type(const input_t *input, output_t *output, int64_t n); + +template +void exclusive_sum(const scalar_t *input, scalar_t *output, int64_t n) { + return exclusive_sum_in_common_type(input, output, n); +} + +void mask_exclusive_sum(const uint8_t *mask, int64_t *output_idx, int64_t n); +inline void mask_exclusive_sum(const bool *mask, int64_t *output_idx, int64_t n) { + return mask_exclusive_sum( + reinterpret_cast(mask), output_idx, n); +} + +} // namespace at::cuda::cub diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/cub_definitions.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub_definitions.cuh new file mode 100644 index 0000000000000000000000000000000000000000..cd2a941f5ed0c85338577be85fb7e68bdabb9177 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/cub_definitions.cuh @@ -0,0 +1,26 @@ +#pragma once + +#if !defined(USE_ROCM) +#include // for CUDA_VERSION +#endif + +#if !defined(USE_ROCM) +#include +#else +#define CUB_VERSION 200001 +#endif + +#define USE_GLOBAL_CUB_WRAPPED_NAMESPACE() true + +// There were many bc-breaking changes in major version release of CCCL v3.0.0 +// Please see https://nvidia.github.io/cccl/cccl/3.0_migration_guide.html +#if CUB_VERSION >= 300400 +#define CUB_V3_4_PLUS() true +#define CUB_V3_PLUS() false +#elif CUB_VERSION >= 200800 +#define CUB_V3_4_PLUS() false +#define CUB_V3_PLUS() true +#else +#define CUB_V3_4_PLUS() false +#define CUB_V3_PLUS() false +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/BLASConstants.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/BLASConstants.cu new file mode 100644 index 0000000000000000000000000000000000000000..06304cdb2399ee4cf488445c5121c6f5056645fe --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/BLASConstants.cu @@ -0,0 +1,45 @@ +#include +#include +#include + +namespace at::cuda::detail { + +__device__ __constant__ float cublas_one_device; +__device__ __constant__ float cublas_zero_device; + +float *get_cublas_device_one() { + static float *ptr = nullptr; + [[maybe_unused]] static auto init_flag = [&]() { + const float one = 1.f; + AT_CUDA_CHECK(cudaMemcpyToSymbol(cublas_one_device, &one, sizeof(float))); + AT_CUDA_CHECK(cudaGetSymbolAddress(reinterpret_cast(&ptr), cublas_one_device)); + return true; + }(); + + return ptr; +} + +float *get_cublas_device_zero() { + static float *ptr = nullptr; + [[maybe_unused]] static auto init_flag = [&]() { + const float zero = 0.f; + AT_CUDA_CHECK(cudaMemcpyToSymbol(cublas_zero_device, &zero, sizeof(float))); + AT_CUDA_CHECK(cudaGetSymbolAddress(reinterpret_cast(&ptr), cublas_zero_device)); + return true; + }(); + + return ptr; +} + +float *get_user_alpha_ptr() { + static float *alpha_ptr; + + static bool init_flag [[maybe_unused]] = []() { + AT_CUDA_CHECK(cudaMalloc(&alpha_ptr, sizeof(float))); + return true; + }(); + + return alpha_ptr; +} + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/BLASConstants.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/BLASConstants.h new file mode 100644 index 0000000000000000000000000000000000000000..2445d6fbd51db99fc350e07ced8220903507733b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/BLASConstants.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace at::cuda::detail { + +float *get_cublas_device_one(); +float *get_cublas_device_zero(); +float *get_user_alpha_ptr(); + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CUDAHooks.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CUDAHooks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5879cdad3b48982340e179c7bcd5193c3b91952d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CUDAHooks.cpp @@ -0,0 +1,594 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if AT_CUDNN_ENABLED() +#include +#include +#endif + +#if AT_MAGMA_ENABLED() +#include +#endif + +#if defined(USE_ROCM) +#include +#include +#endif + +#ifndef USE_ROCM +#include +#endif + + +#include +#include +#include + +namespace c10::cuda::_internal { +void setHasPrimaryContext(bool (*func)(DeviceIndex)); +} + +namespace at::cuda::detail { + +const at::cuda::NVRTC& nvrtc(); +DeviceIndex current_device(); + +static void (*magma_init_fn)() = nullptr; + +void set_magma_init_fn(void (*fn)()) { + magma_init_fn = fn; +} + +namespace { +bool _hasPrimaryContext(DeviceIndex device_index) { + TORCH_CHECK(device_index >= 0 && device_index < at::cuda::device_count(), + "hasPrimaryContext expects a valid device index, but got device_index=", static_cast(device_index)); + unsigned int ctx_flags = 0; + // In standalone tests of cuDevicePrimaryCtxGetState, I've seen the "active" argument end up with weird + // (garbage-looking nonzero) values when the context is not active, unless I initialize it to zero. + int ctx_is_active = 0; + AT_CUDA_DRIVER_CHECK(nvrtc().cuDevicePrimaryCtxGetState(device_index, &ctx_flags, &ctx_is_active)); + return ctx_is_active == 1; +} + +// Register hasPrimaryContext back to c10::cuda +struct _Initializer { + _Initializer() { + c10::cuda::_internal::setHasPrimaryContext(_hasPrimaryContext); + } + ~_Initializer() { + c10::cuda::_internal::setHasPrimaryContext(nullptr); + } +} initializer; +} // anonymous namespace + + +// NB: deleter is dynamic, because we need it to live in a separate +// compilation unit (alt is to have another method in hooks, but +// let's not if we don't need to!) +void CUDAHooks::init() const { + C10_LOG_API_USAGE_ONCE("aten.init.cuda"); + + const auto num_devices = c10::cuda::device_count_ensure_non_zero(); + c10::cuda::CUDACachingAllocator::init(num_devices); + at::cuda::detail::init_p2p_access_cache(num_devices); + +#if AT_MAGMA_ENABLED() + TORCH_INTERNAL_ASSERT(magma_init_fn != nullptr, "Cannot initialize magma, init routine not set"); + magma_init_fn(); +#endif +} + +const Generator& CUDAHooks::getDefaultGenerator(DeviceIndex device_index) const { + return at::cuda::detail::getDefaultCUDAGenerator(device_index); +} + +Generator CUDAHooks::getNewGenerator(DeviceIndex device_index) const { + return make_generator(device_index); +} + +Device CUDAHooks::getDeviceFromPtr(void* data) const { + return at::cuda::getDeviceFromPtr(data); +} + +bool CUDAHooks::isPinnedPtr(const void* data) const { + // First check if driver is broken/missing, in which case PyTorch CPU + // functionalities should still work, we should report `false` here. + if (!at::cuda::is_available()) { + return false; + } + // cudaPointerGetAttributes grabs context on the current device, so we set + // device to one that already has context, if exists. + at::OptionalDeviceGuard device_guard; + auto primary_ctx_device_index = getDeviceIndexWithPrimaryContext(); + if (primary_ctx_device_index.has_value()) { + device_guard.reset_device(at::Device(at::DeviceType::CUDA, *primary_ctx_device_index)); + } + cudaPointerAttributes attr{}; + // We do not believe that CUDA needs mutable access to the data + // here. + cudaError_t err = cudaPointerGetAttributes(&attr, data); +#if !defined(USE_ROCM) + if (err == cudaErrorInvalidValue) { + (void)cudaGetLastError(); // clear CUDA error + return false; + } + AT_CUDA_CHECK(err); +#else + // HIP throws hipErrorUnknown here + if (err != cudaSuccess) { + (void)cudaGetLastError(); // clear HIP error + return false; + } +#endif + return attr.type == cudaMemoryTypeHost; +} + +bool CUDAHooks::hasCUDA() const { + return at::cuda::is_available(); +} + +bool CUDAHooks::hasMAGMA() const { +#if AT_MAGMA_ENABLED() + return true; +#else + return false; +#endif +} + +bool CUDAHooks::hasCuDNN() const { + return AT_CUDNN_ENABLED(); +} + +bool CUDAHooks::hasCuSOLVER() const { +#if defined(CUDART_VERSION) && defined(CUSOLVER_VERSION) + return true; +#elif AT_ROCM_ENABLED() + return true; +#else + return false; +#endif +} + +bool CUDAHooks::hasCuBLASLt() const { +#if defined(CUDART_VERSION) + return true; +#elif AT_ROCM_ENABLED() + return true; +#else + return false; +#endif +} + + +bool CUDAHooks::hasCKSDPA() const { +#if !defined(USE_ROCM) + return false; +#elif defined(USE_ROCM) && defined(USE_ROCM_CK_SDPA) + return true; +#else + return false; +#endif +} + +bool CUDAHooks::hasCKGEMM() const { +#if !defined(USE_ROCM) + return false; +#elif defined(USE_ROCM) && defined(USE_ROCM_CK_GEMM) + return true; +#else + return false; +#endif +} + +bool CUDAHooks::hasROCM() const { + // Currently, this is same as `compiledWithMIOpen`. + // But in future if there are ROCm builds without MIOpen, + // then `hasROCM` should return true while `compiledWithMIOpen` + // should return false + return AT_ROCM_ENABLED(); +} + +#if defined(USE_DIRECT_NVRTC) +static std::pair, at::cuda::NVRTC*> load_nvrtc() { + return std::make_pair(nullptr, at::cuda::load_nvrtc()); +} +#elif !defined(USE_ROCM) +static std::pair, at::cuda::NVRTC*> load_nvrtc() { + return std::make_pair(nullptr, &at::cuda::detail::lazyNVRTC); +} +#else +static std::pair, at::cuda::NVRTC*> load_nvrtc() { +#if defined(_WIN32) + std::string libcaffe2_nvrtc = "caffe2_nvrtc.dll"; +#elif defined(__APPLE__) + std::string libcaffe2_nvrtc = "libcaffe2_nvrtc.dylib"; +#else + std::string libcaffe2_nvrtc = "libcaffe2_nvrtc.so"; +#endif + std::unique_ptr libnvrtc_stub( + new at::DynamicLibrary(libcaffe2_nvrtc.c_str())); + auto fn = (at::cuda::NVRTC * (*)()) libnvrtc_stub->sym("load_nvrtc"); + return std::make_pair(std::move(libnvrtc_stub), fn()); +} +#endif + +const at::cuda::NVRTC& nvrtc() { + // must hold onto DynamicLibrary otherwise it will unload + static auto handle = load_nvrtc(); + return *handle.second; +} + +const at::cuda::NVRTC& CUDAHooks::nvrtc() const { + return at::cuda::detail::nvrtc(); +} + +DeviceIndex current_device() { + c10::DeviceIndex device = 0; + cudaError_t err = c10::cuda::GetDevice(&device); + if (err == cudaSuccess) { + return device; + } + return -1; +} + +/** + * DEPRECATED: use getCurrentDevice() instead + */ +DeviceIndex CUDAHooks::current_device() const { + return at::cuda::detail::current_device(); +} + +bool CUDAHooks::hasPrimaryContext(DeviceIndex device_index) const { + return _hasPrimaryContext(device_index); +} + +Allocator* CUDAHooks::getPinnedMemoryAllocator() const { + return at::cuda::getPinnedMemoryAllocator(); +} + +Allocator* CUDAHooks::getCUDADeviceAllocator() const { + return at::cuda::getCUDADeviceAllocator(); +} + +bool CUDAHooks::compiledWithCuDNN() const { + return AT_CUDNN_ENABLED(); +} + +bool CUDAHooks::compiledWithMIOpen() const { + return AT_ROCM_ENABLED(); +} + +bool CUDAHooks::supportsDilatedConvolutionWithCuDNN() const { +#if AT_CUDNN_ENABLED() + if (!hasCUDA()) { + return false; + } + // NOTE: extra parenthesis around numbers disable clang warnings about + // dead code + return true; +#else + return false; +#endif +} + +bool CUDAHooks::supportsDepthwiseConvolutionWithCuDNN() const { +#if AT_CUDNN_ENABLED() + if (!hasCUDA()) { + return false; + } + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + // Check for Volta cores + if (prop->major >= 7) { + return true; + } else { + return false; + } +#else + return false; +#endif +} + +bool CUDAHooks::supportsBFloat16ConvolutionWithCuDNNv8() const { +#if AT_CUDNN_ENABLED() + if (!hasCUDA()) { + return false; + } + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + // Check for Volta cores + if (prop->major >= 8) { + return true; + } else { + return false; + } +#else + return false; +#endif +} + +bool CUDAHooks::supportsBFloat16RNNWithCuDNN() const { +#if AT_CUDNN_ENABLED() && (CUDNN_VERSION >= 91300) + if (!hasCUDA()) { + return false; + } + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + // Check for Volta cores + if (prop->major >= 8) { + return true; + } else { + return false; + } +#else + return false; +#endif +} + +long CUDAHooks::versionCuDNN() const { +#if AT_CUDNN_ENABLED() + return CUDNN_VERSION; +#else + TORCH_CHECK(false, "Cannot query CuDNN version if ATen_cuda is not built with CuDNN"); +#endif +} + +long CUDAHooks::versionRuntimeCuDNN() const { +#if AT_CUDNN_ENABLED() +#ifndef USE_STATIC_CUDNN + return cudnnGetVersion(); +#else + return CUDNN_VERSION; +#endif +#else + TORCH_CHECK(false, "Cannot query CuDNN version if ATen_cuda is not built with CuDNN"); +#endif +} + +long CUDAHooks::versionCuDNNFrontend() const { +#if AT_CUDNN_ENABLED() + return CUDNN_FRONTEND_VERSION; +#else + TORCH_CHECK(false, "Cannot query CuDNN Frontend version if ATen_cuda is not built with CuDNN"); +#endif +} + +long CUDAHooks::versionMIOpen() const { +#if AT_ROCM_ENABLED() + return MIOPEN_VERSION_MAJOR * 10000 + + MIOPEN_VERSION_MINOR * 100 + + MIOPEN_VERSION_PATCH; +#else + TORCH_CHECK(false, "Cannot query MIOpen version if ATen_cuda is not built with ROCm"); +#endif +} + +long CUDAHooks::versionHipBLASLt() const { +#if AT_ROCM_ENABLED() + return HIPBLASLT_VERSION_MAJOR * 10000 + + HIPBLASLT_VERSION_MINOR * 100 + + HIPBLASLT_VERSION_PATCH; +#else + TORCH_CHECK(false, "Cannot query HipBLASLt version if ATen_cuda is not built with ROCm"); +#endif +} + +long CUDAHooks::versionCUDART() const { +#ifdef CUDART_VERSION + return CUDART_VERSION; +#else + TORCH_CHECK( + false, + "Cannot query CUDART version because CUDART is not available"); +#endif +} + +bool CUDAHooks::hasCUDART() const { +#ifdef CUDART_VERSION + return true; +#else + return false; +#endif +} + +std::string CUDAHooks::showConfig() const { + std::ostringstream oss; + + int runtimeVersion = 0; + AT_CUDA_CHECK(cudaRuntimeGetVersion(&runtimeVersion)); + + auto printCudaStyleVersion = [&](size_t v) { +#ifdef USE_ROCM + // HIP_VERSION value format was changed after ROCm v4.2 to include the patch number + if(v < 500) { + // If major=xx, minor=yy then format -> xxyy + oss << (v / 100) << '.' << (v % 10); + } + else { + // If major=xx, minor=yy & patch=zzzzz then format -> xxyyzzzzz + oss << (v / 10000000) << '.' << (v / 100000 % 100) << '.' << (v % 100000); + } +#else + oss << (v / 1000) << '.' << (v / 10 % 100); + if (v % 10 != 0) { + oss << '.' << (v % 10); + } +#endif + }; + +#if !defined(USE_ROCM) + oss << " - CUDA Runtime "; +#else + oss << " - HIP Runtime "; +#endif + printCudaStyleVersion(runtimeVersion); + oss << '\n'; + + // TODO: Make HIPIFY understand CUDART_VERSION macro +#if !defined(USE_ROCM) + if (runtimeVersion != CUDART_VERSION) { + oss << " - Built with CUDA Runtime "; + printCudaStyleVersion(CUDART_VERSION); + oss << '\n'; + } + oss << " - NVCC architecture flags: " << NVCC_FLAGS_EXTRA << '\n'; +#endif + +#if !defined(USE_ROCM) +#if AT_CUDNN_ENABLED() + + + auto printCudnnStyleVersion = [&](size_t v) { + oss << (v / 1000) << '.' << (v / 100 % 10); + if (v % 100 != 0) { + oss << '.' << (v % 100); + } + }; + + size_t cudnnVersion = cudnnGetVersion(); + oss << " - CuDNN "; + printCudnnStyleVersion(cudnnVersion); + size_t cudnnCudartVersion = cudnnGetCudartVersion(); + if (cudnnCudartVersion != CUDART_VERSION) { + oss << " (built against CUDA "; + printCudaStyleVersion(cudnnCudartVersion); + oss << ')'; + } + oss << '\n'; + if (cudnnVersion != CUDNN_VERSION) { + oss << " - Built with CuDNN "; + printCudnnStyleVersion(CUDNN_VERSION); + oss << '\n'; + } +#endif +#else + // TODO: Check if miopen has the functions above and unify + oss << " - MIOpen " << MIOPEN_VERSION_MAJOR << '.' << MIOPEN_VERSION_MINOR << '.' << MIOPEN_VERSION_PATCH << '\n'; +#endif + +#if AT_MAGMA_ENABLED() + oss << " - Magma " << MAGMA_VERSION_MAJOR << '.' << MAGMA_VERSION_MINOR << '.' << MAGMA_VERSION_MICRO << '\n'; +#endif + + return oss.str(); +} + +double CUDAHooks::batchnormMinEpsilonCuDNN() const { +#if AT_CUDNN_ENABLED() + return CUDNN_BN_MIN_EPSILON; +#else + TORCH_CHECK(false, + "Cannot query CUDNN_BN_MIN_EPSILON if ATen_cuda is not built with CuDNN"); +#endif +} + +int64_t CUDAHooks::cuFFTGetPlanCacheMaxSize(DeviceIndex device_index) const { + return at::native::detail::cufft_get_plan_cache_max_size_impl(device_index); +} + +void CUDAHooks::cuFFTSetPlanCacheMaxSize(DeviceIndex device_index, int64_t max_size) const { + at::native::detail::cufft_set_plan_cache_max_size_impl(device_index, max_size); +} + +int64_t CUDAHooks::cuFFTGetPlanCacheSize(DeviceIndex device_index) const { + return at::native::detail::cufft_get_plan_cache_size_impl(device_index); +} + +void CUDAHooks::cuFFTClearPlanCache(DeviceIndex device_index) const { + at::native::detail::cufft_clear_plan_cache_impl(device_index); +} + +/** + * DEPRECATED: use deviceCount() instead + */ +int CUDAHooks::getNumGPUs() const { + return at::cuda::device_count(); +} + +DeviceIndex CUDAHooks::deviceCount() const { + return at::cuda::device_count(); +} + +DeviceIndex CUDAHooks::getCurrentDevice() const { + return at::cuda::detail::current_device(); +} + +#ifdef USE_ROCM +bool CUDAHooks::isGPUArch(const std::vector& archs, DeviceIndex device_index) const { + hipDeviceProp_t* prop; + if (device_index == -1){ + prop = at::cuda::getCurrentDeviceProperties(); + } else { + prop = at::cuda::getDeviceProperties(device_index); + } + + std::string device_arch = prop->gcnArchName; + for (std::string arch : archs) { + size_t substring = device_arch.find(arch); + if (substring != std::string::npos) { + return true; + } + } + return false; +} + +const std::vector& CUDAHooks::getHipblasltPreferredArchs() const { + static const std::vector archs = { + "gfx90a", "gfx942", +#if ROCM_VERSION >= 60400 + "gfx1200", "gfx1201", +#endif +#if ROCM_VERSION >= 70000 + "gfx950", +#endif +#if ROCM_VERSION >= 71300 + "gfx1100", "gfx1101", "gfx1151" +#endif + }; + return archs; +} + +const std::vector& CUDAHooks::getHipblasltSupportedArchs() const { + static const std::vector archs = { + "gfx90a", "gfx942", +#if ROCM_VERSION >= 60300 + "gfx1100", "gfx1101", "gfx1103", "gfx1200", "gfx1201", "gfx908", +#endif +#if ROCM_VERSION >= 70000 + "gfx950", "gfx1150", "gfx1151", +#endif +#if ROCM_VERSION >= 70200 + "gfx1250" +#endif + }; + return archs; +} +#endif + +void CUDAHooks::deviceSynchronize(DeviceIndex device_index) const { + at::DeviceGuard device_guard(at::Device(at::DeviceType::CUDA, device_index)); + c10::cuda::device_synchronize(); +} + +// Sigh, the registry doesn't support namespaces :( +using at::CUDAHooksRegistry; +using at::RegistererCUDAHooksRegistry; + +REGISTER_CUDA_HOOKS(CUDAHooks) + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CUDAHooks.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CUDAHooks.h new file mode 100644 index 0000000000000000000000000000000000000000..f57e22894a334930d0798f9b0e4549de7e3a889e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CUDAHooks.h @@ -0,0 +1,74 @@ +#pragma once + +#include + +#include + +// TODO: No need to have this whole header, we can just put it all in +// the cpp file + +namespace at::cuda::detail { + +// Set the callback to initialize Magma, which is set by +// torch_cuda_cu. This indirection is required so magma_init is called +// in the same library where Magma will be used. +TORCH_CUDA_CPP_API void set_magma_init_fn(void (*magma_init_fn)()); + + +// The real implementation of CUDAHooksInterface +struct CUDAHooks : public at::CUDAHooksInterface { + CUDAHooks(at::CUDAHooksArgs /*unused*/) {} + void init() const override; + Device getDeviceFromPtr(void* data) const override; + bool isPinnedPtr(const void* data) const override; + const Generator& getDefaultGenerator( + DeviceIndex device_index = -1) const override; + Generator getNewGenerator( + DeviceIndex device_index = -1) const override; + bool hasCUDA() const override; + bool hasMAGMA() const override; + bool hasCuDNN() const override; + bool hasCuSOLVER() const override; + bool hasCuBLASLt() const override; + bool hasROCM() const override; + bool hasCKSDPA() const override; + bool hasCKGEMM() const override; + const at::cuda::NVRTC& nvrtc() const override; + DeviceIndex current_device() const override; + bool isBuilt() const override {return true;} + bool isAvailable() const override {return hasCUDA();} + bool hasPrimaryContext(DeviceIndex device_index) const override; + Allocator* getCUDADeviceAllocator() const override; + Allocator* getPinnedMemoryAllocator() const override; + bool compiledWithCuDNN() const override; + bool compiledWithMIOpen() const override; + bool supportsDilatedConvolutionWithCuDNN() const override; + bool supportsDepthwiseConvolutionWithCuDNN() const override; + bool supportsBFloat16ConvolutionWithCuDNNv8() const override; + bool supportsBFloat16RNNWithCuDNN() const override; + bool hasCUDART() const override; + long versionCUDART() const override; + long versionCuDNN() const override; + long versionRuntimeCuDNN() const override; + long versionCuDNNFrontend() const override; + long versionMIOpen() const override; + long versionHipBLASLt() const override; + std::string showConfig() const override; + double batchnormMinEpsilonCuDNN() const override; + int64_t cuFFTGetPlanCacheMaxSize(DeviceIndex device_index) const override; + void cuFFTSetPlanCacheMaxSize(DeviceIndex device_index, int64_t max_size) const override; + int64_t cuFFTGetPlanCacheSize(DeviceIndex device_index) const override; + void cuFFTClearPlanCache(DeviceIndex device_index) const override; + int getNumGPUs() const override; + DeviceIndex deviceCount() const override; + DeviceIndex getCurrentDevice() const override; + +#ifdef USE_ROCM + bool isGPUArch(const std::vector& archs, DeviceIndex device_index = -1) const override; + const std::vector& getHipblasltPreferredArchs() const override; + const std::vector& getHipblasltSupportedArchs() const override; +#endif + void deviceSynchronize(DeviceIndex device_index) const override; +}; + +} // at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CublasLtUtils.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CublasLtUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..dba24e8f0761a5fdfe94349d2ec70f7d73e136c6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/CublasLtUtils.h @@ -0,0 +1,318 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace at::cuda::blas::detail { + +template +struct CuBlasLtDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_CUDABLAS_CHECK(destructor(x)); + } + } +}; + +template +class CuBlasLtDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; + +class CuBlasLtMatmulDescriptor : public CuBlasLtDescriptor< + cublasLtMatmulDescOpaque_t, + &cublasLtMatmulDescDestroy> { + public: + CuBlasLtMatmulDescriptor( + cublasComputeType_t compute_type, + cudaDataType_t scale_type) { + cublasLtMatmulDesc_t raw_descriptor = nullptr; + TORCH_CUDABLAS_CHECK( + cublasLtMatmulDescCreate(&raw_descriptor, compute_type, scale_type)); + descriptor_.reset(raw_descriptor); + } + + template + void setAttribute(cublasLtMatmulDescAttributes_t attr, const T value) { + // NOLINTNEXTLINE(bugprone-sizeof-expression) + TORCH_CUDABLAS_CHECK(::cublasLtMatmulDescSetAttribute( + descriptor(), attr, &value, sizeof(value))); + } +}; + +class CuBlasLtMatrixLayout : public CuBlasLtDescriptor< + cublasLtMatrixLayoutOpaque_t, + &cublasLtMatrixLayoutDestroy> { + public: + CuBlasLtMatrixLayout( + cudaDataType_t type, + uint64_t rows, + uint64_t cols, + int64_t ld, + bool t = false) { + cublasLtMatrixLayout_t raw_descriptor = nullptr; + TORCH_CUDABLAS_CHECK(cublasLtMatrixLayoutCreate( + &raw_descriptor, type, t ? cols : rows, t ? rows : cols, ld)); + descriptor_.reset(raw_descriptor); + } + + template + void setAttribute(cublasLtMatrixLayoutAttribute_t attr, const T value) { + TORCH_CUDABLAS_CHECK(::cublasLtMatrixLayoutSetAttribute( + descriptor(), attr, &value, sizeof(T))); + } +}; + +class CuBlasLtMatmulPreference : public CuBlasLtDescriptor< + cublasLtMatmulPreferenceOpaque_t, + &cublasLtMatmulPreferenceDestroy> { + public: + CuBlasLtMatmulPreference() { + cublasLtMatmulPreference_t raw_descriptor = nullptr; + TORCH_CUDABLAS_CHECK(cublasLtMatmulPreferenceCreate(&raw_descriptor)); + descriptor_.reset(raw_descriptor); + } + + template + void setAttribute(cublasLtMatmulPreferenceAttributes_t attr, const T value) { + TORCH_CUDABLAS_CHECK(::cublasLtMatmulPreferenceSetAttribute( + descriptor(), attr, &value, sizeof(T))); + } +}; + +struct CublasLtWorkspace { + CublasLtWorkspace() { + size = at::cuda::getCUDABlasLtWorkspaceSize(); + ptr = at::cuda::getCUDABlasLtWorkspace(); + } + + void* ptr; + size_t size; +}; + +inline cublasOperation_t cublasOpFromChar(char op) { + switch (op) { + case 'n': + case 'N': + return CUBLAS_OP_N; + case 't': + case 'T': + return CUBLAS_OP_T; + case 'c': + case 'C': + return CUBLAS_OP_C; + } + TORCH_CHECK( + false, + "cublasOpFromChar input should be 't', 'n' or 'c' but got `", + op, + "`"); + return CUBLAS_OP_N; // unreachable - TORCH_CHECK(false) throws +} + +inline int cublasLtMatmulScaleMode( + at::blas::ScalingType scaling_type, + ScalarType scale_dtype, + bool use_fast_accum) { + switch (scaling_type) { + case at::blas::ScalingType::BlockWise1x32: + TORCH_CHECK(scale_dtype == kFloat8_e8m0fnu); +#if CUDA_VERSION >= 12080 || (defined(USE_ROCM) && ROCM_VERSION >= 70000) + return CUBLASLT_MATMUL_MATRIX_SCALE_VEC32_UE8M0; +#else + TORCH_CHECK( + false, + "scaled_gemm with `torch.float8_e8m0fnu` scales of 1x32 blocks " + "is only supported for CUDA 12.8 and above"); +#endif + case at::blas::ScalingType::BlockWise1x16: + TORCH_CHECK(scale_dtype == kFloat8_e4m3fn); +#if CUDA_VERSION >= 12080 + return CUBLASLT_MATMUL_MATRIX_SCALE_VEC16_UE4M3; +#else + TORCH_CHECK( + false, + "scaled_gemm with `torch.float8_e4m3fn` scales of 1x16 blocks " + "is only supported for CUDA 12.8 and above"); +#endif + case at::blas::ScalingType::RowWise: + TORCH_CHECK(scale_dtype == kFloat); +#if CUDA_VERSION >= 12090 || (defined(USE_ROCM) && defined(HIPBLASLT_OUTER_VEC)) + return CUBLASLT_MATMUL_MATRIX_SCALE_OUTER_VEC_32F; +#elif defined(USE_ROCM) && defined(HIPBLASLT_VEC_EXT) + // Old hipBLASLt rowwise mode is activated through SCALE_POINTER_VEC_EXT. + return 0; +#else + TORCH_CHECK( + false, + "scaled_gemm with rowwise scaling is only supported for CUDA 12.9 " + "and above"); +#endif + case at::blas::ScalingType::BlockWise1x128: + TORCH_CHECK(scale_dtype == kFloat); + TORCH_CHECK( + !use_fast_accum, + "scaled_gemm doesn't support fast accum with 1x128 blockwise scaling"); +#if CUDA_VERSION >= 12090 + return CUBLASLT_MATMUL_MATRIX_SCALE_VEC128_32F; +#else + TORCH_CHECK( + false, + "scaled_gemm with 1x128 blockwise scaling is only supported for " + "CUDA 12.9 and above"); +#endif + case at::blas::ScalingType::BlockWise128x128: + TORCH_CHECK(scale_dtype == kFloat); + TORCH_CHECK( + !use_fast_accum, + "scaled_gemm doesn't support fast accum with 128x128 blockwise scaling"); +#if CUDA_VERSION >= 12090 + return CUBLASLT_MATMUL_MATRIX_SCALE_BLK128x128_32F; +#else + TORCH_CHECK( + false, + "scaled_gemm with 128x128 blockwise scaling is only supported for " + "CUDA 12.9 and above"); +#endif + case at::blas::ScalingType::TensorWise: + TORCH_CHECK(scale_dtype == kFloat); +#if CUDA_VERSION >= 12080 + return CUBLASLT_MATMUL_MATRIX_SCALE_SCALAR_32F; +#else + return 0; +#endif + default: + TORCH_CHECK(false); + } +} + +inline void cublasAdjustLdLevel3( + char transa, + char transb, + int64_t m, + int64_t n, + int64_t k, + int64_t* lda, + int64_t* ldb, + int64_t* ldc) { + bool transa_ = ((transa != 'n') && (transa != 'N')); + bool transb_ = ((transb != 'n') && (transb != 'N')); + + if (n <= 1) { + *ldc = std::max(m, 1); + } + if (transa_) { + if (m <= 1) { + *lda = std::max(k, 1); + } + } else { + if (k <= 1) { + *lda = std::max(m, 1); + } + } + if (transb_) { + if (k <= 1) { + *ldb = std::max(n, 1); + } + } else { + if (n <= 1) { + *ldb = std::max(k, 1); + } + } +} + +#ifndef USE_ROCM +inline uint32_t getAlignment(uintptr_t address) { + uint32_t alignment = 256; + for (;; alignment /= 2) { + if (!(address % alignment)) { + return alignment; + } + } +} +#endif + +template +struct CublasLtTypeInfo { + cudaDataType_t ab_type = CUDA_R_32F; + cudaDataType_t c_type = CUDA_R_32F; + cublasComputeType_t compute_type = CUBLAS_COMPUTE_32F; + cudaDataType_t scale_type = CUDA_R_32F; +}; + +template +CublasLtTypeInfo getCublasLtTypeInfo() { + CublasLtTypeInfo info; + if constexpr (std::is_same_v) { + info.ab_type = CUDA_R_64F; + info.c_type = CUDA_R_64F; + info.compute_type = CUBLAS_COMPUTE_64F; + info.scale_type = CUDA_R_64F; + } else if constexpr (std::is_same_v) { + if (at::globalContext().float32Precision( + at::Float32Backend::CUDA, + at::Float32Op::MATMUL) == at::Float32Precision::TF32) { + info.compute_type = CUBLAS_COMPUTE_32F_FAST_TF32; + } + } else if constexpr (std::is_same_v>) { + info.ab_type = CUDA_C_64F; + info.c_type = CUDA_C_64F; + info.compute_type = CUBLAS_COMPUTE_64F; + info.scale_type = CUDA_C_64F; + } else if constexpr (std::is_same_v>) { + info.ab_type = CUDA_C_32F; + info.c_type = CUDA_C_32F; + info.scale_type = CUDA_C_32F; + } else if constexpr (std::is_same_v) { +#ifndef USE_ROCM + auto* prop = at::cuda::getCurrentDeviceProperties(); + if (prop->major >= 7 && at::globalContext().allowFP16AccumulationCuBLAS()) { + info.compute_type = CUBLAS_COMPUTE_16F; + info.scale_type = CUDA_R_16F; + } +#endif + info.ab_type = CUDA_R_16F; + info.c_type = std::is_same_v ? CUDA_R_32F : CUDA_R_16F; + } else if constexpr (std::is_same_v) { + info.ab_type = CUDA_R_16BF; + info.c_type = std::is_same_v ? CUDA_R_32F : CUDA_R_16BF; + } else { + static_assert( + false && sizeof(T), + "getCublasLtTypeInfo: unsupported cuBLASLt type"); + } + return info; +} + +inline cublasLtEpilogue_t cublasLtEpilogue( + at::cuda::blas::GEMMAndBiasActivationEpilogue activation, + const void* bias) { + switch (activation) { + case at::cuda::blas::GEMMAndBiasActivationEpilogue::RELU: + return bias ? CUBLASLT_EPILOGUE_RELU_BIAS : CUBLASLT_EPILOGUE_RELU; + case at::cuda::blas::GEMMAndBiasActivationEpilogue::GELU: + return bias ? CUBLASLT_EPILOGUE_GELU_BIAS : CUBLASLT_EPILOGUE_GELU; + default: + return bias ? CUBLASLT_EPILOGUE_BIAS : CUBLASLT_EPILOGUE_DEFAULT; + } +} + +} // namespace at::cuda::blas::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/DeviceThreadHandles.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/DeviceThreadHandles.h new file mode 100644 index 0000000000000000000000000000000000000000..73d3a29f540614a8b7c46bfafc5de7a041862408 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/DeviceThreadHandles.h @@ -0,0 +1,200 @@ +// Some stateful GPU libraries, such as cuDNN, cuBLAS, use handles to store states. +// These handles are tied to device, and these libraries requires/recommends not to +// share handles across host threads. +// +// These libraries recommend using one handle per host thread. We may not want to do +// this because threads are relatively light-weight, but creating and destroying +// handles is expensive (destroying the handle causes synchronizations). DataParallel, +// for example, creates new threads for each forward pass. +// +// This file implements a handle pool mechanism. The handle pool returns handles on +// demand as threads request them. If all existing handles in the pool are in use, +// it creates a new one. As threads terminate, they release handles back into the pool. +// In this way, the handle pool never creates more handles than the high-water mark of +// active threads, so it's efficient with DataParallel. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include + +namespace at::cuda { namespace { + +template +struct DeviceThreadHandlePool : public std::enable_shared_from_this> { + + struct Handle { + Handle_t handle; + Handle(bool create = false) : handle(nullptr) + { + if(create) Create(&handle); + } + // std::vector.emplace() and push_back() may route through temporaries and call + // copy/move constructors along the way. If this is the case, we don't want + // the destructors of temporaries to call cudnnDestroy on the handle. + // We can achieve safety (for the narrow case of stashing within std::vectors) + // by making Handle moveable but not copyable, and transferring handle ownership + // to the latest constructed object. This is not a substitute for full-blown + // reference counting, but reference counting may be overkill here. + // Another alternative is to wrap the saved Handles in unique_ptrs, i.e., + // unordered_map>> created_handles; + Handle(const Handle& rhs) = delete; + // Following https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom + Handle(Handle&& rhs) noexcept : Handle() { std::swap(handle, rhs.handle); } + // operator= takes argument by value + Handle& operator=(Handle rhs) { std::swap(handle, rhs.handle); return *this; } + ~Handle() { + if(handle) Destroy(handle); + } + }; + + std::mutex mutex; + + // Handles are lazily created as different threads request them, + // but are never destroyed until the end of the process. + // The maximum number of handles this process will create for each device is equal + // to the high-water mark of the number of concurrently active threads that request + // handles for that device. + // When threads terminate, they release their handles back into the pool for reuse. + // Otherwise, new handles would be created every time new threads were spawned, + // resulting in poor performance for Python modules that repeatedly or frequently + // spawned new sets of threads (like DataParallel, which creates a new set of threads + // for each forward pass). + // + // To prevent potential deadlocks, we explicitly choose not to cap the number + // of handles that are created per device. + // Example of danger: If we cap the max handles at 4, and 5 threads are sharing a device, + // only 4 can make forward progress at any time. The other 4 will not release their + // handles until they exit, so the fifth cannot make progress until then. This is + // not a problem...UNLESS all 5 threads attempt some sort of synchronization at an + // intermediate point (ie, before any of them have exited). We have no way to anticipate + // or enforce that user threads will not attempt such intermediate synchronization. + // The only way to ensure safety is to avoid imposing a cap on the number of handles. + std::unordered_map> created_handles; + std::unordered_map> available_handles; + + // PoolWindow lazily creates and caches the handles that a particular thread is using, + // so in the common case handle access doesn't incur either handle creation or a mutex lock. + class PoolWindow + { + public: + PoolWindow(std::shared_ptr parent): weak_parent(std::move(parent)) {} + ~PoolWindow(){ release(); } + + Handle_t reserve(int device) + { + // If this thread already has a handle for this device, return it + if(my_handles.find(device) != my_handles.end()) + return my_handles[device]; + + // otherwise, either grab a handle from the pool if one is available, + // or if not, create a new one. + auto parent = weak_parent.lock(); + TORCH_CHECK(parent, "Cannot create handle during program termination"); + std::lock_guard guard(parent->mutex); + + if(parent->available_handles[device].size() > 0) + { + my_handles[device] = parent->available_handles[device].back(); + parent->available_handles[device].pop_back(); + } + else + { + // In local testing, I do observe that emplace_back sometimes routes through temporaries + // that incur move-constructor and destructor calls. See comments in Handle above. + parent->created_handles[device].emplace_back(true /*create*/); + my_handles[device] = parent->created_handles[device].back().handle; + } + + return my_handles[device]; + } + +#ifdef USE_ROCM + // hipblaslt cannot share a single handle across multiple streams, so this + // overload returns a handle unique to each (device, stream) pair. + Handle_t reserve(int device, void* stream) + { + auto key = std::make_pair(device, stream); + // If this thread already has a handle for this (device, stream), return it + if(my_stream_handles.find(key) != my_stream_handles.end()) + return my_stream_handles[key]; + + // otherwise, either grab a handle from the pool if one is available, + // or if not, create a new one. + auto parent = weak_parent.lock(); + TORCH_CHECK(parent, "Cannot create handle during program termination"); + std::lock_guard guard(parent->mutex); + + if(parent->available_handles[device].size() > 0) + { + my_stream_handles[key] = parent->available_handles[device].back(); + parent->available_handles[device].pop_back(); + } + else + { + parent->created_handles[device].emplace_back(true /*create*/); + my_stream_handles[key] = parent->created_handles[device].back().handle; + } + + return my_stream_handles[key]; + } +#endif + + private: + // Stores the per-device handles currently owned by this thread + std::unordered_map my_handles; +#ifdef USE_ROCM + // Stores per-(device, stream) handles for ROCm, where hipblaslt + // requires a unique handle per stream. + std::map, Handle_t> my_stream_handles; +#endif + + std::weak_ptr weak_parent; + + // Called by the destructor. Releases this thread's handles back into the pool. + void release() { + if(!my_handles.empty()) { + auto parent = weak_parent.lock(); + if (!parent) { + // If this thread exits after atexit handlers have completed, the + // cuda context itself may be invalid, so we must leak the handles. + return; + } + + std::lock_guard guard(parent->mutex); + for(auto d_h : my_handles) + parent->available_handles[d_h.first].push_back(d_h.second); + } +#ifdef USE_ROCM + if(!my_stream_handles.empty()) { + auto parent = weak_parent.lock(); + if (!parent) { + return; + } + + std::lock_guard guard(parent->mutex); + for(auto& [key, handle] : my_stream_handles) + parent->available_handles[key.first].push_back(handle); + } +#endif + } + }; + + // Warning: + // If you want to change this function, be aware that this function will be called + // by multiple threads and there is no mutex guarding the call of this function, so + // make sure your implementation is thread-safe. + PoolWindow *newPoolWindow() { + // The returned pointer will be owned by a thread local variable + // so that different threads does not share the same PoolWindow. + return new PoolWindow(this->shared_from_this()); + } +}; + +}} // namespace at::cuda::detail:: diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IndexUtils.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IndexUtils.cu new file mode 100644 index 0000000000000000000000000000000000000000..0cf155f399a122dd20c84a31da5993b600bb9248 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IndexUtils.cu @@ -0,0 +1,71 @@ +#include +#include + +namespace at::cuda::detail { + +struct SizeAndStride { + int64_t size; + int64_t stride; +}; + +/* + A comparator that will sort SizeAndStride structs by stride, + in ascending order. + */ + int compareSizeAndStride(const void* a, const void* b) { + const SizeAndStride* aS = (const SizeAndStride*) a; + const SizeAndStride* bS = (const SizeAndStride*) b; + + if (aS->stride < bS->stride) return -1; + if (aS->stride == bS->stride) return 0; + return 1; +} + +/* +Returns false if there is no possibility that the tensor +has "overlapping" indices and true otherwise. +"Overlapping" indices are two+ valid indices that specify +the same offset within the tensor. +The function does this by checking for a sufficient but not +necessary condition of no overlap. In particular, that +that there exists an ordering of the tensor's dimensions +that is nicely "nested," with each dimension contained +within the next one. +*/ +bool maybeOverlappingIndices(const TensorBase& t) { + /* Extract size/stride arrays; only consider size >1 dims. */ + std::vector info(t.dim()); + auto dims = t.dim(); + int nonSize1Dims = 0; + for (int i = 0; i < dims; ++i) { + int64_t size = t.size(i); + if (size > 1) { + info[nonSize1Dims].size = size; + info[nonSize1Dims].stride = t.stride(i); + + if (info[nonSize1Dims].stride < 1) { + return true; + } + + ++nonSize1Dims; + } + } + + // Short-circuits if tensor is a single element. + if (nonSize1Dims == 0) { + return false; + } + + /* Ascending order (innermost dimension in sorted view is at [0]) */ + qsort(info.data(), nonSize1Dims, sizeof(SizeAndStride), compareSizeAndStride); + + for (int i = 0; i < (nonSize1Dims - 1); ++i) { + if (((info[i].size - 1) * info[i].stride) >= info[i + 1].stride) { + return true; + } + } + + return false; +} + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IndexUtils.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IndexUtils.cuh new file mode 100644 index 0000000000000000000000000000000000000000..444a4ba820719abb2c6530ca86440fa9a02f4f18 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IndexUtils.cuh @@ -0,0 +1,63 @@ +#pragma once + +#include +#include +#include + +namespace at::cuda::detail { + +TORCH_CUDA_CU_API bool maybeOverlappingIndices(const at::TensorBase &t); +using at::native::canUse32BitIndexMath; + +template +TensorInfo +getTensorInfo(const at::TensorBase &t) { + IndexType sz[MAX_TENSORINFO_DIMS]; + IndexType st[MAX_TENSORINFO_DIMS]; + + int dims = t.dim(); + for (int i = 0; i < dims; ++i) { + sz[i] = t.size(i); + st[i] = t.stride(i); + } + + scalar* data_ptr = nullptr; + + if constexpr (std::is_const_v) { + data_ptr = t.const_data_ptr(); + } else { + data_ptr = t.mutable_data_ptr(); + } + + return TensorInfo( + data_ptr, dims, sz, st); +} + +// ForwardIt: only legacy random access iterator is supported. +template +static __host__ __device__ __forceinline__ +ForwardIt find_bound(ForwardIt first, ForwardIt last, const T& value) { + ForwardIt it; + typename std::iterator_traits::difference_type count, step; + // NOTE: std::distance(first, last) compiles but produces wrong results here, + // so only legacy random access iterators are safe in this code. + count = last - first; + + while (count > 0) { + it = first; + step = count / 2; + // avoiding std::advance(it, step), + // although it does work unlike std::distance + it += step; + if (is_lower ? *it < value : value >= *it) { + first = ++it; + count -= step + 1; + } + else { + count = step; + } + } + return first; +} + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IntegerDivider.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IntegerDivider.cuh new file mode 100644 index 0000000000000000000000000000000000000000..7532aed5fee08a22c88135169634d206ab3c8982 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/IntegerDivider.cuh @@ -0,0 +1,124 @@ +#pragma once + +#include +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) +#include +#endif + +namespace at::cuda::detail { + +// A utility class to implement integer division by multiplication, given a fixed +// divisor. +// +// WARNING: The fast divider algorithm is only implemented for unsigned int; +// otherwise we default to plain integer division. For unsigned int, +// we further assume that the dividend is at most INT32_MAX. Thus, +// IntDivider must NOT be used for general integer division. +// +// This reduced range is enough for our purpose, and it allows us to +// slightly simplify the computation. +// +// (NOTE: Below, "2^k" denotes exponentiation, i.e., 1< 0), we can find a "magic number" m (2^N +// <= m < 2^(N+1)) and shift s such that: +// +// \floor(n / d) = \floor((m * n) / 2^(N+s)). +// +// Given such m and s, the integer division can be then implemented as: +// +// let m' = m - 2^N // 0 <= m' < 2^N +// +// fast_integer_division(n): +// // Multiply two N-bit unsigned integers: the result is a 2N-bit unsigned +// // integer. Then take the higher N bits. +// t = (m' * n) >> N +// +// // Here we use the fact that n is less than 2^(N-1): otherwise the value +// // of (t + n) may not fit in an N-bit integer. +// return (t + n) >> s +// +// Finding such a magic number is surprisingly easy: +// +// s = \ceil(\log_2 d) +// m' = \floor(2^N * (2^s - d) / d) + 1 // Need 2N-bit integer arithmetic. +// +// See also: +// - Division by Invariant Integers Using Multiplication, +// Torbjörn Granlund and Peter L. Montgomery, 1994. +// +// - http://www.hackersdelight.org/magic.htm +// +// - http://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html + +// Result of div/mod operation stored together. +template +struct DivMod { + Value div, mod; + + C10_HOST_DEVICE DivMod(Value div, Value mod) : div(div), mod(mod) { } +}; + +// Base case: we only have an implementation for uint32_t for now. For +// everything else, we use plain division. +template +struct IntDivider { + IntDivider() = default; + IntDivider(Value d) : divisor(d) { } + + C10_HOST_DEVICE inline Value div(Value n) const { return n / divisor; } + C10_HOST_DEVICE inline Value mod(Value n) const { return n % divisor; } + C10_HOST_DEVICE inline DivMod divmod(Value n) const { + return DivMod(n / divisor, n % divisor); + } + + Value divisor; +}; + +// Implement fast integer division. +template <> +struct IntDivider { + static_assert(sizeof(unsigned int) == 4, "Assumes 32-bit unsigned int."); + + IntDivider() = default; + + IntDivider(unsigned int d) : divisor(d) { + assert(divisor >= 1 && divisor <= INT32_MAX); + + // TODO: gcc/clang has __builtin_clz() but it's not portable. + for (shift = 0; shift < 32; shift++) if ((1U << shift) >= divisor) break; + + uint64_t one = 1; + uint64_t magic = ((one << 32) * ((one << shift) - divisor)) / divisor + 1; + m1 = magic; + assert(m1 > 0 && m1 == magic); // m1 must fit in 32 bits. + } + + C10_HOST_DEVICE inline unsigned int div(unsigned int n) const { +#if defined(__CUDA_ARCH__) || defined(__HIP_DEVICE_COMPILE__) + // 't' is the higher 32-bits of unsigned 32-bit multiplication of 'n' and + // 'm1'. + unsigned int t = __umulhi(n, m1); + return (t + n) >> shift; +#else + // Using uint64_t so that the addition does not overflow. + uint64_t t = ((uint64_t) n * m1) >> 32; + return (t + n) >> shift; +#endif + } + + C10_HOST_DEVICE inline unsigned int mod(unsigned int n) const { + return n - div(n) * divisor; + } + + C10_HOST_DEVICE inline DivMod divmod(unsigned int n) const { + unsigned int q = div(n); + return DivMod(q, n - q * divisor); + } + + unsigned int divisor; // d above. + unsigned int m1; // Magic number: m' above. + unsigned int shift; // Shift amounts. +}; + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/KernelUtils.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/KernelUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..02af7d1302b86c5e4bdf52f98eec5c800060291a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/KernelUtils.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include + +namespace at::cuda::detail { + +// CUDA: grid stride looping +// +// int64_t _i_n_d_e_x specifically prevents overflow in the loop increment. +// If input.numel() < INT_MAX, _i_n_d_e_x < INT_MAX, except after the final +// iteration of the loop where _i_n_d_e_x += blockDim.x * gridDim.x can be +// greater than INT_MAX. But in that case _i_n_d_e_x >= n, so there are no +// further iterations and the overflowed value in i=_i_n_d_e_x is not used. +#define CUDA_KERNEL_LOOP_TYPE(i, n, index_type) \ + int64_t _i_n_d_e_x = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x; \ + for (index_type i=_i_n_d_e_x; _i_n_d_e_x < (n); _i_n_d_e_x+=blockDim.x * gridDim.x, i=_i_n_d_e_x) + +#define CUDA_KERNEL_LOOP(i, n) CUDA_KERNEL_LOOP_TYPE(i, n, int) + + +// Use 1024 threads per block, which requires cuda sm_2x or above +constexpr int CUDA_NUM_THREADS = 1024; + +// CUDA: number of blocks for threads. +inline int GET_BLOCKS(const int64_t N, const int64_t max_threads_per_block=CUDA_NUM_THREADS) { + TORCH_INTERNAL_ASSERT(N > 0, "CUDA kernel launch blocks must be positive, but got N=", N); + constexpr int64_t max_int = std::numeric_limits::max(); + + // Round up division for positive number that cannot cause integer overflow + auto block_num = (N - 1) / max_threads_per_block + 1; + TORCH_INTERNAL_ASSERT(block_num <= max_int, "Can't schedule too many blocks on CUDA device"); + + return static_cast(block_num); +} + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/LazyNVRTC.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/LazyNVRTC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2eb5d24ba2aba3a82baf9a438527e18c5dccfb0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/LazyNVRTC.cpp @@ -0,0 +1,300 @@ +#include + +#include +#include +#include + + + +namespace at::cuda::detail { +namespace _stubs { + +at::DynamicLibrary& getCUDALibrary() { +#if defined(_WIN32) + static at::DynamicLibrary lib("nvcuda.dll"); +#else + static at::DynamicLibrary lib("libcuda.so.1"); +#endif + return lib; +} + +static std::string getLibVersion() { + // [NVRTC versioning] + // Quote of https://docs.nvidia.com/cuda/nvrtc/index.html Section 8.1. NVRTC library versioning + // + // In the following, MAJOR and MINOR denote the major and minor versions of the CUDA Toolkit. + // e.g. for CUDA 11.2, MAJOR is "11" and MINOR is "2". + // + // Linux: + // - In CUDA toolkits prior to CUDA 11.3, the soname was set to "MAJOR.MINOR". + // - In CUDA 11.3 and later 11.x toolkits, the soname field is set to "11.2". + // - In CUDA toolkits with major version > 11 (e.g. CUDA 12.x), the soname field is set to "MAJOR". + // + // Windows: + // - In CUDA toolkits prior to cuda 11.3, the DLL name was of the form "nvrtc64_XY_0.dll", where X = MAJOR, Y = MINOR. + // - In CUDA 11.3 and later 11.x toolkits, the DLL name is "nvrtc64_112_0.dll". + // - In CUDA toolkits with major version > 11 (e.g. CUDA 12.x), the DLL name is of the form "nvrtc64_X0_0.dll" where X = MAJOR. + // + // Consider a CUDA toolkit with major version > 11. The NVRTC library in this CUDA toolkit will have the same soname (Linux) + // or DLL name (Windows) as an NVRTC library in a previous minor version of the same CUDA toolkit. Similarly, the NVRTC + // library in CUDA 11.3 and later 11.x releases will have the same soname (Linux) or DLL name (Windows) as the NVRTC library in CUDA 11.2. + constexpr auto major = CUDA_VERSION / 1000; + constexpr auto minor = ( CUDA_VERSION / 10 ) % 10; +#if defined(_WIN32) + if (major < 11 || (major == 11 && minor < 3)) { + return std::to_string(major) + std::to_string(minor); + } else if (major == 11) { + return "112"; + } else { + return std::to_string(major) + "0"; + } +#else + if (major < 11 || (major == 11 && minor < 3)) { + return std::to_string(major) + "." + std::to_string(minor); + } else if (major == 11) { + return "11.2"; + } else { + return std::to_string(major); + } +#endif +} + +static std::string getLibName() { +#if defined(_WIN32) + return std::string("nvrtc64_") + getLibVersion() + "_0.dll"; +#else + return std::string("libnvrtc.so.") + getLibVersion(); +#endif +} + +static std::string getAltLibName() { +#if !defined(_WIN32) && defined(NVRTC_SHORTHASH) + return std::string("libnvrtc-") + C10_STRINGIZE(NVRTC_SHORTHASH) + ".so." + getLibVersion(); +#else + return {}; +#endif +} + +at::DynamicLibrary& getNVRTCLibrary() { + static std::string libname = getLibName(); + static std::string alt_libname = getAltLibName(); + static at::DynamicLibrary lib(libname.c_str(), alt_libname.empty() ? nullptr : alt_libname.c_str()); + return lib; +} + +#define _STUB_1(LIB, NAME, RETTYPE, ARG1) \ +RETTYPE NAME(ARG1 a1) { \ + auto fn = reinterpret_cast(get## LIB ## Library().sym(__func__)); \ + if (!fn) \ + throw std::runtime_error("Can't get " C10_STRINGIZE(NAME) ); \ + lazyNVRTC.NAME = fn; \ + return fn(a1); \ +} + +#define _STUB_2(LIB, NAME, RETTYPE, ARG1, ARG2) \ +RETTYPE NAME(ARG1 a1, ARG2 a2) { \ + auto fn = reinterpret_cast(get## LIB ## Library().sym(__func__)); \ + if (!fn) \ + throw std::runtime_error("Can't get " C10_STRINGIZE(NAME) ); \ + lazyNVRTC.NAME = fn; \ + return fn(a1, a2); \ +} + +#define _STUB_3(LIB, NAME, RETTYPE, ARG1, ARG2, ARG3) \ +RETTYPE NAME(ARG1 a1, ARG2 a2, ARG3 a3) { \ + auto fn = reinterpret_cast(get## LIB ## Library().sym(__func__)); \ + if (!fn) \ + throw std::runtime_error("Can't get " C10_STRINGIZE(NAME) ); \ + lazyNVRTC.NAME = fn; \ + return fn(a1, a2, a3); \ +} + +#define _STUB_4(LIB, NAME, RETTYPE, ARG1, ARG2, ARG3, ARG4) \ +RETTYPE NAME(ARG1 a1, ARG2 a2, ARG3 a3, ARG4 a4) { \ + auto fn = reinterpret_cast(get## LIB ## Library().sym(__func__)); \ + if (!fn) \ + throw std::runtime_error("Can't get " C10_STRINGIZE(NAME) ); \ + lazyNVRTC.NAME = fn; \ + return fn(a1, a2, a3, a4); \ +} + +#define CUDA_STUB1(NAME, A1) _STUB_1(CUDA, NAME, CUresult CUDAAPI, A1) +#define CUDA_STUB2(NAME, A1, A2) _STUB_2(CUDA, NAME, CUresult CUDAAPI, A1, A2) +#define CUDA_STUB3(NAME, A1, A2, A3) _STUB_3(CUDA, NAME, CUresult CUDAAPI, A1, A2, A3) +#define CUDA_STUB4(NAME, A1, A2, A3, A4) _STUB_4(CUDA, NAME, CUresult CUDAAPI, A1, A2, A3, A4) + +#define NVRTC_STUB1(NAME, A1) _STUB_1(NVRTC, NAME, nvrtcResult, A1) +#define NVRTC_STUB2(NAME, A1, A2) _STUB_2(NVRTC, NAME, nvrtcResult, A1, A2) +#define NVRTC_STUB3(NAME, A1, A2, A3) _STUB_3(NVRTC, NAME, nvrtcResult, A1, A2, A3) + +NVRTC_STUB2(nvrtcVersion, int*, int*) +NVRTC_STUB2(nvrtcAddNameExpression, nvrtcProgram, const char * const) + +nvrtcResult nvrtcCreateProgram(nvrtcProgram *prog, + const char *src, + const char *name, + int numHeaders, + const char * const *headers, + const char * const *includeNames) { + auto fn = reinterpret_cast(getNVRTCLibrary().sym(__func__)); + if (!fn) + throw std::runtime_error("Can't get nvrtcCreateProgram"); + lazyNVRTC.nvrtcCreateProgram = fn; + return fn(prog, src, name, numHeaders, headers, includeNames); +} + +NVRTC_STUB1(nvrtcDestroyProgram, nvrtcProgram *) +NVRTC_STUB2(nvrtcGetPTXSize, nvrtcProgram, size_t *) +NVRTC_STUB2(nvrtcGetPTX, nvrtcProgram, char *) +NVRTC_STUB2(nvrtcGetCUBINSize, nvrtcProgram, size_t *) +NVRTC_STUB2(nvrtcGetCUBIN, nvrtcProgram, char *) +NVRTC_STUB3(nvrtcCompileProgram, nvrtcProgram, int, const char * const *) +_STUB_1(NVRTC, nvrtcGetErrorString, const char *, nvrtcResult) +NVRTC_STUB2(nvrtcGetProgramLogSize,nvrtcProgram, size_t*) +NVRTC_STUB2(nvrtcGetProgramLog, nvrtcProgram, char *) +NVRTC_STUB3(nvrtcGetLoweredName, nvrtcProgram, const char *, const char **) + +CUDA_STUB2(cuModuleLoad, CUmodule*, const char*) +CUDA_STUB2(cuModuleLoadData, CUmodule *, const void *) +CUDA_STUB2(cuFuncSetCacheConfig, CUfunction, CUfunc_cache_enum) +CUDA_STUB3(cuDeviceGetAttribute, int*, CUdevice_attribute_enum, CUdevice) +CUDA_STUB2(cuDeviceGet, CUdevice*, int) +CUDA_STUB3(cuModuleGetFunction, CUfunction *, CUmodule, const char *) +CUDA_STUB4(cuOccupancyMaxActiveBlocksPerMultiprocessor, int *, CUfunction, int, size_t) +CUDA_STUB2(cuGetErrorString, CUresult, const char **) +CUDA_STUB1(cuCtxGetCurrent, CUcontext *) +CUDA_STUB1(cuCtxSetCurrent, CUcontext) +CUDA_STUB1(cuModuleUnload, CUmodule) +CUDA_STUB3(cuDevicePrimaryCtxGetState, CUdevice, unsigned int *, int *) +CUDA_STUB2(cuDevicePrimaryCtxRetain, CUcontext *, CUdevice) +CUDA_STUB4(cuLinkCreate, unsigned int, CUjit_option *, void **, CUlinkState *) +CUDA_STUB3(cuLinkComplete, CUlinkState, void **, size_t *) +CUDA_STUB3(cuFuncSetAttribute, CUfunction, CUfunction_attribute, int) +CUDA_STUB3(cuFuncGetAttribute, int*, CUfunction_attribute, CUfunction) +CUDA_STUB3(cuPointerGetAttribute, void*, CUpointer_attribute, CUdeviceptr) + + +#if defined(CUDA_VERSION) +CUresult CUDAAPI +cuTensorMapEncodeTiled( + CUtensorMap* tensorMap, + CUtensorMapDataType tensorDataType, + cuuint32_t tensorRank, + void* globalAddress, + const cuuint64_t* globalDim, + const cuuint64_t* globalStrides, + const cuuint32_t* boxDim, + const cuuint32_t* elementStrides, + CUtensorMapInterleave interleave, + CUtensorMapSwizzle swizzle, + CUtensorMapL2promotion l2Promotion, + CUtensorMapFloatOOBfill oobFill) { + auto fn = reinterpret_cast( + getCUDALibrary().sym(__func__)); + if (!fn) + throw std::runtime_error("Can't get cuTensorMapEncodeTiled"); + lazyNVRTC.cuTensorMapEncodeTiled = fn; + return fn( + tensorMap, + tensorDataType, + tensorRank, + globalAddress, + globalDim, + globalStrides, + boxDim, + elementStrides, + interleave, + swizzle, + l2Promotion, + oobFill); +} + +#endif + +// Irregularly shaped functions +CUresult CUDAAPI cuLaunchKernel(CUfunction f, + unsigned int gridDimX, + unsigned int gridDimY, + unsigned int gridDimZ, + unsigned int blockDimX, + unsigned int blockDimY, + unsigned int blockDimZ, + unsigned int sharedMemBytes, + CUstream hStream, + void **kernelParams, + void **extra) { + auto fn = reinterpret_cast(getCUDALibrary().sym(__func__)); + if (!fn) + throw std::runtime_error("Can't get cuLaunchKernel"); + lazyNVRTC.cuLaunchKernel = fn; + return fn(f, + gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, + sharedMemBytes, hStream, kernelParams, extra); +} + +// Irregularly shaped functions +CUresult CUDAAPI cuLaunchCooperativeKernel( + CUfunction f, + unsigned int gridDimX, + unsigned int gridDimY, + unsigned int gridDimZ, + unsigned int blockDimX, + unsigned int blockDimY, + unsigned int blockDimZ, + unsigned int sharedMemBytes, + CUstream hStream, + void** kernelParams) { + auto fn = reinterpret_cast( + getCUDALibrary().sym(__func__)); + if (!fn) + throw std::runtime_error("Can't get cuLaunchCooperativeKernel"); + lazyNVRTC.cuLaunchCooperativeKernel = fn; + return fn( + f, + gridDimX, + gridDimY, + gridDimZ, + blockDimX, + blockDimY, + blockDimZ, + sharedMemBytes, + hStream, + kernelParams); +} + +CUresult CUDAAPI cuModuleLoadDataEx(CUmodule *module, + const void *image, + unsigned int numOptions, + CUjit_option *options, + void **optionValues) { + auto fn = reinterpret_cast(getCUDALibrary().sym(__func__)); + if (!fn) + throw std::runtime_error("Can't get cuModuleLoadDataEx"); + lazyNVRTC.cuModuleLoadDataEx = fn; + return fn(module, image, numOptions, options, optionValues); +} + +CUresult CUDAAPI +cuLinkAddData(CUlinkState state, + CUjitInputType type, + void *data, + size_t size, + const char *name, + unsigned int numOptions, + CUjit_option *options, + void **optionValues) { + auto fn = reinterpret_cast(getCUDALibrary().sym(__func__)); + if (!fn) + throw std::runtime_error("Can't get cuLinkAddData"); + lazyNVRTC.cuLinkAddData = fn; + return fn(state, type, data, size, name, numOptions, options, optionValues); +} + +} // namespace _stubs + +NVRTC lazyNVRTC = { +#define _REFERENCE_MEMBER(name) _stubs::name, + AT_FORALL_NVRTC(_REFERENCE_MEMBER) +#undef _REFERENCE_MEMBER +}; +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/LazyNVRTC.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/LazyNVRTC.h new file mode 100644 index 0000000000000000000000000000000000000000..23821c88e964ea499df1479a0c369228ba854738 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/LazyNVRTC.h @@ -0,0 +1,11 @@ +#pragma once +#include +namespace at::cuda { +// Forward-declares at::cuda::NVRTC +struct NVRTC; + +namespace detail { +extern NVRTC lazyNVRTC; +} // namespace detail + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/OffsetCalculator.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/OffsetCalculator.cuh new file mode 100644 index 0000000000000000000000000000000000000000..dfda9138c8be13b71854de845d8c22b4df404ffb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/OffsetCalculator.cuh @@ -0,0 +1,136 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +// If element_sizes is nullptr, then the strides will be in bytes, otherwise +// the strides will be in # of elements. +// Operands that share the same shape, but may have different strides. +// OffsetCalculator iterates the tensor in a column-major order + +#if defined(USE_ROCM) +constexpr int MAX_DIMS = 16; +#else +constexpr int MAX_DIMS = 25; +#endif + +template +struct OffsetCalculator { + // We allow having negative strides to implement some operations like torch.flip + using stride_t = std::conditional_t, + index_t>; + // The offset for each argument. Wrapper around fixed-size array. + // On CUDA, zero sized array is not allowed, so when we are handling nullary + // operators, we need to create a size 1 offset to avoid compiler failure. + // This size 1 offset is just a placeholder, and we will not use it. + using offset_type = std::array(NARGS, 1)>; + + // if element_sizes is nullptr, then the strides will be in bytes, otherwise + // the strides will be in # of elements. + OffsetCalculator(int dims, const int64_t* sizes, const int64_t* const* strides, const int64_t* element_sizes=nullptr) : dims(dims) { + TORCH_CHECK(dims <= MAX_DIMS, "tensor has too many (>", MAX_DIMS, ") dims"); + for (int i=0; i < dims; i++){ + sizes_[i] = at::cuda::detail::IntDivider(sizes[i]); + for (int arg = 0; arg < NARGS; arg++) { + int64_t element_size = (element_sizes == nullptr ? 1LL : element_sizes[arg]); + strides_[i][arg] = strides[arg][i] / element_size; + } + } + } + + C10_HOST_DEVICE offset_type get(index_t linear_idx) const { + offset_type offsets; + +#if defined(USE_ROCM) + if ((dims > 0) && (dims <= 2)) { + auto divmod = sizes_[0].divmod(linear_idx); +#pragma unroll + for (int arg = 0; arg < NARGS; arg++) + offsets[arg] = divmod.mod * strides_[0][arg]; + if (dims >= 2) { + divmod = sizes_[1].divmod(divmod.div); +#pragma unroll + for (int arg = 0; arg < NARGS; arg++) + offsets[arg] += divmod.mod * strides_[1][arg]; + } + // [...] + return offsets; + } +#endif + + #pragma unroll + for (int arg = 0; arg < NARGS; arg++) { + offsets[arg] = 0; + } + + #pragma unroll + for (int dim = 0; dim < MAX_DIMS; ++dim) { + if (dim == dims) { + break; + } + auto divmod = sizes_[dim].divmod(linear_idx); + linear_idx = divmod.div; + + #pragma unroll + for (int arg = 0; arg < NARGS; arg++) { + offsets[arg] += divmod.mod * strides_[dim][arg]; + } + + } + return offsets; + } + + int dims; + at::cuda::detail::IntDivider sizes_[MAX_DIMS]; + stride_t strides_[MAX_DIMS][std::max(NARGS, 1)]; +}; + +template +struct TrivialOffsetCalculator { + // The offset for each argument. Wrapper around fixed-size array. + // The offsets are in # of elements, not in bytes. + // On CUDA, zero sized array is not allowed, so when we are handling nullary + // operators, we need to create a size 1 offset to avoid compiler failure. + // This size 1 offset is just a placeholder, and we will not use it. + using offset_type = std::array(NARGS, 1)>; + + C10_HOST_DEVICE offset_type get(index_t linear_idx) const { + offset_type offsets; + #pragma unroll + for (int arg = 0; arg < NARGS; arg++) { + offsets[arg] = linear_idx; + } + return offsets; + } +}; + +// Make an OffsetCalculator with byte offsets +template +static OffsetCalculator make_offset_calculator(const at::TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(N <= iter.ntensors()); + std::array strides; + for (int i = 0; i < N; i++) { + strides[i] = iter.strides(i).data(); + } + return OffsetCalculator(iter.ndim(), iter.shape().data(), strides.data()); +} + +// Make an OffsetCalculator with element offsets +template +static OffsetCalculator make_element_offset_calculator( + const at::TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(N <= iter.ntensors()); + std::array strides; + std::array element_sizes; + for (int i = 0; i < N; i++) { + strides[i] = iter.strides(i).data(); + element_sizes[i] = iter.element_size(i); + } + return OffsetCalculator( + iter.ndim(), iter.shape().data(), strides.data(), element_sizes.data()); +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/PhiloxCudaStateRaw.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/PhiloxCudaStateRaw.cuh new file mode 100644 index 0000000000000000000000000000000000000000..bdfb55dc0cc94fcf815322291431be3682c8856f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/PhiloxCudaStateRaw.cuh @@ -0,0 +1,43 @@ +// No "#pragma once" because this is a raw definition that can be copied by jit codegen. +// Eager mode clients should not include this file directly, instead, +// they should #include , which has a #pragma once. + +// Stores RNG state values. Passed as a kernel argument. +// See Note [CUDA Graph-safe RNG states]. +// +// The raw definition lives in its own file so jit codegen can easily copy it. +namespace at { + +struct PhiloxCudaState { + PhiloxCudaState() = default; + // Called if graph capture is not underway + PhiloxCudaState(uint64_t seed, + uint64_t offset) { + seed_.val = seed; + offset_.val = offset; + } + // Called if graph capture is underway + PhiloxCudaState(int64_t* seed, + int64_t* offset_extragraph, + uint64_t offset_intragraph) { + seed_.ptr = seed; + offset_.ptr = offset_extragraph; + offset_intragraph_ = offset_intragraph; + captured_ = true; + } + + // Public members, directly accessible by at::cuda::philox::unpack. + // If we made them private with getters/setters, the getters/setters + // would have to be __device__, and we can't declare __device__ in ATen. + union Payload { + uint64_t val; + int64_t* ptr; + }; + + Payload seed_{}; + Payload offset_{}; + uint64_t offset_intragraph_ = 0; + bool captured_ = false; +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/ROCmMacros.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/ROCmMacros.cuh new file mode 100644 index 0000000000000000000000000000000000000000..0e775f5ba8cd6a8abc79a3af762a533b127af822 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/ROCmMacros.cuh @@ -0,0 +1,19 @@ +#pragma once + +#if defined(USE_ROCM) + +#if !__has_builtin(__builtin_amdgcn_processor_is) + #if defined(__amdgcn_processor__) + // Device pass: __amdgcn_processor__ is available + #define __builtin_amdgcn_processor_is(x) (__builtin_strcmp(x, __amdgcn_processor__) == 0) + #else + // Host pass: define a no-op fallback so the macro always exists + #define __builtin_amdgcn_processor_is(x) false + #endif // defined(__amdgcn_processor__) +#endif // !__has_builtin(__builtin_amdgcn_processor_is) + +#if !__has_builtin(__builtin_amdgcn_is_invocable) + #define __builtin_amdgcn_is_invocable(x) (__has_builtin(x)) +#endif + +#endif // defined(USE_ROCM) diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/TensorInfo.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/TensorInfo.cuh new file mode 100644 index 0000000000000000000000000000000000000000..c674922ec14cd6d3cf2177e9688653f03d95a0a3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/TensorInfo.cuh @@ -0,0 +1,116 @@ +#pragma once + +#include + +namespace at::cuda::detail { + +#define MAX_TENSORINFO_DIMS 25 + +// CUDA kernel argument that defines tensor layout +template +struct TensorInfo { + TensorInfo(); + TensorInfo(T* p, + int dim, + IndexType sz[MAX_TENSORINFO_DIMS], + IndexType st[MAX_TENSORINFO_DIMS]); + + // Set the size of the given dimension to 1, as if it were a + // reduction dim (allows you to calculate offsets of the reduction + // slice) + void reduceDim(int dim); + + // See note on [collapse dims]. + int collapseDims(const int excludeDim = -1); + + // Contiguous tensors of more than one dimension are collapsed down + // to one tensor + __host__ __device__ inline bool isContiguous() const { + return (dims == 1 && strides[0] == 1); + } + + T* data; + IndexType sizes[MAX_TENSORINFO_DIMS]; + IndexType strides[MAX_TENSORINFO_DIMS]; + int dims; +}; + +template +TensorInfo::TensorInfo() { + data = nullptr; + dims = 0; +} + +template +TensorInfo::TensorInfo(T* p, + int dim, + IndexType sz[MAX_TENSORINFO_DIMS], + IndexType st[MAX_TENSORINFO_DIMS]) { + data = p; + dims = dim; + TORCH_CHECK(dims < MAX_TENSORINFO_DIMS, "CUDA Tensors cannot have more than 25 dimensions"); + + for (int i = 0; i < dim; ++i) { + sizes[i] = sz[i]; + strides[i] = st[i]; + } +} + +template +void +TensorInfo::reduceDim(int dim) { + TORCH_CHECK(dim < dims && dim >= 0, "expected dim between 0 and dims - 1"); + sizes[dim] = 1; +} + +template +int +TensorInfo::collapseDims(const int excludeDim) { + auto result = at::collapse_dims(sizes, strides, dims, excludeDim); + dims = std::get<1>(result); + return std::get<0>(result); +} + +// Translate a linear index for the apply to a T* offset; +// specialized on `Dims` to reduce nvcc compilation time +template +struct IndexToOffset { + static __host__ __device__ IndexType get( + IndexType linearId, + const TensorInfo& info) { + + IndexType offset = 0; + + // Uses static dims + for (int i = Dims - 1; i > 0; --i) { + IndexType curDimIndex = linearId % info.sizes[i]; + IndexType curDimOffset = curDimIndex * info.strides[i]; + offset += curDimOffset; + linearId /= info.sizes[i]; + } + + return offset + linearId * info.strides[0]; + } +}; + +// Uses dynamic (runtime) instead of static (compile time) dims +template +struct IndexToOffset { + static inline __host__ __device__ IndexType get( + IndexType linearId, + const TensorInfo& info) { + + IndexType offset = 0; + + for (int i = info.dims - 1; i > 0; --i) { + IndexType curDimIndex = linearId % info.sizes[i]; + IndexType curDimOffset = curDimIndex * info.strides[i]; + offset += curDimOffset; + linearId /= info.sizes[i]; + } + + return offset + linearId * info.strides[0]; + } +}; + +} // namespace at::cuda::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/UnpackRaw.cuh b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/UnpackRaw.cuh new file mode 100644 index 0000000000000000000000000000000000000000..2548733f01042a5bebcd02690a77b6349e237ac5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/detail/UnpackRaw.cuh @@ -0,0 +1,34 @@ +// No "#pragma once" because this is a raw definition that can be copied by jit codegen. +// Eager mode clients should not include this file directly, instead, +// they should #include , which has a #pragma once. + +namespace at::cuda::philox { + +// In-kernel call to retrieve philox seed and offset from a PhiloxCudaState instance whether +// that instance was created with graph capture underway or not. +// See Note [CUDA Graph-safe RNG states]. +// +// We can't write a __device__ function in CUDAGeneratorImpl.h, because it's in ATen. +// Also, whatever call unpacks PhiloxCudaState in consumer kernels must be inlineable. +// Easiest thing that comes to mind is, define a __device__ unpack helper here, in ATen/cuda. +// +// The raw definition lives in its own file so jit codegen can easily copy it. +__host__ __device__ __forceinline__ std::tuple +unpack(at::PhiloxCudaState arg) { + if (arg.captured_) { + // static_cast avoids "warning: invalid narrowing conversion from "long" to "unsigned long". + // *(arg.offset_.ptr) is a broadcast load of a single int64_t to the entire kernel. + // For most threads' reads it will hit in cache, so it shouldn't hurt performance. + return std::make_tuple(static_cast(*arg.seed_.ptr), static_cast(*(arg.offset_.ptr) + arg.offset_intragraph_)); + } else { + return std::make_tuple(arg.seed_.val, arg.offset_.val); + } +} + +// Adapted from TE +// extract seed and offset from PhiloxCudaState +__global__ void unpack_cudnn(at::PhiloxCudaState arg, int64_t* seed_ptr, int64_t* offset_ptr); + +void unpack_cudnn_wrapper(at::PhiloxCudaState arg, int64_t* seed_ptr, int64_t* offset_ptr, cudaStream_t stream); + +} // namespace at::cuda::philox diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator.cu b/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator.cu new file mode 100644 index 0000000000000000000000000000000000000000..14366a887beb30fdd09d827ab884b8656dc3f08a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator.cu @@ -0,0 +1,371 @@ +#include + +#if AT_USE_JITERATOR() + +#include +#include +#include + +#include +#include +namespace at { +namespace native { + +static inline void launch_jitted_vectorized_kernel_dynamic( + const std::string& name, TensorIteratorBase& iter, + DeviceIndex dev_idx, int64_t N, const std::string& f, const void* data_ptr, + const c10::SmallVector& extra_args, bool return_by_ref) { + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + + int nInputs = iter.ninputs(); + int nOutputs = iter.noutputs(); + const at::ScalarType common_dtype = iter.common_dtype(); + + int tws = at::cuda::jit::calc_thread_work_size(nInputs, nOutputs, common_dtype, common_dtype); + int vec_size = jitted_can_vectorize_up_to(iter); + + int bws = tws * num_threads(); + // N is still int64_t for the computation, but it's always safe to cast result to int + const uint32_t grid = (N + bws - 1) / bws; + + bool vectorized = vec_size > 1; + + // Different kernels are compiled depending on what we're vectorizing up to (1, 2 or 4 elements) + // fn_ptr is set to the appropriate function based on the vec size and GPU used + // TODO: Memory use can probably be optimized by reusing kernels across GPUs with + // the same compute capability + + std::string f_inputs_type_str = at::cuda::jit::typeName(common_dtype); + std::string compute_type_str = at::cuda::jit::typeName(toOpMathType(common_dtype)); + std::string result_type_str = at::cuda::jit::typeName(common_dtype); + c10::SmallVector extra_args_types = get_extra_args_typenames(extra_args); + + // The cache key includes all the parameters to generate_code + vec_size + dev_idx + std::stringstream ss; + ss << nInputs << '_' << nOutputs << f; + ss << f_inputs_type_str << compute_type_str << result_type_str; + ss << static_cast(at::cuda::jit::BinaryFuncVariant::NoScalar); + ss << extra_args_types; + ss << vec_size; +// DeviceIndex, e.g. int8_t, is not treated as a number by the stream, cast to int as a workaround + ss << static_cast(dev_idx); + const std::string cache_key = std::move(ss).str(); + + static std::mutex _jiterator_mutex; + static std::unordered_map fns; + at::cuda::jit::NvrtcFunction* fn_ptr = &fns[cache_key]; + + if (!fn_ptr->function) { + const std::lock_guard lock{_jiterator_mutex}; + if (!fn_ptr->function) { // cache miss! + // Generates program + auto code = at::cuda::jit::generate_code(nInputs, nOutputs, f, name, + f_inputs_type_str, compute_type_str, result_type_str, + /*contiguous=*/true, /*dynamic_casting=*/false, + at::cuda::jit::BinaryFuncVariant::NoScalar, + extra_args_types, + tws, + vectorized, vec_size, + return_by_ref); + std::string kernel_name = vectorized ? name + "_vectorized" + std::to_string(vec_size) : name; + // Acquires the program + *fn_ptr = at::cuda::jit::jit_pwise_function(code, kernel_name); + } + } + + // size of `extra_args` is unknown at compile-time + auto extra_args_size = extra_args.size(); + + float scalar_val = 0; + + if (vectorized) { + // pack args for kernel launch + constexpr int kernel_args = 3; + auto args = std::make_unique(kernel_args + extra_args_size); + args[0] = &N; + args[1] = data_ptr; + args[2] = &scalar_val; + + for (const auto i : c10::irange(extra_args_size)) { + // since 3 slots are already filled in `args` + args[i + 3] = extra_args[i].data_ptr(); + } + at::cuda::jit::launch_jitted_pwise_function(*fn_ptr, args.get(), {grid, 1u, 1u}, {num_threads(), 1u, 1u}); + } else { + TrivialOffsetCalculatorVariant input_offset_calculator(iter.ninputs()); + void* ic_ptr = input_offset_calculator.data_ptr(); + TrivialOffsetCalculatorVariant output_offset_calculator(iter.noutputs()); + void* oc_ptr = output_offset_calculator.data_ptr(); + + auto l = memory::LoadWithoutCast(); + auto s = memory::StoreWithoutCast(); + + // pack args for kernel launch + constexpr int kernel_args = 7; + auto args = std::make_unique(kernel_args + extra_args_size); + args[0] = &N; + args[1] = data_ptr; + args[2] = ic_ptr; + args[3] = oc_ptr; + args[4] = &l; + args[5] = &s; + args[6] = &scalar_val; + + for (const auto i : c10::irange(extra_args_size)) { + // since 7 slots are already filled in `args` + args[i + 7] = extra_args[i].data_ptr(); + } + + at::cuda::jit::launch_jitted_pwise_function(*fn_ptr, args.get(), {grid, 1u, 1u}, {num_threads(), 1u, 1u}); + } +} + +static inline void launch_jitted_unrolled_kernel_dynamic( + const std::string& name, TensorIteratorBase& iter, + DeviceIndex dev_idx, int64_t N, const std::string& f, const void* data_ptr, + const void* ic_ptr, const void* oc_ptr, const void* l_ptr, const void* s_ptr, bool contiguous, bool dynamic_casting, + const c10::SmallVector& extra_args, bool return_by_ref) { + + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + + int nInputs = iter.ninputs(); + int nOutputs = iter.noutputs(); + const at::ScalarType common_dtype = iter.common_dtype(); + + int tws = at::cuda::jit::calc_thread_work_size(nInputs, nOutputs, common_dtype, common_dtype); + int bws = tws * num_threads(); + //casting result to int is always safe, intermediate is int64 and won't overflow + const uint32_t grid = (N + bws - 1) / bws; + + std::string f_inputs_type_str = at::cuda::jit::typeName(common_dtype); + std::string compute_type_str = at::cuda::jit::typeName(toOpMathType(common_dtype)); + std::string result_type_str = at::cuda::jit::typeName(common_dtype); + c10::SmallVector extra_args_types = get_extra_args_typenames(extra_args); + + // The cache key includes all the parameters to generate_code + dev_idx + std::stringstream ss; + ss << nInputs << '_' << nOutputs << f; + ss << f_inputs_type_str << compute_type_str << result_type_str; + ss << contiguous << dynamic_casting; + ss << static_cast(at::cuda::jit::BinaryFuncVariant::NoScalar); + ss << extra_args_types; + ss << dev_idx; + const std::string cache_key = std::move(ss).str(); + + static std::mutex _jiterator_mutex; + static std::unordered_map fns; + + at::cuda::jit::NvrtcFunction* fn_ptr = &fns[cache_key]; + if (!fn_ptr->function) { + const std::lock_guard lock{_jiterator_mutex}; + if (!fn_ptr->function) { + auto code = at::cuda::jit::generate_code(nInputs, nOutputs, f, name, + f_inputs_type_str, compute_type_str, result_type_str, + contiguous, dynamic_casting, + at::cuda::jit::BinaryFuncVariant::NoScalar, + extra_args_types, tws, /*vectorized*/false, /*vec_size*/0, return_by_ref); + *fn_ptr = at::cuda::jit::jit_pwise_function(code, name); + } + } + + float scalar_val = 0; + + // pack args for kernel launch + constexpr int kernel_args = 7; + auto extra_args_size = extra_args.size(); + auto args = std::make_unique(kernel_args + extra_args_size); + args[0] = &N; + args[1] = data_ptr; + args[2] = ic_ptr; + args[3] = oc_ptr; + args[4] = l_ptr; + args[5] = s_ptr; + args[6] = &scalar_val; + + for (const auto i : c10::irange(extra_args_size)) { + // since 7 slots are already filled in `args` + args[i + 7] = extra_args[i].data_ptr(); + } + + at::cuda::jit::launch_jitted_pwise_function(*fn_ptr, args.get(), {grid, 1u, 1u}, {num_threads(), 1u, 1u}); +} + +static void jitted_gpu_kernel_dynamic_impl( + const std::string& kernel_name, + TensorIteratorBase& iter, + const std::string& f, + const bool dynamic_casting, + const c10::SmallVector& extra_args, + bool return_by_ref) { + + TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing()); + TORCH_INTERNAL_ASSERT(iter.noutputs() <= 8); + TORCH_INTERNAL_ASSERT(iter.ninputs() <= 8); + + ArrayVariant data(iter); + const void* data_ptr = data.data_ptr(); + + int64_t numel = iter.numel(); + bool contiguous = iter.is_contiguous(); + + // Decides which of 4 kernel types to launch + // Variations are: + // - Case 1: no dynamic casting and contiguous + // - Case 2: no dynamic casting and noncontiguous + // - Case 3: dynamic casting and contiguous + // - Case 4: dynamic casting and noncontiguous + // These cases align with the non-jitted CUDALoops.cuh cases in gpu_kernel_impl + + if (!dynamic_casting) { + if (contiguous) { + // Case 1: no dynamic casting and contiguous + launch_jitted_vectorized_kernel_dynamic(kernel_name, iter, + iter.device().index(), numel, f, data_ptr, extra_args, return_by_ref); + return; + } + + // Case 2: no dynamic casting and noncontiguous + OffsetCalculatorVariant input_offset_calculator(iter); + const void* ic_ptr = input_offset_calculator.data_ptr(); + OffsetCalculatorVariant output_offset_calculator(iter); + const void* oc_ptr = output_offset_calculator.data_ptr(); + + auto loader = memory::LoadWithoutCast(); + auto storer = memory::StoreWithoutCast(); + const void* l_ptr = &loader; + const void* s_ptr = &storer; + + launch_jitted_unrolled_kernel_dynamic( + kernel_name, iter, iter.device().index(), numel, f, data_ptr, + ic_ptr, oc_ptr, l_ptr, s_ptr, contiguous, dynamic_casting, extra_args, return_by_ref); + + return; + } + + // Cases 3 and 4 are handled below + // Both require construction of one or more storers and loaders + + // Creates load casts from inputs (note offset indexing into the iterators noutpus...n tensors) + LoadWithCastVariant loader(iter); + void* l_ptr = loader.data_ptr(); + + // Creates store cast to output (the 0...noutpus-1 tensor in TensorIterator) + StoreWithCastVariant storer(iter); + void* s_ptr = storer.data_ptr(); + + if (contiguous) { + // Case 3: dynamic casting and contiguous + TrivialOffsetCalculatorVariant input_offset_calculator(iter.ninputs()); + void* ic_ptr = input_offset_calculator.data_ptr(); + TrivialOffsetCalculatorVariant output_offset_calculator(iter.noutputs()); + void* oc_ptr = output_offset_calculator.data_ptr(); + + launch_jitted_unrolled_kernel_dynamic( + kernel_name, iter, iter.device().index(), numel, f, data_ptr, + ic_ptr, oc_ptr, l_ptr, s_ptr, contiguous, dynamic_casting, extra_args, return_by_ref); + return; + } + + // Case 4: dynamic casting and noncontiguous + OffsetCalculatorVariant input_offset_calculator(iter); + void* ic_ptr = input_offset_calculator.data_ptr(); + OffsetCalculatorVariant output_offset_calculator(iter); + void* oc_ptr = output_offset_calculator.data_ptr(); + + launch_jitted_unrolled_kernel_dynamic( + kernel_name, iter, iter.device().index(), numel, f, data_ptr, + ic_ptr, oc_ptr, l_ptr, s_ptr, contiguous, dynamic_casting, extra_args, return_by_ref); +} + +// Entrypoint for dynamic version of jitted GPU kernels, which accepts dynamic number of inputs +// and arbitrary types of input and extra args. This dynamic version is needed for jiterator with python interface, +// since the kernel definition is unknown at the compilation time. +// Similarly, launch_jitted_vectorized_kernel_dynamic and launch_jitted_unrolled_kernel_dynamic are created +// to handle arbitrary functions defined in python user code. +// For templated version, see note [Jiterator] in JitLoops.cuh for more details +static void jitted_gpu_kernel_dynamic( + const std::string& kernel_name, + TensorIteratorBase& iter, + const std::string& f, + const c10::SmallVector& extra_args, + bool return_by_ref) { + + // TODO: much of preamble is common to both jitted_gpu_kernel and gpu_kernel + // Maybe it could be refactored? + for (int arg = 0; arg < iter.ntensors(); arg++) { + TORCH_INTERNAL_ASSERT( + iter.device(arg).is_cuda(), + "argument ", arg, ": expected a CUDA device but found ", iter.device(arg)); + } + + if (iter.numel() == 0) { + return; + } + + if (!iter.can_use_32bit_indexing()) { + for (auto& sub_iter : iter.with_32bit_indexing()) { + jitted_gpu_kernel_dynamic(kernel_name, sub_iter, f, extra_args, return_by_ref); + } + return; + } + + // Computes if dynamic casting is needed + // Dynamic casting is needed if an input's or output's dtype differs from the common dtype + bool needs_dynamic_casting = false; + const at::ScalarType common_dtype = iter.common_dtype(); + for (auto i = 0; i < iter.ntensors(); ++i) { + if (iter.dtype(i) != common_dtype) { + needs_dynamic_casting = true; + break; + } + } + + jitted_gpu_kernel_dynamic_impl(kernel_name, iter, f, needs_dynamic_casting, extra_args, return_by_ref); +} + +} // namespace native + +namespace cuda { + +c10::SmallVector CompileAndLaunchKernel( + const std::string& code_string, + const std::string& kernel_name, + const int num_outputs, + const c10::SmallVector& tensors, + const c10::SmallVector& extra_args, + bool return_by_ref) { + + c10::SmallVector outs(num_outputs); + TensorIteratorConfig config; + config + .set_check_mem_overlap(true) + .allow_cpu_scalars(false) + .promote_inputs_to_common_dtype(true) + .cast_common_dtype_to_outputs(true) + .enforce_safe_casting_to_output(true) + .check_all_same_device(true); + for (int i = 0; i < num_outputs; ++i) { + config.add_owned_output(outs[i]); + } + for (const auto& t: tensors) { + config.add_const_input(t); + } + TensorIterator iter = config.build(); + + CUDAGuard guard(iter.device()); + at::native::jitted_gpu_kernel_dynamic(kernel_name, iter, code_string, extra_args, return_by_ref); + + c10::SmallVector outputs; + if (num_outputs > 0) { + outputs.reserve(num_outputs); + } + for (int i = 0; i < num_outputs; ++i) { + outputs.emplace_back(iter.output(i)); + } + + return outputs; +} + +}} // namespace at::cuda + +#endif // AT_USE_JITERATOR() diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator.h new file mode 100644 index 0000000000000000000000000000000000000000..5e67b0f83c5d8a52cb1534bdbc7879138b53bdf9 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator.h @@ -0,0 +1,40 @@ +#pragma once +#include + +#if AT_USE_JITERATOR() + +#include +#include +#include + +#include +#include + +namespace at::cuda { + +TORCH_CUDA_CPP_API c10::SmallVector CompileAndLaunchKernel( + const std::string& code_string, + const std::string& kernel_name, + const int num_outputs, + const c10::SmallVector& tensors, + const c10::SmallVector& extra_args, + bool return_by_ref); + +} // namespace at::cuda + +#else + +namespace at::cuda { + +TORCH_CUDA_CPP_API c10::SmallVector CompileAndLaunchKernel( + const std::string& code_string, + const std::string& kernel_name, + const int num_outputs, + const c10::SmallVector& tensors, + const c10::SmallVector& extra_args, + bool return_by_ref) { + TORCH_CHECK(false, "Jiterator is not supported"); + } +} // namespace at::cuda + +#endif // AT_USE_JITERATOR() diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator_impl.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..5cc5913d155818622ef81b8969eda6c3f6a895e7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/jiterator_impl.h @@ -0,0 +1,252 @@ +#pragma once +#include + +#if AT_USE_JITERATOR() + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace at::native { + + +#define AT_FOR_8_CASES(_) \ + _(1) \ + _(2) \ + _(3) \ + _(4) \ + _(5) \ + _(6) \ + _(7) \ + _(8) + +#define AT_FOR_8_CASES_WITH_COMMA(_) \ + _(1) , \ + _(2) , \ + _(3) , \ + _(4) , \ + _(5) , \ + _(6) , \ + _(7) , \ + _(8) + +c10::SmallVector get_extra_args_typenames(const c10::SmallVector& extra_args) { + c10::SmallVector args_typenames(extra_args.size()); + for (const auto i : c10::irange(extra_args.size())) { + args_typenames[i] = at::cuda::jit::typeName(extra_args[i].type()); + } + return args_typenames; +} + +int can_vectorize_up_to(at::ScalarType type, char* pointer) { + switch(type) { +#define DEFINE_CASE(ctype, scalartype) \ + case scalartype : return memory::can_vectorize_up_to(pointer); + + AT_FORALL_SCALAR_TYPES_V2( + AT_WRAP(DEFINE_CASE), + AT_EXPAND(AT_ALL_SCALAR_TYPES_WITH_COMPLEX)) +#undef DEFINE_CASE + + default: TORCH_INTERNAL_ASSERT(false, "Unrecognized ScalarType: ", type); + } +} + +// jitted version of the above +// See Note [Jiterator], this relies on the assumptions enumerated there +int jitted_can_vectorize_up_to(const TensorIteratorBase& iter) { + const at::ScalarType common_dtype = iter.common_dtype(); + const at::ScalarType result_dtype = common_dtype; + + // Deals with output + int result = can_vectorize_up_to(result_dtype, static_cast(iter.data_ptr(0))); + + // Incorporates input(s) + for (auto i = 1; i < iter.ntensors(); ++i) { + result = std::min(result, can_vectorize_up_to(common_dtype, static_cast(iter.data_ptr(i)))); + } + + return result; +} + +template +static std::unique_ptr> make_unique_offset_calculator( + const TensorIteratorBase& iter) { + // array size can not be 0, this happens when N == 0 + constexpr int array_size = std::max(N, 1); + TORCH_INTERNAL_ASSERT(N == (IS_INPUT ? iter.ninputs() : iter.noutputs())); + + std::array strides; + int64_t element_sizes[array_size]; + for (int i = 0; i < N; i++) { + int index = IS_INPUT ? i + iter.noutputs() : i; + strides[i] = iter.strides(index).data(); + element_sizes[i] = iter.element_size(index); + } + return std::make_unique>(iter.ndim(), iter.shape().data(), strides.data(), element_sizes); +} + +template +struct OffsetCalculatorVariant { +#define DEFINE_CASE(index) std::unique_ptr> + using OffsetCalculatorTypes = std::variant< + AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE) + >; +#undef DEFINE_CASE + + OffsetCalculatorVariant(const TensorIteratorBase& iter) { + int num = IS_INPUT ? iter.ninputs() : iter.noutputs(); + + switch(num) { +#define DEFINE_CASE(index) \ + case index : v = make_unique_offset_calculator(iter); break; + + AT_FOR_8_CASES(DEFINE_CASE) +#undef DEFINE_CASE + default: + TORCH_CHECK(false, "OffsetCalculatorVariant is not implemented for num_tensor = ", num); + } + } + + void* data_ptr() { + return std::visit([](auto & v){ return static_cast(v.get()); }, v); + } + + private: + OffsetCalculatorTypes v{}; +}; + +struct ArrayVariant { +// works for up to 8 input + 8 outputs +#define DEFINE_CASE(index) std::array, std::array + using ArrayTypes = std::variant< + AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE) + >; +#undef DEFINE_CASE + + ArrayVariant(const TensorIteratorBase& iter) { + int ntensors = iter.ntensors(); + switch(ntensors) { +#define DEFINE_CASE(index) \ + case index: array = std::array{}; break; \ + case index+8: array = std::array{}; break; + + AT_FOR_8_CASES(DEFINE_CASE) +#undef DEFINE_CASE + + default: + TORCH_CHECK(false, "ArrayVariant is not implemented for ntensors = ", ntensors); + } + + std::visit([&](auto& a) { + for (auto i = 0; i < ntensors; ++i) { + a[i] = (char*)iter.data_ptr(i); + } + }, array); + } + + void* data_ptr() { + return std::visit([](auto & a){ return static_cast(&a); }, array); + } + +private: + ArrayTypes array; +}; + +struct TrivialOffsetCalculatorVariant { +#define DEFINE_CASE(index) TrivialOffsetCalculator + using TrivialOffsetCalculatorTypes = std::variant< + AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE) + >; +#undef DEFINE_CASE + + TrivialOffsetCalculatorVariant(int num) { + switch(num) { +#define DEFINE_CASE(index) \ + case index: v = TrivialOffsetCalculator(); break; + + AT_FOR_8_CASES(DEFINE_CASE) +#undef DEFINE_CASE + + default: + TORCH_CHECK(false, "TrivialOffsetCalculatorVariant is not implemented for num_tensors = ", num); + } + } + + void* data_ptr() { + return std::visit([](auto & v){ return static_cast(&v); }, v); + } + +private: + TrivialOffsetCalculatorTypes v{}; +}; + +struct LoadWithCastVariant { +#define DEFINE_CASE(index) std::unique_ptr> + using LoadWithCastPtr = std::variant< + AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE) + >; +#undef DEFINE_CASE + + LoadWithCastVariant(const TensorIteratorBase& iter) { + int arity = iter.ninputs(); + switch(arity) { +#define DEFINE_CASE(index) \ + case index: v = std::make_unique>(iter); break; + + AT_FOR_8_CASES(DEFINE_CASE) +#undef DEFINE_CASE + + default: + TORCH_CHECK(false, "LoadWithCastVariant is not implemented for ninputs = ", arity); + } + } + + void* data_ptr() { + return std::visit([](auto & v){ return static_cast(v.get()); }, v); + } + +private: + LoadWithCastPtr v{}; +}; + +struct StoreWithCastVariant { +#define DEFINE_CASE(index) std::unique_ptr> + using StoreWithCastPtr = std::variant< + AT_FOR_8_CASES_WITH_COMMA(DEFINE_CASE) + >; +#undef DEFINE_CASE + + StoreWithCastVariant(const TensorIteratorBase& iter) { + int num = iter.noutputs(); + switch(num) { +#define DEFINE_CASE(index) \ + case index: v = std::make_unique>(iter); break; + + AT_FOR_8_CASES(DEFINE_CASE) +#undef DEFINE_CASE + + default: + TORCH_CHECK(false, "StoreWithCastVariant is not implemented for noutputs = ", num); + } + } + + void* data_ptr() { + return std::visit([](auto & v){ return static_cast(v.get()); }, v); + } + +private: + StoreWithCastPtr v{}; +}; + +} // namespace at::native + + +#endif // AT_USE_JITERATOR() diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_basic.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_basic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d52eaea4d3942171c7c554a3a5b79f160b5f3080 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_basic.cpp @@ -0,0 +1,323 @@ +// This file is modified from LLVM, see the following copyright information +// +// -*- C++ -*- +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include +#include + +namespace at::cuda { + +// copy-pasted from some llvm files: +// - https://github.com/llvm/llvm-project/blob/main/libcxx/include/type_traits +// - https://github.com/llvm/llvm-project/blob/main/clang/test/Headers/Inputs/include/type_traits +const std::string traits = R"ESCAPE( + +namespace std { + +template +_Tp&& __declval(int); +template +_Tp __declval(long); +template +decltype(__declval<_Tp>(0)) declval() noexcept; + +template +struct integral_constant { + static const _Tp value = __v; + typedef _Tp value_type; + typedef integral_constant type; +}; + +typedef integral_constant true_type; +typedef integral_constant false_type; + +// is_same, functional +template struct is_same : public false_type {}; +template struct is_same<_Tp, _Tp> : public true_type {}; + +// is_integral, for some types. +template struct is_integral + : public integral_constant {}; +template <> struct is_integral + : public integral_constant {}; +template <> struct is_integral + : public integral_constant {}; +template <> struct is_integral + : public integral_constant {}; +template <> struct is_integral + : public integral_constant {}; +template <> struct is_integral + : public integral_constant {}; +template <> struct is_integral + : public integral_constant {}; + +// enable_if, functional +template struct enable_if{}; +template struct enable_if{ + using type = _Tp; +}; +template +using enable_if_t = typename enable_if::type; + +template struct remove_const {typedef _Tp type;}; +template struct remove_const {typedef _Tp type;}; +template using remove_const_t = typename remove_const<_Tp>::type; + +template struct remove_volatile {typedef _Tp type;}; +template struct remove_volatile {typedef _Tp type;}; +template using remove_volatile_t = typename remove_volatile<_Tp>::type; + +template struct remove_cv +{typedef typename remove_volatile::type>::type type;}; +template using remove_cv_t = typename remove_cv<_Tp>::type; + +template struct __libcpp_is_floating_point : public false_type {}; +template <> struct __libcpp_is_floating_point : public true_type {}; +template <> struct __libcpp_is_floating_point : public true_type {}; +template <> struct __libcpp_is_floating_point : public true_type {}; + +template struct is_floating_point + : public __libcpp_is_floating_point::type> {}; + +template struct is_arithmetic + : public integral_constant::value || + is_floating_point<_Tp>::value> {}; +template +inline constexpr bool is_arithmetic_v = is_arithmetic<_Tp>::value; + +template +struct __numeric_type +{ + static void __test(...); + static float __test(float); + static double __test(char); + static double __test(int); + static double __test(unsigned); + static double __test(long); + static double __test(unsigned long); + static double __test(long long); + static double __test(unsigned long long); + static double __test(double); + static long double __test(long double); + + typedef decltype(__test(declval<_Tp>())) type; + static const bool value = !is_same::value; +}; + +template <> +struct __numeric_type +{ + static const bool value = true; +}; + +// __promote + +template ::value && + __numeric_type<_A2>::value && + __numeric_type<_A3>::value> +class __promote_imp +{ +public: + static const bool value = false; +}; + +template +class __promote_imp<_A1, _A2, _A3, true> +{ +private: + typedef typename __promote_imp<_A1>::type __type1; + typedef typename __promote_imp<_A2>::type __type2; + typedef typename __promote_imp<_A3>::type __type3; +public: + typedef decltype(__type1() + __type2() + __type3()) type; + static const bool value = true; +}; + +template +class __promote_imp<_A1, _A2, void, true> +{ +private: + typedef typename __promote_imp<_A1>::type __type1; + typedef typename __promote_imp<_A2>::type __type2; +public: + typedef decltype(__type1() + __type2()) type; + static const bool value = true; +}; + +template +class __promote_imp<_A1, void, void, true> +{ +public: + typedef typename __numeric_type<_A1>::type type; + static const bool value = true; +}; + +template +class __promote : public __promote_imp<_A1, _A2, _A3> {}; + +} // namespace std + +)ESCAPE"; + +const std::string &get_traits_string() { + return traits; +} + +// This is copy-pasted from the following llvm file: +// - https://github.com/llvm/llvm-project/blob/main/libcxx/include/cmath +const std::string cmath = R"ESCAPE( + +namespace std { + +using ::signbit; +using ::isfinite; +using ::isinf; +using ::isnan; + +using ::abs; + +using ::acos; +using ::acosf; +using ::asin; +using ::asinf; +using ::atan; +using ::atanf; +using ::atan2; +using ::atan2f; +using ::ceil; +using ::ceilf; +using ::cos; +using ::cosf; +using ::cosh; +using ::coshf; + +using ::exp; +using ::expf; + +using ::fabs; +using ::fabsf; +using ::floor; +using ::floorf; + +using ::fmod; +using ::fmodf; + +using ::frexp; +using ::frexpf; +using ::ldexp; +using ::ldexpf; + +using ::log; +using ::logf; + +using ::log10; +using ::log10f; +using ::modf; +using ::modff; + +using ::pow; +using ::powf; + +using ::sin; +using ::sinf; +using ::sinh; +using ::sinhf; + +using ::sqrt; +using ::sqrtf; +using ::tan; +using ::tanf; + +using ::tanh; +using ::tanhf; + +using ::acosh; +using ::acoshf; +using ::asinh; +using ::asinhf; +using ::atanh; +using ::atanhf; +using ::cbrt; +using ::cbrtf; + +using ::copysign; +using ::copysignf; + +using ::erf; +using ::erff; +using ::erfc; +using ::erfcf; +using ::exp2; +using ::exp2f; +using ::expm1; +using ::expm1f; +using ::fdim; +using ::fdimf; +using ::fmaf; +using ::fma; +using ::fmax; +using ::fmaxf; +using ::fmin; +using ::fminf; +using ::hypot; +using ::hypotf; +using ::ilogb; +using ::ilogbf; +using ::lgamma; +using ::lgammaf; +using ::llrint; +using ::llrintf; +using ::llround; +using ::llroundf; +using ::log1p; +using ::log1pf; +using ::log2; +using ::log2f; +using ::logb; +using ::logbf; +using ::lrint; +using ::lrintf; +using ::lround; +using ::lroundf; + +using ::nan; +using ::nanf; + +using ::nearbyint; +using ::nearbyintf; +using ::nextafter; +using ::nextafterf; +using ::remainder; +using ::remainderf; +using ::remquo; +using ::remquof; +using ::rint; +using ::rintf; +using ::round; +using ::roundf; +using ::scalbln; +using ::scalblnf; +using ::scalbn; +using ::scalbnf; +using ::tgamma; +using ::tgammaf; +using ::trunc; +using ::truncf; + +} // namespace std + +)ESCAPE"; + +const std::string &get_cmath_string() { + return cmath; +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_complex.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_complex.cpp new file mode 100644 index 0000000000000000000000000000000000000000..deac2d8ef04d33d70005a81cb1731d27674f8124 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_complex.cpp @@ -0,0 +1,1179 @@ +// This is copy-pasted (with modification) from the following llvm file: +// - https://github.com/llvm/llvm-project/blob/main/libcxx/include/complex +// +// -*- C++ -*- +//===----------------------------------------------------------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include +#include + + +namespace at::cuda { + +const std::string complex_body = R"ESCAPE( + +namespace std { + +template class complex; + +template complex<_Tp> operator*(const complex<_Tp>& __z, const complex<_Tp>& __w); +template complex<_Tp> operator/(const complex<_Tp>& __x, const complex<_Tp>& __y); + +template +class complex +{ +public: + typedef _Tp value_type; +private: + value_type __re_; + value_type __im_; +public: + constexpr + complex(const value_type& __re = value_type(), const value_type& __im = value_type()) + : __re_(__re), __im_(__im) {} + template constexpr + complex(const complex<_Xp>& __c) + : __re_(__c.real()), __im_(__c.imag()) {} + + constexpr value_type real() const {return __re_;} + constexpr value_type imag() const {return __im_;} + + void real(value_type __re) {__re_ = __re;} + void imag(value_type __im) {__im_ = __im;} + + constexpr operator bool() const { + return real() || imag(); + } + + complex& operator= (const value_type& __re) + {__re_ = __re; __im_ = value_type(); return *this;} + complex& operator+=(const value_type& __re) {__re_ += __re; return *this;} + complex& operator-=(const value_type& __re) {__re_ -= __re; return *this;} + complex& operator*=(const value_type& __re) {__re_ *= __re; __im_ *= __re; return *this;} + complex& operator/=(const value_type& __re) {__re_ /= __re; __im_ /= __re; return *this;} + + template complex& operator= (const complex<_Xp>& __c) + { + __re_ = __c.real(); + __im_ = __c.imag(); + return *this; + } + template complex& operator+=(const complex<_Xp>& __c) + { + __re_ += __c.real(); + __im_ += __c.imag(); + return *this; + } + template complex& operator-=(const complex<_Xp>& __c) + { + __re_ -= __c.real(); + __im_ -= __c.imag(); + return *this; + } + template complex& operator*=(const complex<_Xp>& __c) + { + *this = *this * complex(__c.real(), __c.imag()); + return *this; + } + template complex& operator/=(const complex<_Xp>& __c) + { + *this = *this / complex(__c.real(), __c.imag()); + return *this; + } +}; + +template<> class complex; + +template<> +class complex +{ + float __re_; + float __im_; +public: + typedef float value_type; + + constexpr complex(float __re = 0.0f, float __im = 0.0f) + : __re_(__re), __im_(__im) {} + + explicit constexpr complex(const complex& __c); + + constexpr float real() const {return __re_;} + constexpr float imag() const {return __im_;} + + void real(value_type __re) {__re_ = __re;} + void imag(value_type __im) {__im_ = __im;} + + constexpr operator bool() const { + return real() || imag(); + } + + complex& operator= (float __re) + {__re_ = __re; __im_ = value_type(); return *this;} + complex& operator+=(float __re) {__re_ += __re; return *this;} + complex& operator-=(float __re) {__re_ -= __re; return *this;} + complex& operator*=(float __re) {__re_ *= __re; __im_ *= __re; return *this;} + complex& operator/=(float __re) {__re_ /= __re; __im_ /= __re; return *this;} + + template complex& operator= (const complex<_Xp>& __c) + { + __re_ = __c.real(); + __im_ = __c.imag(); + return *this; + } + template complex& operator+=(const complex<_Xp>& __c) + { + __re_ += __c.real(); + __im_ += __c.imag(); + return *this; + } + template complex& operator-=(const complex<_Xp>& __c) + { + __re_ -= __c.real(); + __im_ -= __c.imag(); + return *this; + } + template complex& operator*=(const complex<_Xp>& __c) + { + *this = *this * complex(__c.real(), __c.imag()); + return *this; + } + template complex& operator/=(const complex<_Xp>& __c) + { + *this = *this / complex(__c.real(), __c.imag()); + return *this; + } +}; + +template<> +class complex +{ + double __re_; + double __im_; +public: + typedef double value_type; + + constexpr complex(double __re = 0.0, double __im = 0.0) + : __re_(__re), __im_(__im) {} + + constexpr complex(const complex& __c); + + constexpr double real() const {return __re_;} + constexpr double imag() const {return __im_;} + + void real(value_type __re) {__re_ = __re;} + void imag(value_type __im) {__im_ = __im;} + + constexpr operator bool() const { + return real() || imag(); + } + + complex& operator= (double __re) + {__re_ = __re; __im_ = value_type(); return *this;} + complex& operator+=(double __re) {__re_ += __re; return *this;} + complex& operator-=(double __re) {__re_ -= __re; return *this;} + complex& operator*=(double __re) {__re_ *= __re; __im_ *= __re; return *this;} + complex& operator/=(double __re) {__re_ /= __re; __im_ /= __re; return *this;} + + template complex& operator= (const complex<_Xp>& __c) + { + __re_ = __c.real(); + __im_ = __c.imag(); + return *this; + } + template complex& operator+=(const complex<_Xp>& __c) + { + __re_ += __c.real(); + __im_ += __c.imag(); + return *this; + } + template complex& operator-=(const complex<_Xp>& __c) + { + __re_ -= __c.real(); + __im_ -= __c.imag(); + return *this; + } + template complex& operator*=(const complex<_Xp>& __c) + { + *this = *this * complex(__c.real(), __c.imag()); + return *this; + } + template complex& operator/=(const complex<_Xp>& __c) + { + *this = *this / complex(__c.real(), __c.imag()); + return *this; + } +}; + +inline +constexpr +complex::complex(const complex& __c) + : __re_(__c.real()), __im_(__c.imag()) {} + +inline +constexpr +complex::complex(const complex& __c) + : __re_(__c.real()), __im_(__c.imag()) {} + + +// 26.3.6 operators: + +template +inline +complex<_Tp> +operator+(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + complex<_Tp> __t(__x); + __t += __y; + return __t; +} + +template +inline +complex<_Tp> +operator+(const complex<_Tp>& __x, const _Tp& __y) +{ + complex<_Tp> __t(__x); + __t += __y; + return __t; +} + +template +inline +complex<_Tp> +operator+(const _Tp& __x, const complex<_Tp>& __y) +{ + complex<_Tp> __t(__y); + __t += __x; + return __t; +} + +template +inline +complex<_Tp> +operator-(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + complex<_Tp> __t(__x); + __t -= __y; + return __t; +} + +template +inline +complex<_Tp> +operator-(const complex<_Tp>& __x, const _Tp& __y) +{ + complex<_Tp> __t(__x); + __t -= __y; + return __t; +} + +template +inline +complex<_Tp> +operator-(const _Tp& __x, const complex<_Tp>& __y) +{ + complex<_Tp> __t(-__y); + __t += __x; + return __t; +} + +template +complex<_Tp> +operator*(const complex<_Tp>& __z, const complex<_Tp>& __w) +{ + _Tp __a = __z.real(); + _Tp __b = __z.imag(); + _Tp __c = __w.real(); + _Tp __d = __w.imag(); + _Tp __ac = __a * __c; + _Tp __bd = __b * __d; + _Tp __ad = __a * __d; + _Tp __bc = __b * __c; + _Tp __x = __ac - __bd; + _Tp __y = __ad + __bc; + if (isnan(__x) && isnan(__y)) + { + bool __recalc = false; + if (isinf(__a) || isinf(__b)) + { + __a = copysign(isinf(__a) ? _Tp(1) : _Tp(0), __a); + __b = copysign(isinf(__b) ? _Tp(1) : _Tp(0), __b); + if (isnan(__c)) + __c = copysign(_Tp(0), __c); + if (isnan(__d)) + __d = copysign(_Tp(0), __d); + __recalc = true; + } + if (isinf(__c) || isinf(__d)) + { + __c = copysign(isinf(__c) ? _Tp(1) : _Tp(0), __c); + __d = copysign(isinf(__d) ? _Tp(1) : _Tp(0), __d); + if (isnan(__a)) + __a = copysign(_Tp(0), __a); + if (isnan(__b)) + __b = copysign(_Tp(0), __b); + __recalc = true; + } + if (!__recalc && (isinf(__ac) || isinf(__bd) || + isinf(__ad) || isinf(__bc))) + { + if (isnan(__a)) + __a = copysign(_Tp(0), __a); + if (isnan(__b)) + __b = copysign(_Tp(0), __b); + if (isnan(__c)) + __c = copysign(_Tp(0), __c); + if (isnan(__d)) + __d = copysign(_Tp(0), __d); + __recalc = true; + } + if (__recalc) + { + __x = _Tp(INFINITY) * (__a * __c - __b * __d); + __y = _Tp(INFINITY) * (__a * __d + __b * __c); + } + } + return complex<_Tp>(__x, __y); +} + +template +inline +complex<_Tp> +operator*(const complex<_Tp>& __x, const _Tp& __y) +{ + complex<_Tp> __t(__x); + __t *= __y; + return __t; +} + +template +inline +complex<_Tp> +operator*(const _Tp& __x, const complex<_Tp>& __y) +{ + complex<_Tp> __t(__y); + __t *= __x; + return __t; +} + +template +complex<_Tp> +operator/(const complex<_Tp>& __z, const complex<_Tp>& __w) +{ + int __ilogbw = 0; + _Tp __a = __z.real(); + _Tp __b = __z.imag(); + _Tp __c = __w.real(); + _Tp __d = __w.imag(); + _Tp __logbw = logb(fmax(fabs(__c), fabs(__d))); + if (isfinite(__logbw)) + { + __ilogbw = static_cast(__logbw); + __c = scalbn(__c, -__ilogbw); + __d = scalbn(__d, -__ilogbw); + } + _Tp __denom = __c * __c + __d * __d; + _Tp __x = scalbn((__a * __c + __b * __d) / __denom, -__ilogbw); + _Tp __y = scalbn((__b * __c - __a * __d) / __denom, -__ilogbw); + if (isnan(__x) && isnan(__y)) + { + if ((__denom == _Tp(0)) && (!isnan(__a) || !isnan(__b))) + { + __x = copysign(_Tp(INFINITY), __c) * __a; + __y = copysign(_Tp(INFINITY), __c) * __b; + } + else if ((isinf(__a) || isinf(__b)) && isfinite(__c) && isfinite(__d)) + { + __a = copysign(isinf(__a) ? _Tp(1) : _Tp(0), __a); + __b = copysign(isinf(__b) ? _Tp(1) : _Tp(0), __b); + __x = _Tp(INFINITY) * (__a * __c + __b * __d); + __y = _Tp(INFINITY) * (__b * __c - __a * __d); + } + else if (isinf(__logbw) && __logbw > _Tp(0) && isfinite(__a) && isfinite(__b)) + { + __c = copysign(isinf(__c) ? _Tp(1) : _Tp(0), __c); + __d = copysign(isinf(__d) ? _Tp(1) : _Tp(0), __d); + __x = _Tp(0) * (__a * __c + __b * __d); + __y = _Tp(0) * (__b * __c - __a * __d); + } + } + return complex<_Tp>(__x, __y); +} + +template +inline +complex<_Tp> +operator/(const complex<_Tp>& __x, const _Tp& __y) +{ + return complex<_Tp>(__x.real() / __y, __x.imag() / __y); +} + +template +inline +complex<_Tp> +operator/(const _Tp& __x, const complex<_Tp>& __y) +{ + complex<_Tp> __t(__x); + __t /= __y; + return __t; +} + +template +inline +complex<_Tp> +operator+(const complex<_Tp>& __x) +{ + return __x; +} + +template +inline +complex<_Tp> +operator-(const complex<_Tp>& __x) +{ + return complex<_Tp>(-__x.real(), -__x.imag()); +} + +template +inline constexpr +bool +operator==(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + return __x.real() == __y.real() && __x.imag() == __y.imag(); +} + +template +inline constexpr +bool +operator==(const complex<_Tp>& __x, const _Tp& __y) +{ + return __x.real() == __y && __x.imag() == 0; +} + +template +inline constexpr +bool +operator==(const _Tp& __x, const complex<_Tp>& __y) +{ + return __x == __y.real() && 0 == __y.imag(); +} + +template +inline constexpr +bool +operator!=(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + return !(__x == __y); +} + +template +inline constexpr +bool +operator!=(const complex<_Tp>& __x, const _Tp& __y) +{ + return !(__x == __y); +} + +template +inline constexpr +bool +operator!=(const _Tp& __x, const complex<_Tp>& __y) +{ + return !(__x == __y); +} + +template +inline constexpr +bool +operator&&(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + return bool(__x) && bool(__y); +} + +template +inline constexpr +bool +isnan(const complex<_Tp>& __x) +{ + return isnan(__x.real()) || isnan(__x.imag()); +} + +template +inline constexpr +bool +operator||(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + return bool(__x) || bool(__y); +} + +// 26.3.7 values: + +template ::value, + bool = is_floating_point<_Tp>::value + > +struct __libcpp_complex_overload_traits {}; + +// Integral Types +template +struct __libcpp_complex_overload_traits<_Tp, true, false> +{ + typedef double _ValueType; + typedef complex _ComplexType; +}; + +// Floating point types +template +struct __libcpp_complex_overload_traits<_Tp, false, true> +{ + typedef _Tp _ValueType; + typedef complex<_Tp> _ComplexType; +}; + +// real + +template +inline constexpr +_Tp +real(const complex<_Tp>& __c) +{ + return __c.real(); +} + +template +inline constexpr +typename __libcpp_complex_overload_traits<_Tp>::_ValueType +real(_Tp __re) +{ + return __re; +} + +// imag + +template +inline constexpr +_Tp +imag(const complex<_Tp>& __c) +{ + return __c.imag(); +} + +template +inline constexpr +typename __libcpp_complex_overload_traits<_Tp>::_ValueType +imag(_Tp) +{ + return 0; +} + +// abs + +template +inline +_Tp +abs(const complex<_Tp>& __c) +{ + return hypot(__c.real(), __c.imag()); +} + +// arg + +template +inline +_Tp +arg(const complex<_Tp>& __c) +{ + return atan2(__c.imag(), __c.real()); +} + +template +inline +typename enable_if +< + is_integral<_Tp>::value || is_same<_Tp, double>::value, + double +>::type +arg(_Tp __re) +{ + return atan2(0., __re); +} + +template +inline +typename enable_if< + is_same<_Tp, float>::value, + float +>::type +arg(_Tp __re) +{ + return atan2f(0.F, __re); +} + +} + +)ESCAPE"; + +const std::string complex_half_body = R"ESCAPE( +namespace std { +template <> +struct alignas(2) complex { + at::Half real_; + at::Half imag_; + + // Constructors + complex() = default; + + // implicit casting to and from `complex`. + // NOTE: computation of `complex` will occur in `complex` + __host__ __device__ inline complex(const std::complex& value) + : real_(value.real()), imag_(value.imag()) {} + + inline __host__ __device__ operator std::complex() const { + return {real_, imag_}; + } + + at::Half real() const {return real_;} + at::Half imag() const {return imag_;} + +}; +} +)ESCAPE"; + + +const std::string &get_complex_body_string() { + return complex_body; +} + +const std::string &get_complex_half_body_string() { + return complex_half_body; +} + +const std::string complex_math = R"ESCAPE( + +namespace std { + +// norm + +template +inline +_Tp +norm(const complex<_Tp>& __c) +{ + if (isinf(__c.real())) + return abs(__c.real()); + if (isinf(__c.imag())) + return abs(__c.imag()); + return __c.real() * __c.real() + __c.imag() * __c.imag(); +} + +template +inline +typename __libcpp_complex_overload_traits<_Tp>::_ValueType +norm(_Tp __re) +{ + typedef typename __libcpp_complex_overload_traits<_Tp>::_ValueType _ValueType; + return static_cast<_ValueType>(__re) * __re; +} + +// conj + +template +inline +complex<_Tp> +conj(const complex<_Tp>& __c) +{ + return complex<_Tp>(__c.real(), -__c.imag()); +} + +template +inline +typename __libcpp_complex_overload_traits<_Tp>::_ComplexType +conj(_Tp __re) +{ + typedef typename __libcpp_complex_overload_traits<_Tp>::_ComplexType _ComplexType; + return _ComplexType(__re); +} + + + +// proj + +template +inline +complex<_Tp> +proj(const complex<_Tp>& __c) +{ + complex<_Tp> __r = __c; + if (isinf(__c.real()) || isinf(__c.imag())) + __r = complex<_Tp>(INFINITY, copysign(_Tp(0), __c.imag())); + return __r; +} + +template +inline +typename enable_if +< + is_floating_point<_Tp>::value, + typename __libcpp_complex_overload_traits<_Tp>::_ComplexType +>::type +proj(_Tp __re) +{ + if (isinf(__re)) + __re = abs(__re); + return complex<_Tp>(__re); +} + +template +inline +typename enable_if +< + is_integral<_Tp>::value, + typename __libcpp_complex_overload_traits<_Tp>::_ComplexType +>::type +proj(_Tp __re) +{ + typedef typename __libcpp_complex_overload_traits<_Tp>::_ComplexType _ComplexType; + return _ComplexType(__re); +} + +// polar + +template +complex<_Tp> +polar(const _Tp& __rho, const _Tp& __theta = _Tp()) +{ + if (isnan(__rho) || signbit(__rho)) + return complex<_Tp>(_Tp(NAN), _Tp(NAN)); + if (isnan(__theta)) + { + if (isinf(__rho)) + return complex<_Tp>(__rho, __theta); + return complex<_Tp>(__theta, __theta); + } + if (isinf(__theta)) + { + if (isinf(__rho)) + return complex<_Tp>(__rho, _Tp(NAN)); + return complex<_Tp>(_Tp(NAN), _Tp(NAN)); + } + _Tp __x = __rho * cos(__theta); + if (isnan(__x)) + __x = 0; + _Tp __y = __rho * sin(__theta); + if (isnan(__y)) + __y = 0; + return complex<_Tp>(__x, __y); +} + +// log + +template +inline +complex<_Tp> +log(const complex<_Tp>& __x) +{ + return complex<_Tp>(log(abs(__x)), arg(__x)); +} + +// log10 + +template +inline +complex<_Tp> +log10(const complex<_Tp>& __x) +{ + return log(__x) / log(_Tp(10)); +} + +// log2 + +template +inline +complex<_Tp> +log2(const complex<_Tp>& __x) +{ + return log(__x) / log(_Tp(2)); +} + +// sqrt + +template +complex<_Tp> +sqrt(const complex<_Tp>& __x) +{ + if (isinf(__x.imag())) + return complex<_Tp>(_Tp(INFINITY), __x.imag()); + if (isinf(__x.real())) + { + if (__x.real() > _Tp(0)) + return complex<_Tp>(__x.real(), isnan(__x.imag()) ? __x.imag() : copysign(_Tp(0), __x.imag())); + return complex<_Tp>(isnan(__x.imag()) ? __x.imag() : _Tp(0), copysign(__x.real(), __x.imag())); + } + return polar(sqrt(abs(__x)), arg(__x) / _Tp(2)); +} + +// exp + +template +complex<_Tp> +exp(const complex<_Tp>& __x) +{ + _Tp __i = __x.imag(); + if (__i == 0) { + return complex<_Tp>(exp(__x.real()), copysign(_Tp(0), __x.imag())); + } + if (isinf(__x.real())) + { + if (__x.real() < _Tp(0)) + { + if (!isfinite(__i)) + __i = _Tp(1); + } + else if (__i == 0 || !isfinite(__i)) + { + if (isinf(__i)) + __i = _Tp(NAN); + return complex<_Tp>(__x.real(), __i); + } + } + _Tp __e = exp(__x.real()); + return complex<_Tp>(__e * cos(__i), __e * sin(__i)); +} + +// pow + +template +inline +complex<_Tp> +pow(const complex<_Tp>& __x, const complex<_Tp>& __y) +{ + return exp(__y * log(__x)); +} + +template +inline +complex::type> +pow(const complex<_Tp>& __x, const complex<_Up>& __y) +{ + typedef complex::type> result_type; + return std::pow(result_type(__x), result_type(__y)); +} + +template +inline +typename enable_if +< + is_arithmetic<_Up>::value, + complex::type> +>::type +pow(const complex<_Tp>& __x, const _Up& __y) +{ + typedef complex::type> result_type; + return std::pow(result_type(__x), result_type(__y)); +} + +template +inline +typename enable_if +< + is_arithmetic<_Tp>::value, + complex::type> +>::type +pow(const _Tp& __x, const complex<_Up>& __y) +{ + typedef complex::type> result_type; + return std::pow(result_type(__x), result_type(__y)); +} + +// __sqr, computes pow(x, 2) + +template +inline +complex<_Tp> +__sqr(const complex<_Tp>& __x) +{ + return complex<_Tp>((__x.real() - __x.imag()) * (__x.real() + __x.imag()), + _Tp(2) * __x.real() * __x.imag()); +} + +// asinh + +template +complex<_Tp> +asinh(const complex<_Tp>& __x) +{ + const _Tp __pi(atan2(+0., -0.)); + if (isinf(__x.real())) + { + if (isnan(__x.imag())) + return __x; + if (isinf(__x.imag())) + return complex<_Tp>(__x.real(), copysign(__pi * _Tp(0.25), __x.imag())); + return complex<_Tp>(__x.real(), copysign(_Tp(0), __x.imag())); + } + if (isnan(__x.real())) + { + if (isinf(__x.imag())) + return complex<_Tp>(__x.imag(), __x.real()); + if (__x.imag() == 0) + return __x; + return complex<_Tp>(__x.real(), __x.real()); + } + if (isinf(__x.imag())) + return complex<_Tp>(copysign(__x.imag(), __x.real()), copysign(__pi/_Tp(2), __x.imag())); + complex<_Tp> __z = log(__x + sqrt(__sqr(__x) + _Tp(1))); + return complex<_Tp>(copysign(__z.real(), __x.real()), copysign(__z.imag(), __x.imag())); +} + +// acosh + +template +complex<_Tp> +acosh(const complex<_Tp>& __x) +{ + const _Tp __pi(atan2(+0., -0.)); + if (isinf(__x.real())) + { + if (isnan(__x.imag())) + return complex<_Tp>(abs(__x.real()), __x.imag()); + if (isinf(__x.imag())) + { + if (__x.real() > 0) + return complex<_Tp>(__x.real(), copysign(__pi * _Tp(0.25), __x.imag())); + else + return complex<_Tp>(-__x.real(), copysign(__pi * _Tp(0.75), __x.imag())); + } + if (__x.real() < 0) + return complex<_Tp>(-__x.real(), copysign(__pi, __x.imag())); + return complex<_Tp>(__x.real(), copysign(_Tp(0), __x.imag())); + } + if (isnan(__x.real())) + { + if (isinf(__x.imag())) + return complex<_Tp>(abs(__x.imag()), __x.real()); + return complex<_Tp>(__x.real(), __x.real()); + } + if (isinf(__x.imag())) + return complex<_Tp>(abs(__x.imag()), copysign(__pi/_Tp(2), __x.imag())); + complex<_Tp> __z = log(__x + sqrt(__sqr(__x) - _Tp(1))); + return complex<_Tp>(copysign(__z.real(), _Tp(0)), copysign(__z.imag(), __x.imag())); +} + +// atanh + +template +complex<_Tp> +atanh(const complex<_Tp>& __x) +{ + const _Tp __pi(atan2(+0., -0.)); + if (isinf(__x.imag())) + { + return complex<_Tp>(copysign(_Tp(0), __x.real()), copysign(__pi/_Tp(2), __x.imag())); + } + if (isnan(__x.imag())) + { + if (isinf(__x.real()) || __x.real() == 0) + return complex<_Tp>(copysign(_Tp(0), __x.real()), __x.imag()); + return complex<_Tp>(__x.imag(), __x.imag()); + } + if (isnan(__x.real())) + { + return complex<_Tp>(__x.real(), __x.real()); + } + if (isinf(__x.real())) + { + return complex<_Tp>(copysign(_Tp(0), __x.real()), copysign(__pi/_Tp(2), __x.imag())); + } + if (abs(__x.real()) == _Tp(1) && __x.imag() == _Tp(0)) + { + return complex<_Tp>(copysign(_Tp(INFINITY), __x.real()), copysign(_Tp(0), __x.imag())); + } + complex<_Tp> __z = log((_Tp(1) + __x) / (_Tp(1) - __x)) / _Tp(2); + return complex<_Tp>(copysign(__z.real(), __x.real()), copysign(__z.imag(), __x.imag())); +} + +// sinh + +template +complex<_Tp> +sinh(const complex<_Tp>& __x) +{ + if (isinf(__x.real()) && !isfinite(__x.imag())) + return complex<_Tp>(__x.real(), _Tp(NAN)); + if (__x.real() == 0 && !isfinite(__x.imag())) + return complex<_Tp>(__x.real(), _Tp(NAN)); + if (__x.imag() == 0 && !isfinite(__x.real())) + return __x; + return complex<_Tp>(sinh(__x.real()) * cos(__x.imag()), cosh(__x.real()) * sin(__x.imag())); +} + +// cosh + +template +complex<_Tp> +cosh(const complex<_Tp>& __x) +{ + if (isinf(__x.real()) && !isfinite(__x.imag())) + return complex<_Tp>(abs(__x.real()), _Tp(NAN)); + if (__x.real() == 0 && !isfinite(__x.imag())) + return complex<_Tp>(_Tp(NAN), __x.real()); + if (__x.real() == 0 && __x.imag() == 0) + return complex<_Tp>(_Tp(1), __x.imag()); + if (__x.imag() == 0 && !isfinite(__x.real())) + return complex<_Tp>(abs(__x.real()), __x.imag()); + return complex<_Tp>(cosh(__x.real()) * cos(__x.imag()), sinh(__x.real()) * sin(__x.imag())); +} + +// tanh + +template +complex<_Tp> +tanh(const complex<_Tp>& __x) +{ + if (isinf(__x.real())) + { + if (!isfinite(__x.imag())) + return complex<_Tp>(copysign(_Tp(1), __x.real()), _Tp(0)); + return complex<_Tp>(copysign(_Tp(1), __x.real()), copysign(_Tp(0), sin(_Tp(2) * __x.imag()))); + } + if (isnan(__x.real()) && __x.imag() == 0) + return __x; + _Tp __2r(_Tp(2) * __x.real()); + _Tp __2i(_Tp(2) * __x.imag()); + _Tp __d(cosh(__2r) + cos(__2i)); + _Tp __2rsh(sinh(__2r)); + if (isinf(__2rsh) && isinf(__d)) + return complex<_Tp>(__2rsh > _Tp(0) ? _Tp(1) : _Tp(-1), + __2i > _Tp(0) ? _Tp(0) : _Tp(-0.)); + return complex<_Tp>(__2rsh/__d, sin(__2i)/__d); +} + +// asin + +template +complex<_Tp> +asin(const complex<_Tp>& __x) +{ + complex<_Tp> __z = asinh(complex<_Tp>(-__x.imag(), __x.real())); + return complex<_Tp>(__z.imag(), -__z.real()); +} + +// acos + +template +complex<_Tp> +acos(const complex<_Tp>& __x) +{ + const _Tp __pi(atan2(+0., -0.)); + if (isinf(__x.real())) + { + if (isnan(__x.imag())) + return complex<_Tp>(__x.imag(), __x.real()); + if (isinf(__x.imag())) + { + if (__x.real() < _Tp(0)) + return complex<_Tp>(_Tp(0.75) * __pi, -__x.imag()); + return complex<_Tp>(_Tp(0.25) * __pi, -__x.imag()); + } + if (__x.real() < _Tp(0)) + return complex<_Tp>(__pi, signbit(__x.imag()) ? -__x.real() : __x.real()); + return complex<_Tp>(_Tp(0), signbit(__x.imag()) ? __x.real() : -__x.real()); + } + if (isnan(__x.real())) + { + if (isinf(__x.imag())) + return complex<_Tp>(__x.real(), -__x.imag()); + return complex<_Tp>(__x.real(), __x.real()); + } + if (isinf(__x.imag())) + return complex<_Tp>(__pi/_Tp(2), -__x.imag()); + if (__x.real() == 0 && (__x.imag() == 0 || isnan(__x.imag()))) + return complex<_Tp>(__pi/_Tp(2), -__x.imag()); + complex<_Tp> __z = log(__x + sqrt(__sqr(__x) - _Tp(1))); + if (signbit(__x.imag())) + return complex<_Tp>(abs(__z.imag()), abs(__z.real())); + return complex<_Tp>(abs(__z.imag()), -abs(__z.real())); +} + +// atan + +template +complex<_Tp> +atan(const complex<_Tp>& __x) +{ + complex<_Tp> __z = atanh(complex<_Tp>(-__x.imag(), __x.real())); + return complex<_Tp>(__z.imag(), -__z.real()); +} + +// sin + +template +complex<_Tp> +sin(const complex<_Tp>& __x) +{ + complex<_Tp> __z = sinh(complex<_Tp>(-__x.imag(), __x.real())); + return complex<_Tp>(__z.imag(), -__z.real()); +} + +// cos + +template +inline +complex<_Tp> +cos(const complex<_Tp>& __x) +{ + return cosh(complex<_Tp>(-__x.imag(), __x.real())); +} + +// tan + +template +complex<_Tp> +tan(const complex<_Tp>& __x) +{ + complex<_Tp> __z = tanh(complex<_Tp>(-__x.imag(), __x.real())); + return complex<_Tp>(__z.imag(), -__z.real()); +} + +// Literal suffix for complex number literals [complex.literals] +inline namespace literals +{ + inline namespace complex_literals + { + constexpr complex operator""i(long double __im) + { + return { 0.0, static_cast(__im) }; + } + + constexpr complex operator""i(unsigned long long __im) + { + return { 0.0, static_cast(__im) }; + } + + + constexpr complex operator""if(long double __im) + { + return { 0.0f, static_cast(__im) }; + } + + constexpr complex operator""if(unsigned long long __im) + { + return { 0.0f, static_cast(__im) }; + } + } // namespace complex_literals +} // namespace literals + +} // namespace std + +)ESCAPE"; + +const std::string &get_complex_math_string() { + return complex_math; +} + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_jit_strings.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_jit_strings.h new file mode 100644 index 0000000000000000000000000000000000000000..ec2caa7b34b80eec75210988b7d6081e368f65bf --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/llvm_jit_strings.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace at::cuda { + +TORCH_CUDA_CPP_API const std::string &get_traits_string(); +TORCH_CUDA_CPP_API const std::string &get_cmath_string(); +TORCH_CUDA_CPP_API const std::string &get_complex_body_string(); +TORCH_CUDA_CPP_API const std::string &get_complex_half_body_string(); +TORCH_CUDA_CPP_API const std::string &get_complex_math_string(); + +} // namespace at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/nvrtc_stub/ATenNVRTC.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/nvrtc_stub/ATenNVRTC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..28d79bdfe27abbb5819340ee26fde6e751717832 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/nvrtc_stub/ATenNVRTC.cpp @@ -0,0 +1,12 @@ +#include + +namespace at::cuda { + +NVRTC* load_nvrtc() { + auto self = new NVRTC(); +#define CREATE_ASSIGN(name) self->name = name; + AT_FORALL_NVRTC(CREATE_ASSIGN) + return self; +} + +} // at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/nvrtc_stub/ATenNVRTC.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/nvrtc_stub/ATenNVRTC.h new file mode 100644 index 0000000000000000000000000000000000000000..8e485dc38bcea2e0376dc40b16cac853184f643d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/nvrtc_stub/ATenNVRTC.h @@ -0,0 +1,143 @@ +#pragma once + +#include +#include +#include + +namespace at::cuda { + + +// NOTE [ USE OF NVRTC AND DRIVER API ] +// +// ATen does not directly link to either libnvrtc or libcuda because they +// require libcuda to be installed, yet we want our GPU build to work on CPU +// machines as long as CUDA is not initialized. +// +// Normal CUDA code in torch uses the cuda runtime libraries which can be +// installed even if the driver is not installed, but sometimes we specifically +// need to use the driver API (e.g., to load JIT compiled code). +// To accomplish this, we lazily link libcaffe2_nvrtc which provides a struct +// at::cuda::NVRTC that contains function pointers to all of the apis we need. +// +// IT IS AN ERROR TO TRY TO CALL ANY nvrtc* or cu* FUNCTION DIRECTLY. +// INSTEAD USE, e.g. +// detail::getCUDAHooks().nvrtc().cuLoadModule(...) +// or +// globalContext().getNVRTC().cuLoadModule(...) +// +// If a function is missing add it to the list in ATen/cuda/nvrtc_stub/ATenNVRTC.h +// and edit ATen/cuda/detail/LazyNVRTC.cpp accordingly (e.g., via one of the stub +// macros). + +#if !defined(USE_ROCM) + +#define AT_FORALL_NVRTC_BASE(_) \ + _(nvrtcVersion) \ + _(nvrtcAddNameExpression) \ + _(nvrtcCreateProgram) \ + _(nvrtcDestroyProgram) \ + _(nvrtcGetPTXSize) \ + _(nvrtcGetPTX) \ + _(nvrtcCompileProgram) \ + _(nvrtcGetErrorString) \ + _(nvrtcGetProgramLogSize) \ + _(nvrtcGetProgramLog) \ + _(nvrtcGetLoweredName) \ + _(cuModuleLoad) \ + _(cuModuleLoadData) \ + _(cuModuleLoadDataEx) \ + _(cuModuleGetFunction) \ + _(cuOccupancyMaxActiveBlocksPerMultiprocessor) \ + _(cuGetErrorString) \ + _(cuLaunchKernel) \ + _(cuLaunchCooperativeKernel) \ + _(cuCtxGetCurrent) \ + _(cuCtxSetCurrent) \ + _(cuModuleUnload) \ + _(cuDevicePrimaryCtxGetState) \ + _(cuDevicePrimaryCtxRetain) \ + _(cuLinkCreate) \ + _(cuLinkAddData) \ + _(cuLinkComplete) \ + _(cuFuncSetAttribute) \ + _(cuFuncGetAttribute) \ + _(cuPointerGetAttribute) \ + _(cuFuncSetCacheConfig) \ + _(cuDeviceGetAttribute) \ + _(cuDeviceGet) \ + + +#if defined(CUDA_VERSION) +#define AT_FORALL_NVRTC_EXTENDED(_) \ + AT_FORALL_NVRTC_BASE(_) \ + _(cuTensorMapEncodeTiled) +#else +#define AT_FORALL_NVRTC_EXTENDED(_) \ + AT_FORALL_NVRTC_BASE(_) +#endif + +#if defined(CUDA_VERSION) +#define AT_FORALL_NVRTC(_) \ + AT_FORALL_NVRTC_EXTENDED(_) \ + _(nvrtcGetCUBINSize) \ + _(nvrtcGetCUBIN) +#else +#define AT_FORALL_NVRTC(_) \ + AT_FORALL_NVRTC_EXTENDED(_) +#endif + +#else + +// NOTE [ ATen NVRTC Stub and HIP ] +// +// ATen's NVRTC stub library, caffe2_nvrtc, provides dynamic loading of both +// NVRTC and driver APIs. While the former is not yet supported for HIP, the +// later is supported and needed (e.g., in CUDAHooks::getDeviceWithPrimaryContext() +// used by tensor.pin_memory()). +// +// The macro below strips out certain unsupported operations on HIP from the full +// list above. +// +// HIP doesn't have +// cuGetErrorString (maps to non-functional hipGetErrorString___) +// +// HIP from ROCm 3.5 on renamed hipOccupancyMaxActiveBlocksPerMultiprocessor +// to hipModuleOccupancyMaxActiveBlocksPerMultiprocessor. +#if TORCH_HIP_VERSION < 305 +#define HIPOCCUPANCYMAXACTIVEBLOCKSPERMULTIPROCESSOR hipOccupancyMaxActiveBlocksPerMultiprocessor +#else +#define HIPOCCUPANCYMAXACTIVEBLOCKSPERMULTIPROCESSOR cuOccupancyMaxActiveBlocksPerMultiprocessor +#endif + +#define AT_FORALL_NVRTC(_) \ + _(nvrtcVersion) \ + _(nvrtcCreateProgram) \ + _(nvrtcAddNameExpression) \ + _(nvrtcDestroyProgram) \ + _(nvrtcGetPTXSize) \ + _(nvrtcGetPTX) \ + _(cuModuleLoadData) \ + _(cuModuleLoad) \ + _(cuGetErrorString) \ + _(cuModuleGetFunction) \ + _(HIPOCCUPANCYMAXACTIVEBLOCKSPERMULTIPROCESSOR) \ + _(nvrtcGetErrorString) \ + _(nvrtcGetProgramLogSize) \ + _(nvrtcGetProgramLog) \ + _(cuLaunchKernel) \ + _(nvrtcCompileProgram) \ + _(cuCtxGetCurrent) \ + _(nvrtcGetLoweredName) \ + _(cuModuleUnload) \ + _(cuDevicePrimaryCtxGetState) + +#endif + +extern "C" typedef struct NVRTC { +#define CREATE_MEMBER(name) decltype(&name) name; + AT_FORALL_NVRTC(CREATE_MEMBER) +#undef CREATE_MEMBER +} NVRTC; + +extern "C" TORCH_CUDA_CPP_API NVRTC* load_nvrtc(); +} // at::cuda diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmCommon.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmCommon.h new file mode 100644 index 0000000000000000000000000000000000000000..97e5cccc3775c4a2bd9c301c4a6de04c1ba571eb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmCommon.h @@ -0,0 +1,718 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif +#include +#include + +namespace at::cuda::tunable { + +using at::blas::ScalingType; + +enum class BlasOp { + N = 0, + T = 1 +}; + +inline char BlasOpToString(BlasOp op) { + switch (op) { + case BlasOp::N: + return 'N'; + case BlasOp::T: + return 'T'; + } + TORCH_CHECK(false, "unrecognized BlasOp"); + return 'N'; +} + +template +inline const char* BLASTypeName(T v) { + return "unknown"; +} + +template <> +inline const char* BLASTypeName(float v) { + return "f32_r"; +} + +template <> +inline const char* BLASTypeName(double v) { + return "f64_r"; +} + +template <> +inline const char* BLASTypeName(BFloat16 v) { + return "bf16_r"; +} + +template <> +inline const char* BLASTypeName(Half v) { + return "f16_r"; +} + +//https://github.com/ROCm/hipBLASLt/blob/develop/library/src/include/auxiliary.hpp#L175 +template <> +inline const char* BLASTypeName(Float8_e4m3fn v) { + return "f8_r"; +} + +template <> +inline const char* BLASTypeName(Float8_e5m2 v) { + return "bf8_r"; +} + +template <> +inline const char* BLASTypeName(Float8_e4m3fnuz v) { + return "f8_fnuz_r"; +} + +template <> +inline const char* BLASTypeName(Float8_e5m2fnuz v) { + return "bf8_fnuz_r"; +} + +template <> +inline const char* BLASTypeName(c10::complex v) { + return "f64_r"; +} + +template <> +inline const char* BLASTypeName(c10::complex v) { + return "f32_r"; +} + +inline std::string ScalarTypeToBLASType(c10::ScalarType scalar_type) { + std::string BLASType; + switch (scalar_type) { + case c10::ScalarType::Float:{ + BLASType = "f32_r"; + break; + } + case c10::ScalarType::Double:{ + BLASType = "f64_r"; + break; + } + case c10::ScalarType::BFloat16:{ + BLASType = "bf16_r"; + break; + } + case c10::ScalarType::Half: { + BLASType = "f16_r"; + break; + } + case c10::ScalarType::Float8_e4m3fn: { + BLASType = "f8_r"; + break; + } + case c10::ScalarType::Float8_e5m2: { + BLASType = "bf8_r"; + break; + } + case c10::ScalarType::Float8_e4m3fnuz: { + BLASType = "f8_fnuz_r"; + break; + } + case c10::ScalarType::Float8_e5m2fnuz: { + BLASType = "bf8_fnuz_r"; + break; + } + case c10::ScalarType::ComplexFloat:{ + BLASType = "f32_c"; + break; + } + case c10::ScalarType::ComplexDouble:{ + BLASType = "f64_c"; + break; + } + default: + BLASType = "unknown"; + } + return BLASType; + +} + +// Similar to Compute Type in GemmRocblas.h +template +inline std::string ComputeTypeFor() { + return "Unknown ComputeType"; +} + +// This is a union of the compute types for +// ROCBLAS and hipBLASLt. +template <> +inline std::string ComputeTypeFor() { + if (at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) != at::Float32Precision::TF32) { + return "f32_r"; + } else { + return "xf32_r"; + } +} + +template <> +inline std::string ComputeTypeFor() { + return "f64_r"; +} + +template <> +inline std::string ComputeTypeFor() { + return "f32_r"; +} + +template <> +inline std::string ComputeTypeFor() { + return "f32_r"; +} + +template <> +inline std::string ComputeTypeFor>() { + return "f32_c"; +} + +template <> +inline std::string ComputeTypeFor>() { + return "f64_c"; +} + +template <> +inline std::string ComputeTypeFor() { + return "f32_r"; +} + +template <> +inline std::string ComputeTypeFor() { + return "f32_r"; +} + +template <> +inline std::string ComputeTypeFor() { + return "f32_r"; +} + +template <> +inline std::string ComputeTypeFor() { + return "f32_r"; +} + +// Convert opmath_type to string +template +inline std::string to_string_opmath(const at::opmath_type& value) { + if constexpr (std::is_same_v, c10::complex> || + std::is_same_v, c10::complex>) { + return fmt::format("({:.4f}, {:.4f})", value.real(), value.imag()); + } else { + return fmt::format("{:.4f}", value); + } +} + +// convert activation epilogue to string +inline std::string to_string_epilogue(const at::cuda::blas::GEMMAndBiasActivationEpilogue& value) { + switch (value) { + case at::cuda::blas::GEMMAndBiasActivationEpilogue::None: + return std::string("None"); + break; + case at::cuda::blas::GEMMAndBiasActivationEpilogue::RELU: + return std::string("RELU"); + break; + case cuda::blas::GEMMAndBiasActivationEpilogue::GELU: + return std::string("GELU"); + break; + default: + return std::string("unknown"); + } +} + +namespace detail { + +static bool NumericalCheck(ScalarType dtype, void* c, void* other_c, int64_t size, const NumericalCheckConfig& config) { + + if (!config.enabled) { + return true; // skip when disabled + } + + auto options = at::TensorOptions().dtype(dtype).device(at::kCUDA); + at::Tensor ref = at::from_blob(c, {size}, options); + at::Tensor oth = at::from_blob(other_c, {size}, options); + at::Tensor ref_float = ref.to(at::kFloat); + at::Tensor oth_float = oth.to(at::kFloat); + + const bool ok = at::allclose(ref_float, oth_float, config.rtol, config.atol); + if (ok) { + TUNABLE_LOG3("├──verify numerics: PASSED with atol=", config.atol, ", rtol=", config.rtol); + } else { + TUNABLE_LOG3("├──verify numerics: FAILED with atol=", config.atol, ", rtol=", config.rtol); + } + return ok; +} + +} + +// Note on GetSizeA et al. +// Tensors can be dense or arbitrarily strided. We only need our copies to be large enough. +// Our copies must be at least as large as the m n k shapes dictate, but could be larger +// depending on the lda ldb ldc values. Similarly for the batched case. + +template +struct GemmParams : OpParams { + GemmParams() = default; + GemmParams(const GemmParams&) = default; + GemmParams& operator=(const GemmParams&) = default; + ~GemmParams() override = default; + + std::string BLASSignature() const override { + std::string alpha_str = to_string_opmath(alpha); + std::string beta_str = to_string_opmath(beta); + return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, " + "alpha: %s, beta: %s, transA: %c, transB: %c, batch_count: 1, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, bias_type: %s, compute_type: %s }", + m, n, k, lda, ldb, ldc, ldc, alpha_str, beta_str, transa, transb, + BLASTypeName(T{}), BLASTypeName(T{}), BLASTypeName(T{}), BLASTypeName(T{}), ComputeTypeFor(), ComputeTypeFor(), ComputeTypeFor()); + } + + std::string Signature() const override { + return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, lda, ldb, ldc); + } + + size_t GetSizeA() const { + size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m); + size_t size_dense = m * k; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeB() const { + size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k); + size_t size_dense = k * n; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeC() const { + size_t size_stride = ldc * n; + size_t size_dense = m * n; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSize(bool duplicate_inputs) const { + size_t size = GetSizeC(); + if (duplicate_inputs) { + size += GetSizeA(); + size += GetSizeB(); + } + return size; + } + + GemmParams* DeepCopy(bool duplicate_inputs) const { + GemmParams* copy = new GemmParams(*this); + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + size_t c_size = GetSizeC(); + copy->c = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(c_size)); + AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync( + copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true)); + if (duplicate_inputs) { + size_t a_size = GetSizeA(); + size_t b_size = GetSizeB(); + copy->a = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(a_size)); + copy->b = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(b_size)); + copy->duplicate_inputs_ = true; + } + return copy; + } + + // only call on object returned by DeepCopy + void Delete() { + c10::cuda::CUDACachingAllocator::raw_delete(c); + if (duplicate_inputs_) { + // NOLINTNEXTLINE(*const-cast*) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(a)); + // NOLINTNEXTLINE(*const-cast*) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(b)); + } + } + + TuningStatus NumericalCheck(GemmParams *other) { + auto* ctx = getTuningContext(); + auto cfg = ctx->GetNumericalCheckConfig(); + auto c_dtype = c10::CppTypeToScalarType::value; + return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL; + } + + char transa{}; + char transb{}; + int64_t m{}; + int64_t n{}; + int64_t k{}; + at::opmath_type alpha; + const T* a{}; + int64_t lda{}; + const T* b{}; + int64_t ldb{}; + at::opmath_type beta; + T* c{}; + int64_t ldc{}; +private: + bool duplicate_inputs_{false}; +}; + +template +struct GemmAndBiasParams : OpParams { + GemmAndBiasParams() = default; + GemmAndBiasParams(const GemmAndBiasParams&) = default; + GemmAndBiasParams(GemmAndBiasParams&&) noexcept = default; + GemmAndBiasParams& operator=(const GemmAndBiasParams&) = default; + GemmAndBiasParams& operator=(GemmAndBiasParams&&) noexcept = default; + ~GemmAndBiasParams() override = default; + + std::string BLASSignature() const override { + std::string alpha_str = to_string_opmath(alpha); + std::string activation_str = to_string_epilogue(activation); + return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, " + "alpha: %s, transA: %c, transB: %c, batch_count: 1, a_type: %s, b_type: %s, c_type: %s, d_type: %s, activation: %s, bias_type: %s, scale_type: %s, compute_type: %s }", + m, n, k, lda, ldb, ldc, ldc, alpha_str, transa, transb, + BLASTypeName(T{}), BLASTypeName(T{}), BLASTypeName(T{}), BLASTypeName(T{}), activation_str, BLASTypeName(T{}), ComputeTypeFor(), ComputeTypeFor(), ComputeTypeFor()); + } + + std::string Signature() const override { + return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, lda, ldb, ldc); + } + + size_t GetSizeA() const { + size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m); + size_t size_dense = m * k; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeB() const { + size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k); + size_t size_dense = k * n; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeC() const { + size_t size_stride = ldc * n; + size_t size_dense = m * n; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSize(bool duplicate_inputs) const { + size_t size = GetSizeC(); + if (duplicate_inputs) { + size += GetSizeA(); + size += GetSizeB(); + } + return size; + } + + GemmAndBiasParams* DeepCopy(bool duplicate_inputs) const { + GemmAndBiasParams* copy = new GemmAndBiasParams(*this); + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + size_t c_size = GetSizeC(); + copy->c = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(c_size)); + AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync( + copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true)); + if (duplicate_inputs) { + size_t a_size = GetSizeA(); + size_t b_size = GetSizeB(); + copy->a = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(a_size)); + copy->b = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(b_size)); + copy->duplicate_inputs_ = true; + } + return copy; + } + + // only call on object returned by DeepCopy + void Delete() { + c10::cuda::CUDACachingAllocator::raw_delete(c); + if (duplicate_inputs_) { + // NOLINTNEXTLINE(*const-cast) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(a)); + // NOLINTNEXTLINE(*const-cast) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(b)); + } + } + + TuningStatus NumericalCheck(GemmAndBiasParams *other) { + auto* ctx = getTuningContext(); + auto cfg = ctx->GetNumericalCheckConfig(); + auto c_dtype = c10::CppTypeToScalarType::value; + return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL; + } + + char transa{}; + char transb{}; + int64_t m{}; + int64_t n{}; + int64_t k{}; + at::opmath_type alpha{}; + const T* a{}; + int64_t lda{}; + const T* b{}; + int64_t ldb{}; + T* c{}; + int64_t ldc{}; + const T* bias{}; + at::cuda::blas::GEMMAndBiasActivationEpilogue activation{}; +private: + bool duplicate_inputs_{false}; +}; + +template +struct GemmStridedBatchedParams : OpParams { + GemmStridedBatchedParams() = default; + GemmStridedBatchedParams(const GemmStridedBatchedParams&) = default; + GemmStridedBatchedParams(GemmStridedBatchedParams&&) noexcept = default; + GemmStridedBatchedParams& operator=(const GemmStridedBatchedParams&) = default; + GemmStridedBatchedParams& operator=(GemmStridedBatchedParams&&) noexcept = default; + ~GemmStridedBatchedParams() override = default; + + std::string BLASSignature() const override { + std::string alpha_str = to_string_opmath(alpha); + std::string beta_str = to_string_opmath(beta); + return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: %ld, stride_b: %ld, stride_c: %ld, stride_d: %ld, " + "alpha: %s, beta: %s, transA: %c, transB: %c, batch_count: %ld, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, compute_type: %s }", + m, n, k, lda, ldb, ldc, ldc, stride_a, stride_b, stride_c, stride_c, alpha_str, beta_str, transa, transb, batch, + BLASTypeName(T{}), BLASTypeName(T{}), BLASTypeName(C_Dtype{}), BLASTypeName(T{}), ComputeTypeFor(), ComputeTypeFor()); + } + + std::string Signature() const override { + return fmt::sprintf("%c%c_%ld_%ld_%ld_B_%ld_ld_%ld_%ld_%ld", transa, transb, m, n, k, batch, lda, ldb, ldc); + } + + size_t GetSizeA() const { + size_t size_stride = stride_a * batch; + size_t size_dense = m * k * batch; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeB() const { + size_t size_stride = stride_b * batch; + size_t size_dense = k * n * batch; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeC() const { + size_t size_stride = stride_c * batch; + size_t size_dense = m * n * batch; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSize(bool duplicate_inputs) const { + size_t size = GetSizeC(); + if (duplicate_inputs) { + size += GetSizeA(); + size += GetSizeB(); + } + return size; + } + + GemmStridedBatchedParams* DeepCopy(bool duplicate_inputs) const { + GemmStridedBatchedParams* copy = new GemmStridedBatchedParams(*this); + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + size_t c_size = GetSizeC(); + copy->c = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(c_size)); + AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync( + copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true)); + if (duplicate_inputs) { + size_t a_size = GetSizeA(); + size_t b_size = GetSizeB(); + // NOLINTNEXTLINE(*const-cast*) + copy->a = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(a_size)); + // NOLINTNEXTLINE(*const-cast*) + copy->b = static_cast(c10::cuda::CUDACachingAllocator::raw_alloc(b_size)); + copy->duplicate_inputs_ = true; + } + return copy; + } + + // only call on object returned by DeepCopy + void Delete() { + c10::cuda::CUDACachingAllocator::raw_delete(c); + if (duplicate_inputs_) { + // NOLINTNEXTLINE(*const-cast*) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(a)); + // NOLINTNEXTLINE(*const-cast*) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(b)); + } + } + + TuningStatus NumericalCheck(GemmStridedBatchedParams *other) { + auto* ctx = getTuningContext(); + auto cfg = ctx->GetNumericalCheckConfig(); + auto c_dtype = c10::CppTypeToScalarType::value; + return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL; + } + + char transa{}; + char transb{}; + int64_t m{}; + int64_t n{}; + int64_t k{}; + at::opmath_type alpha{}; + const T* a{}; + int64_t lda{}; + int64_t stride_a{}; + const T* b{}; + int64_t ldb{}; + int64_t stride_b{}; + at::opmath_type beta; + C_Dtype* c{}; + int64_t ldc{}; + int64_t stride_c{}; + int64_t batch{}; +private: + bool duplicate_inputs_{false}; +}; + +template +struct ScaledGemmParams : OpParams { + ScaledGemmParams() = default; + ScaledGemmParams(const ScaledGemmParams&) = default; + ScaledGemmParams(ScaledGemmParams&&) noexcept = default; + ScaledGemmParams& operator=(const ScaledGemmParams&) = default; + ScaledGemmParams& operator=(ScaledGemmParams&&) noexcept = default; + ~ScaledGemmParams() override = default; + + std::string BLASSignature() const override { + // Excluding use_fast_accum and use_rowise booleans for now + if (bias_ptr == nullptr) { + return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, " + "transA: %c, transB: %c, batch_count: 1, scaleA: f32_r, scaleB: f32_r, a_type: %s, b_type: %s, c_type: %s, d_type: %s, scale_type: %s, compute_type: %s }", + m, n, k, lda, ldb, ldc, ldc, transa, transb, + ScalarTypeToBLASType(a_dtype), ScalarTypeToBLASType(b_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(c_dtype), + ComputeTypeFor(), ComputeTypeFor()); + } + else { + return fmt::sprintf("- { function: matmul, M: %ld, N: %ld, K: %ld, lda: %ld, ldb: %ld, ldc: %ld, ldd: %ld, stride_a: 0, stride_b: 0, stride_c: 0, stride_d: 0, " + "transA: %c, transB: %c, batch_count: 1, scaleA: f32_r, scaleB: f32_r, a_type: %s, b_type: %s, c_type: %s, d_type: %s, bias_type: %s, scale_type: %s, compute_type: %s }", + m, n, k, lda, ldb, ldc, ldc, transa, transb, + ScalarTypeToBLASType(a_dtype), ScalarTypeToBLASType(b_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(c_dtype), ScalarTypeToBLASType(bias_dtype), + ComputeTypeFor(), ComputeTypeFor()); + } + } + + std::string Signature() const override { + // In Blas.cpp, code defaults to a bias_dtype of Half even when there is no bias vector. + // Search for this line:: + // params.bias_dtype = bias ? bias->scalar_type() : isFloat8Type(out_dtype_) ? at::ScalarType::Half : out_dtype_; + // + // In TunableOp, we must distinguish in param signature these two cases: with and without a bias vector. + return fmt::sprintf("%c%c_%ld_%ld_%ld_ld_%ld_%ld_%ld_rw_%d_bias_%s", + transa, transb, m, n, k, lda, ldb, ldc, + a_scaling_type == ScalingType::RowWise && b_scaling_type == ScalingType::RowWise, + bias_ptr == nullptr ? "None" : at::toString(bias_dtype)); + } + + size_t GetSizeA() const { + size_t size_stride = lda * ((transa == 'n' || transa == 'N') ? k : m); + size_t size_dense = m * k; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeB() const { + size_t size_stride = ldb * ((transb == 'n' || transb == 'N') ? n : k); + size_t size_dense = k * n; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSizeC() const { + size_t size_stride = ldc * n; + size_t size_dense = m * n; + return sizeof(T) * (size_stride > size_dense ? size_stride : size_dense); + } + + size_t GetSize(bool duplicate_inputs) const { + size_t size = GetSizeC(); + if (duplicate_inputs) { + size += GetSizeA(); + size += GetSizeB(); + } + return size; + } + + ScaledGemmParams* DeepCopy(bool duplicate_inputs) const { + ScaledGemmParams* copy = new ScaledGemmParams(*this); + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + size_t c_size = GetSizeC(); + copy->c = c10::cuda::CUDACachingAllocator::raw_alloc(c_size); + AT_CUDA_CHECK(c10::cuda::CUDACachingAllocator::memcpyAsync( + copy->c, device, c, device, c_size, getCurrentCUDAStream(device), true)); + if (duplicate_inputs) { + size_t a_size = GetSizeA(); + size_t b_size = GetSizeB(); + copy->a = c10::cuda::CUDACachingAllocator::raw_alloc(a_size); + copy->b = c10::cuda::CUDACachingAllocator::raw_alloc(b_size); + copy->duplicate_inputs_ = true; + } + return copy; + } + + // only call on object returned by DeepCopy + void Delete() { + c10::cuda::CUDACachingAllocator::raw_delete(c); + if (duplicate_inputs_) { + // NOLINTNEXTLINE(*const-cast*) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(a)); + // NOLINTNEXTLINE(*const-cast*) + c10::cuda::CUDACachingAllocator::raw_delete(const_cast(b)); + } + } + + TuningStatus NumericalCheck(ScaledGemmParams *other) { + auto* ctx = getTuningContext(); + auto cfg = ctx->GetNumericalCheckConfig(); + return detail::NumericalCheck(c_dtype, c, other->c, GetSizeC()/sizeof(T), cfg) ? OK : FAIL; + } + + char transa{}; + char transb{}; + int64_t m{}; + int64_t n{}; + int64_t k{}; + const void* a{}; + const void* a_scale_ptr{}; + int64_t lda{}; + ScalarType a_dtype{}; + ScalarType a_scale_dtype{}; + ScalingType a_scaling_type{}; + const void* b{}; + const void* b_scale_ptr{}; + int64_t ldb{}; + ScalarType b_dtype{}; + ScalarType b_scale_dtype{}; + ScalingType b_scaling_type{}; + const void* bias_ptr{}; + ScalarType bias_dtype{}; + void* c{}; + const void* c_scale_ptr{}; + int64_t ldc{}; + ScalarType c_dtype{}; + void* amax_ptr{}; + bool use_fast_accum{}; +private: + bool duplicate_inputs_{false}; +}; + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmCublaslt.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmCublaslt.h new file mode 100644 index 0000000000000000000000000000000000000000..5543787820a0ccd0afb967fb4bf9b9369ffb1f30 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmCublaslt.h @@ -0,0 +1,841 @@ +#pragma once + +#ifndef USE_ROCM + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::cuda::tunable { + +namespace { + +template +int64_t CublasltBatchCount(const GemmParams* /*params*/) { + return 0; +} + +template +int64_t CublasltBatchCount(const GemmAndBiasParams* /*params*/) { + return 0; +} + +template +int64_t CublasltBatchCount( + const GemmStridedBatchedParams* params) { + return params->batch; +} + +template +int64_t CublasltStrideA(const GemmParams* /*params*/) { + return 0; +} + +template +int64_t CublasltStrideA(const GemmAndBiasParams* /*params*/) { + return 0; +} + +template +int64_t CublasltStrideA(const GemmStridedBatchedParams* params) { + return params->stride_a; +} + +template +int64_t CublasltStrideB(const GemmParams* /*params*/) { + return 0; +} + +template +int64_t CublasltStrideB(const GemmAndBiasParams* /*params*/) { + return 0; +} + +template +int64_t CublasltStrideB(const GemmStridedBatchedParams* params) { + return params->stride_b; +} + +template +int64_t CublasltStrideC(const GemmParams* /*params*/) { + return 0; +} + +template +int64_t CublasltStrideC(const GemmAndBiasParams* /*params*/) { + return 0; +} + +template +int64_t CublasltStrideC(const GemmStridedBatchedParams* params) { + return params->stride_c; +} + +template +at::opmath_type CublasltBeta(const GemmParams* params) { + return params->beta; +} + +template +at::opmath_type CublasltBeta( + const GemmStridedBatchedParams* params) { + return params->beta; +} + +template +at::opmath_type CublasltBeta(const GemmAndBiasParams* params) { + return params->bias ? 0 : 1; +} + +template +const void* CublasltBias(const ParamsT* /*params*/) { + return nullptr; +} + +template +const void* CublasltBias(const GemmAndBiasParams* params) { + return params->bias; +} + +template +at::cuda::blas::GEMMAndBiasActivationEpilogue CublasltActivation( + const ParamsT* /*params*/) { + return at::cuda::blas::GEMMAndBiasActivationEpilogue::None; +} + +template +at::cuda::blas::GEMMAndBiasActivationEpilogue CublasltActivation( + const GemmAndBiasParams* params) { + return params->activation; +} + +template +class CublasltStandardGemmProblem { + public: + CublasltStandardGemmProblem( + char transa, + char transb, + int64_t m, + int64_t n, + int64_t k, + at::opmath_type alpha, + const T* a, + int64_t lda, + int64_t stride_a, + const T* b, + int64_t ldb, + int64_t stride_b, + at::opmath_type beta, + C_Dtype* c, + int64_t ldc, + int64_t stride_c, + int64_t batch_count, + const void* bias, + at::cuda::blas::GEMMAndBiasActivationEpilogue activation, + bool set_epilogue_attribute) + : type_info_(at::cuda::blas::detail::getCublasLtTypeInfo()), + m_(m), + n_(n), + k_(k), + lda_(lda), + ldb_(ldb), + ldc_(ldc), + stride_a_(stride_a), + stride_b_(stride_b), + stride_c_(stride_c), + batch_count_(batch_count), + a_(a), + b_(b), + c_(c), + alpha_(alpha), + beta_(beta), + opa_(at::cuda::blas::detail::cublasOpFromChar(transa)), + opb_(at::cuda::blas::detail::cublasOpFromChar(transb)), + compute_desc_(type_info_.compute_type, type_info_.scale_type), + bias_(bias), + activation_(activation), + set_epilogue_attribute_(set_epilogue_attribute) { + at::cuda::blas::detail::cublasAdjustLdLevel3( + transa, transb, m_, n_, k_, &lda_, &ldb_, &ldc_); + initialize(); + } + + cublasComputeType_t compute_type() const { + return type_info_.compute_type; + } + + cudaDataType_t scale_type() const { + return type_info_.scale_type; + } + + cudaDataType_t a_type() const { + return type_info_.ab_type; + } + + cudaDataType_t b_type() const { + return type_info_.ab_type; + } + + cudaDataType_t c_type() const { + return type_info_.c_type; + } + + cudaDataType_t d_type() const { + return type_info_.c_type; + } + + cublasLtMatmulDesc_t compute_desc() const { + return compute_desc_.descriptor(); + } + + cublasLtMatrixLayout_t adesc() const { + return adesc_->descriptor(); + } + + cublasLtMatrixLayout_t bdesc() const { + return bdesc_->descriptor(); + } + + cublasLtMatrixLayout_t cdesc() const { + return cdesc_->descriptor(); + } + + cublasLtMatrixLayout_t ddesc() const { + return cdesc(); + } + + cublasLtMatrixLayout_t heuristic_bdesc() const { + return lie_to_cublaslt_ ? fake_bdesc_->descriptor() : bdesc(); + } + + cublasLtMatrixLayout_t heuristic_cdesc() const { + return lie_to_cublaslt_ ? fake_cdesc_->descriptor() : cdesc(); + } + + cublasLtMatrixLayout_t heuristic_ddesc() const { + return heuristic_cdesc(); + } + + cublasLtMatmulPreference_t preference() const { + return preference_.descriptor(); + } + + void* alpha_ptr() const { + return alpha_ptr_; + } + + void* beta_ptr() const { + return beta_ptr_; + } + + const T* a() const { + return a_; + } + + const T* b() const { + return b_; + } + + C_Dtype* c() const { + return c_; + } + + C_Dtype* d() const { + return c_; + } + + void* workspace() const { + return workspace_.ptr; + } + + size_t workspace_size() const { + return workspace_.size; + } + + private: + void initialize() { + alpha_ptr_ = &alpha_; + beta_ptr_ = &beta_; + if constexpr (std::is_same_v) { + if (type_info_.compute_type == CUBLAS_COMPUTE_16F) { + halpha_ = alpha_; + hbeta_ = beta_; + alpha_ptr_ = &halpha_; + beta_ptr_ = &hbeta_; + } + } + + compute_desc_.setAttribute(CUBLASLT_MATMUL_DESC_TRANSA, opa_); + compute_desc_.setAttribute(CUBLASLT_MATMUL_DESC_TRANSB, opb_); + if (set_epilogue_attribute_ || bias_ != nullptr || + activation_ != at::cuda::blas::GEMMAndBiasActivationEpilogue::None) { + epilogue_ = + at::cuda::blas::detail::cublasLtEpilogue(activation_, bias_); + compute_desc_.setAttribute(CUBLASLT_MATMUL_DESC_EPILOGUE, epilogue_); + } + if (bias_ != nullptr) { + compute_desc_.setAttribute(CUBLASLT_MATMUL_DESC_BIAS_POINTER, bias_); + } + + if (at::globalContext()._SMCarveout_EXPERIMENTAL().has_value()) { + compute_desc_.setAttribute( + CUBLASLT_MATMUL_DESC_SM_COUNT_TARGET, + at::cuda::getCurrentDeviceProperties()->multiProcessorCount - + at::globalContext()._SMCarveout_EXPERIMENTAL().value()); + } + + if constexpr (std::is_same_v) { + auto fp16_reduction = at::globalContext().allowFP16ReductionCuBLAS(); + if (fp16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + reduction_mask_ = + fp16_reduction == + at::CuBLASReductionOption:: + DisallowReducedPrecisionAllowSplitK + ? (CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE | + CUBLASLT_REDUCTION_SCHEME_NONE) + : CUBLASLT_REDUCTION_SCHEME_NONE; + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_REDUCTION_SCHEME_MASK, reduction_mask_); + } + } else if constexpr (std::is_same_v) { + auto bf16_reduction = at::globalContext().allowBF16ReductionCuBLAS(); + if (bf16_reduction != + at::CuBLASReductionOption::AllowReducedPrecisionWithSplitK) { + reduction_mask_ = + bf16_reduction == + at::CuBLASReductionOption:: + DisallowReducedPrecisionAllowSplitK + ? (CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE | + CUBLASLT_REDUCTION_SCHEME_NONE) + : CUBLASLT_REDUCTION_SCHEME_NONE; + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_REDUCTION_SCHEME_MASK, reduction_mask_); + } + } + + adesc_ = std::make_unique( + type_info_.ab_type, m_, k_, lda_, opa_ != CUBLAS_OP_N); + bdesc_ = std::make_unique( + type_info_.ab_type, k_, n_, ldb_, opb_ != CUBLAS_OP_N); + cdesc_ = std::make_unique( + type_info_.c_type, m_, n_, ldc_); + + if (batch_count_ > 1) { + int batch_as_int = static_cast(batch_count_); + adesc_->setAttribute(CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, batch_as_int); + bdesc_->setAttribute(CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, batch_as_int); + cdesc_->setAttribute(CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, batch_as_int); + adesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stride_a_); + bdesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stride_b_); + cdesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stride_c_); + } + + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_A_BYTES, + at::cuda::blas::detail::getAlignment(reinterpret_cast(a_))); + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_B_BYTES, + at::cuda::blas::detail::getAlignment(reinterpret_cast(b_))); + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_C_BYTES, + at::cuda::blas::detail::getAlignment(reinterpret_cast(c_))); + if (bias_ != nullptr) { + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_MIN_ALIGNMENT_D_BYTES, + at::cuda::blas::detail::getAlignment( + reinterpret_cast(bias_))); + } + + preference_.setAttribute( + CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, workspace_.size); + + lie_to_cublaslt_ = reduction_mask_ == CUBLASLT_REDUCTION_SCHEME_NONE && + n_ == 1 && at::cuda::getCurrentDeviceProperties()->major >= 10; + if (lie_to_cublaslt_) { + const auto fake_ldb = ldb_ == 1 ? 2 : ldb_; + const auto fake_ldc = ldc_ == 1 ? 2 : ldc_; + fake_bdesc_ = + std::make_unique( + type_info_.ab_type, k_, 2, fake_ldb, opb_ == CUBLAS_OP_T); + fake_cdesc_ = + std::make_unique( + type_info_.c_type, m_, 2, fake_ldc); + if (batch_count_ > 1) { + int batch_as_int = static_cast(batch_count_); + fake_bdesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, batch_as_int); + fake_cdesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, batch_as_int); + fake_bdesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stride_b_); + fake_cdesc_->setAttribute( + CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, stride_c_); + } + } + } + + at::cuda::blas::detail::CublasLtTypeInfo type_info_; + int64_t m_; + int64_t n_; + int64_t k_; + int64_t lda_; + int64_t ldb_; + int64_t ldc_; + int64_t stride_a_; + int64_t stride_b_; + int64_t stride_c_; + int64_t batch_count_; + const T* a_; + const T* b_; + C_Dtype* c_; + at::opmath_type alpha_; + at::opmath_type beta_; + at::Half halpha_; + at::Half hbeta_; + void* alpha_ptr_ = nullptr; + void* beta_ptr_ = nullptr; + uint32_t reduction_mask_ = std::numeric_limits::max(); + cublasOperation_t opa_; + cublasOperation_t opb_; + at::cuda::blas::detail::CuBlasLtMatmulDescriptor compute_desc_; + at::cuda::blas::detail::CuBlasLtMatmulPreference preference_; + const void* bias_ = nullptr; + at::cuda::blas::GEMMAndBiasActivationEpilogue activation_; + bool set_epilogue_attribute_; + cublasLtEpilogue_t epilogue_ = CUBLASLT_EPILOGUE_DEFAULT; + std::unique_ptr adesc_; + std::unique_ptr bdesc_; + std::unique_ptr cdesc_; + std::unique_ptr fake_bdesc_; + std::unique_ptr fake_cdesc_; + at::cuda::blas::detail::CublasLtWorkspace workspace_; + bool lie_to_cublaslt_ = false; +}; + +template +auto MakeCublasltStandardGemmProblem(const ParamsT* params) { + return CublasltStandardGemmProblem( + params->transa, + params->transb, + params->m, + params->n, + params->k, + params->alpha, + params->a, + params->lda, + CublasltStrideA(params), + params->b, + params->ldb, + CublasltStrideB(params), + CublasltBeta(params), + params->c, + params->ldc, + CublasltStrideC(params), + CublasltBatchCount(params), + CublasltBias(params), + CublasltActivation(params), + true /* set_epilogue_attribute */); +} + +template +auto MakeCublasltStandardGemmProblem( + const GemmStridedBatchedParams* params) { + return CublasltStandardGemmProblem( + params->transa, + params->transb, + params->m, + params->n, + params->k, + params->alpha, + params->a, + params->lda, + params->stride_a, + params->b, + params->ldb, + params->stride_b, + params->beta, + params->c, + params->ldc, + params->stride_c, + params->batch, + nullptr, + at::cuda::blas::GEMMAndBiasActivationEpilogue::None, + // Keep batched GEMM descriptor behavior aligned with the legacy path; + // setting EPILOGUE_DEFAULT changes some cuBLASLt heuristic results. + false /* set_epilogue_attribute */); +} + + +struct CublasltAlgoConfig { + int32_t id = 0; + uint32_t tile = 0; + uint32_t stages = 0; + int32_t splitk = 1; + uint32_t reduction = 0; + uint32_t swizzle = 0; + uint32_t custom = 0; +#if defined(CUBLAS_VERSION) && CUBLAS_VERSION >= 12000 + uint16_t inner_shape = 0; + uint16_t cluster_shape = 0; +#endif +}; + +template +bool CublasltGetAlgoConfigAttribute( + const cublasLtMatmulAlgo_t* algo, + cublasLtMatmulAlgoConfigAttributes_t attr, + T* value) { + size_t written = 0; + return cublasLtMatmulAlgoConfigGetAttribute( + algo, attr, value, sizeof(T), &written) == CUBLAS_STATUS_SUCCESS; +} + +inline std::optional CublasltAlgoConfigFromAlgo( + const cublasLtMatmulAlgo_t& algo) { + CublasltAlgoConfig config; + bool ok = + CublasltGetAlgoConfigAttribute(&algo, CUBLASLT_ALGO_CONFIG_ID, &config.id) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_TILE_ID, &config.tile) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_STAGES_ID, &config.stages) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_SPLITK_NUM, &config.splitk) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME, &config.reduction) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, &config.swizzle) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_CUSTOM_OPTION, &config.custom); +#if defined(CUBLAS_VERSION) && CUBLAS_VERSION >= 12000 + ok = ok && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_INNER_SHAPE_ID, &config.inner_shape) && + CublasltGetAlgoConfigAttribute( + &algo, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &config.cluster_shape); +#endif + if (!ok) { + return std::nullopt; + } + return config; +} + +inline std::string CublasltAlgoConfigName(const CublasltAlgoConfig& config) { + std::string name = fmt::sprintf( + "Gemm_Cublaslt_id_%d_tile_%u_stages_%u_splitk_%d_red_%u_swizzle_%u_custom_%u", + config.id, + config.tile, + config.stages, + config.splitk, + config.reduction, + config.swizzle, + config.custom); +#if defined(CUBLAS_VERSION) && CUBLAS_VERSION >= 12000 + name += fmt::sprintf( + "_inner_%hu_cluster_%hu", config.inner_shape, config.cluster_shape); +#endif + return name; +} + +inline std::optional CublasltAlgoConfigFromName( + const std::string& name) { + CublasltAlgoConfig config; +#if defined(CUBLAS_VERSION) && CUBLAS_VERSION >= 12000 + int matched = std::sscanf( + name.c_str(), + "Gemm_Cublaslt_id_%d_tile_%u_stages_%u_splitk_%d_red_%u_swizzle_%u_custom_%u" + "_inner_%hu_cluster_%hu", + &config.id, + &config.tile, + &config.stages, + &config.splitk, + &config.reduction, + &config.swizzle, + &config.custom, + &config.inner_shape, + &config.cluster_shape); + if (matched != 9) { + return std::nullopt; + } +#else + int matched = std::sscanf( + name.c_str(), + "Gemm_Cublaslt_id_%d_tile_%u_stages_%u_splitk_%d_red_%u_swizzle_%u_custom_%u", + &config.id, + &config.tile, + &config.stages, + &config.splitk, + &config.reduction, + &config.swizzle, + &config.custom); + if (matched != 7) { + return std::nullopt; + } +#endif + return config; +} + +template +bool CublasltSetAlgoConfigAttribute( + cublasLtMatmulAlgo_t* algo, + cublasLtMatmulAlgoConfigAttributes_t attr, + const T& value) { + return cublasLtMatmulAlgoConfigSetAttribute( + algo, attr, &value, sizeof(value)) == CUBLAS_STATUS_SUCCESS; +} + +template +bool CublasltInitializeAlgo( + const ProblemT& problem, + const CublasltAlgoConfig& config, + cublasLtMatmulAlgo_t* algo) { + auto status = cublasLtMatmulAlgoInit( + at::cuda::getCurrentCUDABlasLtHandle(), + problem.compute_type(), + problem.scale_type(), + problem.a_type(), + problem.b_type(), + problem.c_type(), + problem.d_type(), + config.id, + algo); + if (status != CUBLAS_STATUS_SUCCESS) { + return false; + } + + bool ok = + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_TILE_ID, config.tile) && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_STAGES_ID, config.stages) && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_SPLITK_NUM, config.splitk) && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME, config.reduction) && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, config.swizzle) && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_CUSTOM_OPTION, config.custom); +#if defined(CUBLAS_VERSION) && CUBLAS_VERSION >= 12000 + ok = ok && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_INNER_SHAPE_ID, config.inner_shape) && + CublasltSetAlgoConfigAttribute( + algo, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, config.cluster_shape); +#endif + return ok; +} + +template +bool CublasltValidateAlgo( + const ProblemT& problem, + cublasLtMatmulAlgo_t* algo) { + cublasLtMatmulHeuristicResult_t check_result = {}; + auto status = cublasLtMatmulAlgoCheck( + at::cuda::getCurrentCUDABlasLtHandle(), + problem.compute_desc(), + problem.adesc(), + problem.bdesc(), + problem.cdesc(), + problem.ddesc(), + algo, + &check_result); + return status == CUBLAS_STATUS_SUCCESS && + check_result.workspaceSize <= problem.workspace_size(); +} + +template +struct CublasltStandardGemmProblemFactory { + template + auto operator()(const ParamsT* params) const { + return MakeCublasltStandardGemmProblem(params); + } +}; + + +template +class CublasltMatmulOp : public Callable { + public: + explicit CublasltMatmulOp(std::string name) + : name_(std::move(name)), config_(CublasltAlgoConfigFromName(name_)) {} + + CublasltMatmulOp(std::string name, CublasltAlgoConfig config) + : name_(std::move(name)), config_(config) {} + + TuningStatus Call(const ParamsT* params) override { + auto problem = problem_factory_(params); + if (problem.workspace() == nullptr) { + return FAIL; + } + cublasLtMatmulAlgo_t algo = {}; + if (!InitializeAlgo(problem, &algo)) { + return FAIL; + } + auto status = cublasLtMatmul( + at::cuda::getCurrentCUDABlasLtHandle(), + problem.compute_desc(), + problem.alpha_ptr(), + problem.a(), + problem.adesc(), + problem.b(), + problem.bdesc(), + problem.beta_ptr(), + problem.c(), + problem.cdesc(), + problem.d(), + problem.ddesc(), + &algo, + problem.workspace(), + problem.workspace_size(), + at::cuda::getCurrentCUDAStream()); + return status == CUBLAS_STATUS_SUCCESS ? OK : FAIL; + } + + private: + template + bool InitializeAlgo(const ProblemT& problem, cublasLtMatmulAlgo_t* algo) { + if (!config_.has_value() || + !CublasltInitializeAlgo(problem, config_.value(), algo) || + !CublasltValidateAlgo(problem, algo)) { + return false; + } + return true; + } + + ProblemFactory problem_factory_; + std::string name_; + std::optional config_; +}; + +template +std::vector> +GetCublasltHeuristicCandidates(const ProblemT& problem) { + std::vector> ret; + if (problem.workspace() == nullptr) { + return ret; + } + + std::vector heuristic_results( + getTuningContext()->GetCublasLtRequestedAlgoCount()); + int returned_result = 0; + auto status = cublasLtMatmulAlgoGetHeuristic( + at::cuda::getCurrentCUDABlasLtHandle(), + problem.compute_desc(), + problem.adesc(), + problem.heuristic_bdesc(), + problem.heuristic_cdesc(), + problem.heuristic_ddesc(), + problem.preference(), + static_cast(heuristic_results.size()), + heuristic_results.data(), + &returned_result); + if (status != CUBLAS_STATUS_SUCCESS || returned_result == 0) { + return ret; + } + + for (int i = 0; i < returned_result; ++i) { + if (heuristic_results[i].state != CUBLAS_STATUS_SUCCESS) { + continue; + } + auto config = CublasltAlgoConfigFromAlgo(heuristic_results[i].algo); + if (!config.has_value()) { + continue; + } + ret.emplace_back(CublasltAlgoConfigName(config.value()), config.value()); + } + return ret; +} + +} // anonymous namespace + +template +class CublasltMatmulTunableOp : public TunableOp { + public: + CublasltMatmulTunableOp() = default; + + protected: + void RegisterOpCandidates(const ParamsT* params) override { + const auto params_sig = params->Signature(); + std::scoped_lock l{candidate_lock_}; + if (candidate_names_by_params_.find(params_sig) != + candidate_names_by_params_.end()) { + return; + } + + std::vector candidate_names{"Default"}; + auto problem = problem_factory_(params); + for (auto&& [name, config] : GetCublasltHeuristicCandidates(problem)) { + if (!this->HasOp(name)) { + this->RegisterOp( + name, + std::make_unique>( + name, config)); + } + candidate_names.emplace_back(std::move(name)); + } + candidate_names_by_params_.emplace(params_sig, std::move(candidate_names)); + } + + std::vector CandidateNames(const ParamsT* params) const override { + const auto params_sig = params->Signature(); + std::scoped_lock l{candidate_lock_}; + auto it = candidate_names_by_params_.find(params_sig); + if (it == candidate_names_by_params_.end()) { + return {"Default"}; + } + return it->second; + } + + bool RegisterOpForResult( + const ResultEntry& result, + const ParamsT* /*params*/) override { + const auto name = result.GetKey(); + if (this->HasOp(name)) { + return true; + } + if (!CublasltAlgoConfigFromName(name).has_value()) { + return false; + } + this->RegisterOp( + name, + std::make_unique>(name)); + return true; + } + + private: + ProblemFactory problem_factory_; + mutable std::mutex candidate_lock_; + std::unordered_map> + candidate_names_by_params_; +}; + +template +class CublasltGemmTunableOp + : public CublasltMatmulTunableOp< + ParamsT, + CublasltStandardGemmProblemFactory> {}; + + +} // namespace at::cuda::tunable + +#endif // USE_ROCM diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmHipblaslt.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmHipblaslt.h new file mode 100644 index 0000000000000000000000000000000000000000..b5a79027d1c40069f62e72410cd3d815fff4002a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmHipblaslt.h @@ -0,0 +1,708 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define TORCH_HIPBLASLT_CHECK(EXPR) \ + do { \ + hipblasStatus_t __err = EXPR; \ + TORCH_CHECK(__err == HIPBLAS_STATUS_SUCCESS, \ + "hipblaslt error: ", \ + hipblasStatusToString(__err), \ + " when calling `" #EXPR "`"); \ + } while (0) + +namespace at::cuda::tunable { + +template +constexpr hipDataType HipDataTypeFor(); + +template <> +constexpr hipDataType HipDataTypeFor() { + return HIP_R_32F; +} + +template <> +constexpr hipDataType HipDataTypeFor() { + return HIP_R_16F; +} + +template <> +constexpr hipDataType HipDataTypeFor() { + return HIP_R_16BF; +} + +template <> +constexpr hipDataType HipDataTypeFor>() { + return HIP_C_16BF; +} + +template <> +constexpr hipDataType HipDataTypeFor() { + return HIP_R_64F; +} + +template <> +constexpr hipDataType HipDataTypeFor() { + return HIP_R_8F_E4M3_FNUZ; +} + +template <> +constexpr hipDataType HipDataTypeFor() { + return HIP_R_8F_E5M2_FNUZ; +} + +// This code is instantiated regardless of ROCm version. +// Prior to ROCm 6.3, we hard-code the known enum values. +template <> +constexpr hipDataType HipDataTypeFor() { +#if ROCM_VERSION >= 60300 + return HIP_R_8F_E4M3; +#else + return static_cast(28); +#endif +} + +template <> +constexpr hipDataType HipDataTypeFor() { +#if ROCM_VERSION >= 60300 + return HIP_R_8F_E5M2; +#else + return static_cast(29); +#endif +} + +// This type is not intended for matrix types but rather a scale factor. +// Return a dummy value to satisfy linker. +template <> +constexpr hipDataType HipDataTypeFor() { + return static_cast(500); +} + +template <> +constexpr hipDataType HipDataTypeFor() { +#if ROCM_VERSION >= 70000 + return HIP_R_4F_E2M1; +#else + return static_cast(33); +#endif +} + +template +constexpr hipblasComputeType_t HipBlasComputeTypeFor() { + return HIPBLAS_COMPUTE_32F; +} + +template <> +constexpr hipblasComputeType_t HipBlasComputeTypeFor() { + return HIPBLAS_COMPUTE_64F; +} + +template +int GetBatchFromParams(const GemmParams* params) { + return 1; +} + +template +int GetBatchFromParams(const GemmAndBiasParams* params) { + return 1; +} + +template +int GetBatchFromParams(const GemmStridedBatchedParams* params) { + return params->batch; +} + +template +int GetBatchFromParams(const ScaledGemmParams* params) { + return 1; +} + +template +int GetStrideAFromParams(const GemmParams* params) { + return 1; +} + +template +int GetStrideAFromParams(const GemmAndBiasParams* params) { + return 1; +} + +template +int GetStrideAFromParams(const GemmStridedBatchedParams* params) { + return params->stride_a; +} + +template +int GetStrideAFromParams(const ScaledGemmParams* params) { + return 1; +} + +template +int GetStrideBFromParams(const GemmParams* params) { + return 1; +} + +template +int GetStrideBFromParams(const GemmAndBiasParams* params) { + return 1; +} + +template +int GetStrideBFromParams(const GemmStridedBatchedParams* params) { + return params->stride_b; +} + +template +int GetStrideBFromParams(const ScaledGemmParams* params) { + return 1; +} + +template +int GetStrideCFromParams(const GemmParams* params) { + return 1; +} + +template +int GetStrideCFromParams(const GemmAndBiasParams* params) { + return 1; +} + +template +int GetStrideCFromParams(const GemmStridedBatchedParams* params) { + return params->stride_c; +} + +template +int GetStrideCFromParams(const ScaledGemmParams* params) { + return 1; +} + +template +at::opmath_type GetAlphaFromParams(const GemmParams* params) { + return params->alpha; +} + +template +at::opmath_type GetAlphaFromParams(const GemmAndBiasParams* params) { + return params->alpha; +} + +template +at::opmath_type GetAlphaFromParams(const GemmStridedBatchedParams* params) { + return params->alpha; +} + +template +at::opmath_type GetAlphaFromParams(const ScaledGemmParams* params) { + return at::opmath_type{1.0}; +} + +template +at::opmath_type GetBetaFromParams(const GemmParams* params) { + return params->beta; +} + +template +at::opmath_type GetBetaFromParams(const GemmAndBiasParams* params) { + return at::opmath_type{0.0}; +} + +template +at::opmath_type GetBetaFromParams(const GemmStridedBatchedParams* params) { + return params->beta; +} + +template +at::opmath_type GetBetaFromParams(const ScaledGemmParams* params) { + return at::opmath_type{0.0}; +} + +template +ScalingType GetAScalingTypeFromParams(const GemmParams* params) { + return ScalingType::TensorWise; +} + +template +ScalingType GetBScalingTypeFromParams(const GemmParams* params) { + return ScalingType::TensorWise; +} + +template +ScalingType GetAScalingTypeFromParams(const GemmAndBiasParams* params) { + return ScalingType::TensorWise; +} + +template +ScalingType GetBScalingTypeFromParams(const GemmAndBiasParams* params) { + return ScalingType::TensorWise; +} + +template +ScalingType GetAScalingTypeFromParams(const GemmStridedBatchedParams* params) { + return ScalingType::TensorWise; +} + +template +ScalingType GetBScalingTypeFromParams(const GemmStridedBatchedParams* params) { + return ScalingType::TensorWise; +} + +template +ScalingType GetAScalingTypeFromParams(const ScaledGemmParams* params) { + return params->a_scaling_type; +} + +template +ScalingType GetBScalingTypeFromParams(const ScaledGemmParams* params) { + return params->b_scaling_type; +} + +template +const void* GetAScalePointerFromParams(const GemmParams* params) { + return nullptr; +} + +template +const void* GetAScalePointerFromParams(const GemmAndBiasParams* params) { + return nullptr; +} + +template +const void* GetAScalePointerFromParams(const GemmStridedBatchedParams* params) { + return nullptr; +} + +template +const void* GetAScalePointerFromParams(const ScaledGemmParams* params) { + return params->a_scale_ptr; +} + +template +const void* GetBScalePointerFromParams(const GemmParams* params) { + return nullptr; +} + +template +const void* GetBScalePointerFromParams(const GemmAndBiasParams* params) { + return nullptr; +} + +template +const void* GetBScalePointerFromParams(const GemmStridedBatchedParams* params) { + return nullptr; +} + +template +const void* GetBScalePointerFromParams(const ScaledGemmParams* params) { + return params->b_scale_ptr; +} + +template +const void* GetDScalePointerFromParams(const GemmParams* params) { + return nullptr; +} + +template +const void* GetDScalePointerFromParams(const GemmAndBiasParams* params) { + return nullptr; +} + +template +const void* GetDScalePointerFromParams(const GemmStridedBatchedParams* params) { + return nullptr; +} + +template +const void* GetDScalePointerFromParams(const ScaledGemmParams* params) { + return params->c_scale_ptr; +} + +template +const void* GetBiasPointerFromParams(const GemmParams* params) { + return nullptr; +} + +template +const void* GetBiasPointerFromParams(const GemmAndBiasParams* params) { + return params->bias; +} + +template +const void* GetBiasPointerFromParams(const GemmStridedBatchedParams* params) { + return nullptr; +} + +template +const void* GetBiasPointerFromParams(const ScaledGemmParams* params) { + return params->bias_ptr; +} + +template +hipDataType GetBiasTypeFromParams(const GemmParams* params) { + return HIP_R_32F; +} + +template +hipDataType GetBiasTypeFromParams(const GemmAndBiasParams* params) { + return HipDataTypeFor(); +} + +template +hipDataType GetBiasTypeFromParams(const GemmStridedBatchedParams* params) { + return HIP_R_32F; +} + +template +hipDataType GetBiasTypeFromParams(const ScaledGemmParams* params) { + return at::cuda::ScalarTypeToCudaDataType(params->bias_dtype); +} + +template +at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const GemmParams* params) { + return at::cuda::blas::GEMMAndBiasActivationEpilogue::None; +} + +template +at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const GemmAndBiasParams* params) { + return params->activation; +} + +template +at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const GemmStridedBatchedParams* params) { + return at::cuda::blas::GEMMAndBiasActivationEpilogue::None; +} + +template +at::cuda::blas::GEMMAndBiasActivationEpilogue GetActivationFromParams(const ScaledGemmParams* params) { + return at::cuda::blas::GEMMAndBiasActivationEpilogue::None; +} + +static hipblasOperation_t _hipblasOpFromChar(char op) { + switch (op) { + case 'n': + case 'N': + return HIPBLAS_OP_N; + case 't': + case 'T': + return HIPBLAS_OP_T; + case 'c': + case 'C': + return HIPBLAS_OP_C; + } + TORCH_CHECK(false, + "_hipblasOpFromChar input should be 't', 'n' or 'c' but got `", op, "`"); +} + +static char _charFromhipblasOp(hipblasOperation_t op) { + switch (op) { + case HIPBLAS_OP_N: + return 'N'; + case HIPBLAS_OP_T: + return 'T'; + case HIPBLAS_OP_C: + return 'C'; + } + TORCH_CHECK(false, + "_charFromhipblasOp input should be HIPBLAS_OP_N/T/C but got `", op, "`"); +} + +static hipblasOperation_t MapLayoutToHipBlasLt(BlasOp layout) { + if (layout == BlasOp::N) { + return HIPBLAS_OP_N; + } + return HIPBLAS_OP_T; +} + +template +struct HipBlasLtDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_CUDABLAS_CHECK(destructor(x)); + } + } +}; + +template +class HipBlasLtDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; + +class HipBlasLtMatmulDescriptor : public HipBlasLtDescriptor< + hipblasLtMatmulDescOpaque_t, + &hipblasLtMatmulDescDestroy> { + public: + HipBlasLtMatmulDescriptor( + hipblasComputeType_t compute_type, + hipDataType scale_type) { + hipblasLtMatmulDesc_t raw_descriptor = nullptr; + TORCH_HIPBLASLT_CHECK( + hipblasLtMatmulDescCreate(&raw_descriptor, compute_type, scale_type)); + descriptor_.reset(raw_descriptor); + } + template + inline void setAttribute(hipblasLtMatmulDescAttributes_t attr, const T value) { + TORCH_HIPBLASLT_CHECK(::hipblasLtMatmulDescSetAttribute(descriptor(), attr, &value, sizeof(T))); + } +}; + +template +class HipblasltGemmOp : public Callable { + public: + HipblasltGemmOp(hipblasLtMatmulAlgo_t algo) : algo_{algo} {} + + TuningStatus Call(const ParamsT* params) override { + hipblasOperation_t transa_outer = MapLayoutToHipBlasLt(ALayout); + hipblasOperation_t transb_outer = MapLayoutToHipBlasLt(BLayout); + auto a_datatype = HipDataTypeFor(); + auto b_datatype = HipDataTypeFor(); + auto in_out_datatype = HipDataTypeFor(); + auto opa = _hipblasOpFromChar(params->transa); + auto opb = _hipblasOpFromChar(params->transb); + + TORCH_CHECK(transa_outer == opa && transb_outer == opb, "trans mismatch, shouldn't happen"); + + using opmath_t = at::opmath_type; + opmath_t alpha = GetAlphaFromParams(params); + opmath_t beta = GetBetaFromParams(params); + + hipblasLtMatrixLayout_t mat_a, mat_b, mat_c; + if (opa == HIPBLAS_OP_N) { + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_a, a_datatype, params->m, params->k, params->lda)); + } + else { + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_a, a_datatype, params->k, params->m, params->lda)); + } + if (opb == HIPBLAS_OP_N) { + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_b, b_datatype, params->k, params->n, params->ldb)); + } + else { + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_b, b_datatype, params->n, params->k, params->ldb)); + } + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutCreate(&mat_c, in_out_datatype, params->m, params->n, params->ldc)); + + // specific to batched gemmm + int batch = GetBatchFromParams(params); + if (batch > 1) { + int64_t stride_a = GetStrideAFromParams(params); + int64_t stride_b = GetStrideBFromParams(params); + int64_t stride_c = GetStrideCFromParams(params); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute( + mat_a, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &batch, sizeof(batch))); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute( + mat_a, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride_a, sizeof(stride_a))); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute( + mat_b, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &batch, sizeof(batch))); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute( + mat_b, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride_b, sizeof(stride_b))); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute( + mat_c, HIPBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &batch, sizeof(batch))); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutSetAttribute( + mat_c, HIPBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride_c, sizeof(stride_c))); + } + + hipblasComputeType_t computeType = HipBlasComputeTypeFor(); + if constexpr (std::is_same_v) { + if (at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) == at::Float32Precision::TF32) { + computeType = HIPBLAS_COMPUTE_32F_FAST_TF32; + } + } + auto scale_type = HipDataTypeFor(); + HipBlasLtMatmulDescriptor matmul(computeType, scale_type); + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_TRANSA, opa); + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_TRANSB, opb); + + // specific to scaled gemm + const void* mat1_scale_ptr = GetAScalePointerFromParams(params); + const void* mat2_scale_ptr = GetBScalePointerFromParams(params); + const void* result_scale_ptr = GetDScalePointerFromParams(params); + if (mat1_scale_ptr && mat2_scale_ptr) { + hipblasLtMatmulDescAttributes_t a_scale_ptr_desc = HIPBLASLT_MATMUL_DESC_A_SCALE_POINTER; + hipblasLtMatmulDescAttributes_t b_scale_ptr_desc = HIPBLASLT_MATMUL_DESC_B_SCALE_POINTER; + if (GetAScalingTypeFromParams(params) == ScalingType::RowWise) { +#if defined(HIPBLASLT_OUTER_VEC) + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_A_SCALE_MODE, HIPBLASLT_MATMUL_MATRIX_SCALE_OUTER_VEC_32F); +#elif defined(HIPBLASLT_VEC_EXT) + a_scale_ptr_desc = HIPBLASLT_MATMUL_DESC_A_SCALE_POINTER_VEC_EXT; +#endif + } + if (GetBScalingTypeFromParams(params) == ScalingType::RowWise) { +#if defined(HIPBLASLT_OUTER_VEC) + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_B_SCALE_MODE, HIPBLASLT_MATMUL_MATRIX_SCALE_OUTER_VEC_32F); +#elif defined(HIPBLASLT_VEC_EXT) + b_scale_ptr_desc = HIPBLASLT_MATMUL_DESC_B_SCALE_POINTER_VEC_EXT; +#endif + } + matmul.setAttribute(a_scale_ptr_desc, mat1_scale_ptr); + matmul.setAttribute(b_scale_ptr_desc, mat2_scale_ptr); + } + if (result_scale_ptr) { + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_D_SCALE_POINTER, result_scale_ptr); + } + + const void* bias_ptr = GetBiasPointerFromParams(params); + auto bias_datatype = GetBiasTypeFromParams(params); + if (bias_ptr) { + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_BIAS_POINTER, bias_ptr); + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_BIAS_DATA_TYPE, bias_datatype); + auto activation = GetActivationFromParams(params); + if (activation == at::cuda::blas::GEMMAndBiasActivationEpilogue::RELU) { + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_EPILOGUE, HIPBLASLT_EPILOGUE_RELU_BIAS); + } + else if (activation == at::cuda::blas::GEMMAndBiasActivationEpilogue::GELU) { + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_EPILOGUE, HIPBLASLT_EPILOGUE_GELU_BIAS); + } + else { + matmul.setAttribute(HIPBLASLT_MATMUL_DESC_EPILOGUE, HIPBLASLT_EPILOGUE_BIAS); + } + } + + size_t workspace_size = at::cuda::getCUDABlasLtWorkspaceSize(); + + auto op_handle = at::cuda::getCurrentCUDABlasLtHandle(); + + size_t ret_workspace_size = 0; + auto status = hipblaslt_ext::matmulIsAlgoSupported(op_handle, + matmul.descriptor(), + &alpha, + mat_a, + mat_b, + &beta, + mat_c, + mat_c, + algo_, + ret_workspace_size); + + if (status == HIPBLAS_STATUS_SUCCESS) { + if (ret_workspace_size >= workspace_size) { + return FAIL; + } + } + else { + return FAIL; + } + + void* workspace_buffer = at::cuda::getCUDABlasLtWorkspace(); + + TORCH_HIPBLASLT_CHECK(hipblasLtMatmul(op_handle, + matmul.descriptor(), + &alpha, + params->a, + mat_a, + params->b, + mat_b, + &beta, + params->c, + mat_c, + params->c, + mat_c, + &algo_, + workspace_buffer, + workspace_size, + at::cuda::getCurrentCUDAStream())); + + //TORCH_HIPBLASLT_CHECK(hipblasLtMatmulDescDestroy(matmul)); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutDestroy(mat_a)); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutDestroy(mat_b)); + TORCH_HIPBLASLT_CHECK(hipblasLtMatrixLayoutDestroy(mat_c)); + return OK; + } + + private: + hipblasLtMatmulAlgo_t algo_; +}; + +template +auto GetHipBlasLtTypeStringAndOps() { + hipblasOperation_t transa_outer = MapLayoutToHipBlasLt(ALayout); + hipblasOperation_t transb_outer = MapLayoutToHipBlasLt(BLayout); + auto a_datatype = HipDataTypeFor(); + auto b_datatype = HipDataTypeFor(); + auto in_out_datatype = HipDataTypeFor(); + std::vector heuristic_result; +#if ROCM_VERSION == 60400 + // hipblaslt TT fp32 regression on ROCm 6.4, cannot use + if ((a_datatype == HIP_R_32F || b_datatype == HIP_R_32F || in_out_datatype == HIP_R_32F) + && (transa_outer == HIPBLAS_OP_T && transb_outer == HIPBLAS_OP_T)) { + std::vector>>> ignore; + return ignore; + } +#endif + + hipblasComputeType_t computeType = HipBlasComputeTypeFor(); + if constexpr (std::is_same_v) { + if (at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) == at::Float32Precision::TF32) { + computeType = HIPBLAS_COMPUTE_32F_FAST_TF32; + } + } + + hipblasLtHandle_t handle; + TORCH_HIPBLASLT_CHECK(hipblasLtCreate(&handle)); + TORCH_HIPBLASLT_CHECK(hipblaslt_ext::getAllAlgos(handle, + hipblaslt_ext::GemmType::HIPBLASLT_GEMM, + transa_outer, + transb_outer, + a_datatype, + b_datatype, + in_out_datatype, + in_out_datatype, + computeType, + heuristic_result)); + TORCH_HIPBLASLT_CHECK(hipblasLtDestroy(handle)); + + int returned_algo_count = heuristic_result.size(); + std::vector>>> ret; + for (int i = 0; i < returned_algo_count; i++) { + auto algo = heuristic_result[i].algo; + int algo_index = hipblaslt_ext::getIndexFromAlgo(algo); + auto callable = std::make_unique>(algo); + std::string type_string = fmt::sprintf("Gemm_Hipblaslt_%d", algo_index); + ret.emplace_back(type_string, std::move(callable)); + } + + return ret; +} + +template +auto GetHipBlasLtGemmTypeStringAndOps() { + return GetHipBlasLtTypeStringAndOps>(); +} + +template +auto GetHipBlasLtGemmAndBiasTypeStringAndOps() { + return GetHipBlasLtTypeStringAndOps>(); +} + +template +auto GetHipBlasLtGemmStridedBatchedTypeStringAndOps() { + return GetHipBlasLtTypeStringAndOps>(); +} + +template +auto GetHipBlasLtScaledGemmTypeStringAndOps() { + return GetHipBlasLtTypeStringAndOps>(); +} + +#undef TORCH_HIPBLASLT_CHECK + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmRocblas.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmRocblas.h new file mode 100644 index 0000000000000000000000000000000000000000..4cbdd025ec9ed3fbfeaad3fa3f7c5b3e54e27794 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/GemmRocblas.h @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#define ROCBLAS_BETA_FEATURES_API +#include + +#define TORCH_ROCBLAS_CHECK(EXPR) \ + do { \ + rocblas_status __err = EXPR; \ + TORCH_CHECK(__err == rocblas_status_success, \ + "rocblas error: ", \ + rocblas_status_to_string(__err), \ + " when calling `" #EXPR "`"); \ + } while (0) + +namespace at::cuda::tunable { + +template +constexpr rocblas_datatype RocBlasDataTypeFor(); + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_f64_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_f16_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor() { + return rocblas_datatype_bf16_r; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor>() { + return rocblas_datatype_f32_c; +} + +template <> +constexpr rocblas_datatype RocBlasDataTypeFor>() { + return rocblas_datatype_f64_c; +} + +template +constexpr rocblas_datatype RocBlasComputeTypeFor(); + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + return rocblas_datatype_f64_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + // Note that we're returning the _compute_ type for a given datatype. + // As of 12/2022, using compute type FP16 for 16-bit floats was much + // slower than using compute type FP32. So we use FP32 compute even for + // FP16 datatypes. This is how GEMM is implemented even in the function + // rocblasGemmHelper (see fpgeneric.h) + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor() { + // Note that we're returning the _compute_ type for a given datatype. + // As of 12/2022, using compute type FP16 for 16-bit floats was much + // slower than using compute type FP32. So we use FP32 compute even for + // BF16 datatypes. This is how GEMM is implemented even in the function + // rocblasGemmHelper (see fpgeneric.h) + return rocblas_datatype_f32_r; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor>() { + return rocblas_datatype_f32_c; +} + +template <> +constexpr rocblas_datatype RocBlasComputeTypeFor>() { + return rocblas_datatype_f64_c; +} + +template +auto DoCastForHalfOrBfloat16(const T fp) { + return fp; +} + +template <> +inline auto DoCastForHalfOrBfloat16(const Half fp) { + // alpha and beta should be the same as compute_type, in Half case it is float. + float h = fp; + return h; +} + +template <> +inline auto DoCastForHalfOrBfloat16(const BFloat16 fp) { + // alpha and beta should be the same as compute_type, in bfloat16 case it is float. + float h = fp; + return h; +} + +static rocblas_operation _rocblasOpFromChar(char op) { + switch (op) { + case 'n': + case 'N': + return rocblas_operation_none; + case 't': + case 'T': + return rocblas_operation_transpose; + case 'c': + case 'C': + return rocblas_operation_conjugate_transpose; + } + TORCH_CHECK(false, + "_rocblasOpFromChar input should be 't', 'n' or 'c' but got `", op, "`"); +} + +template +class RocblasGemmOp : public Callable> { + public: + RocblasGemmOp(int32_t solution) : solution_{solution} {} + + TuningStatus Call(const GemmParams* params) override { + auto input_output_type = RocBlasDataTypeFor(); + if (at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) == at::Float32Precision::TF32 && input_output_type == rocblas_datatype_f32_r) + return FAIL; // no support for TF32 in rocBLAS + auto compute_type = RocBlasComputeTypeFor(); + auto h_a = DoCastForHalfOrBfloat16(params->alpha); + auto h_b = DoCastForHalfOrBfloat16(params->beta); + auto status = rocblas_gemm_ex( + (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(), + _rocblasOpFromChar(params->transa), + _rocblasOpFromChar(params->transb), + params->m, params->n, params->k, + &h_a, + params->a, input_output_type, params->lda, + params->b, input_output_type, params->ldb, + &h_b, + params->c, input_output_type, params->ldc, + params->c, input_output_type, params->ldc, + compute_type, + rocblas_gemm_algo_solution_index, + solution_, + rocblas_gemm_flags_none); + if (status != rocblas_status_success) { + return FAIL; + } + return OK; + } + + private: + int32_t solution_; +}; + +template +auto GetRocBlasGemmTypeStringAndOps() { + rocblas_handle handle = (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(); + rocblas_int solution_size; + auto input_output_type = RocBlasDataTypeFor(); + auto compute_type = RocBlasComputeTypeFor(); + // Get the number of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + nullptr, + &solution_size)); + const auto solution_capacity = static_cast(solution_size); + std::vector solutions(solution_capacity); + // Get the list of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + solutions.data(), + &solution_size)); + // See rocblas/internal/rocblas-beta.h: the list_size parameter + // (solution_size here) is updated to the number of solution indices filled. + solutions.resize(std::min(static_cast(solution_size), solution_capacity)); + std::vector>>>> ret; + for (size_t i = 0; i < solutions.size(); ++i) { + auto solution = static_cast(solutions[i]); + auto callable = std::make_unique>(solution); + ret.emplace_back(std::make_pair(fmt::sprintf("Gemm_Rocblas_%d", solution), std::move(callable))); + } + return ret; +} + +template +class RocblasGemmStridedBatchedOp : public Callable> { + public: + RocblasGemmStridedBatchedOp(int32_t solution) : solution_{solution} {} + + TuningStatus Call(const GemmStridedBatchedParams* params) override { + auto input_output_type = RocBlasDataTypeFor(); + if (at::globalContext().float32Precision(at::Float32Backend::CUDA, at::Float32Op::MATMUL) == at::Float32Precision::TF32 && input_output_type == rocblas_datatype_f32_r) + return FAIL; // no support for TF32 in rocBLAS + auto compute_type = RocBlasComputeTypeFor(); + auto h_a = DoCastForHalfOrBfloat16(params->alpha); + auto h_b = DoCastForHalfOrBfloat16(params->beta); + auto status = rocblas_gemm_strided_batched_ex( + (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(), + _rocblasOpFromChar(params->transa), + _rocblasOpFromChar(params->transb), + params->m, params->n, params->k, + &h_a, + params->a, input_output_type, params->lda, params->stride_a, + params->b, input_output_type, params->ldb, params->stride_b, + &h_b, + params->c, input_output_type, params->ldc, params->stride_c, + params->c, input_output_type, params->ldc, params->stride_c, + params->batch, + compute_type, + rocblas_gemm_algo_solution_index, + solution_, + rocblas_gemm_flags_none); + if (status != rocblas_status_success) { + return FAIL; + } + return OK; + } + + private: + int32_t solution_; +}; + +template +auto GetRocBlasGemmStridedBatchedTypeStringAndOps() { + rocblas_handle handle = (rocblas_handle)at::cuda::getCurrentCUDABlasHandle(); + rocblas_int solution_size; + auto input_output_type = RocBlasDataTypeFor(); + auto compute_type = RocBlasComputeTypeFor(); + // Get the number of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + nullptr, + &solution_size)); + const auto solution_capacity = static_cast(solution_size); + std::vector solutions(solution_capacity); + // Get the list of available solutions + TORCH_ROCBLAS_CHECK(rocblas_gemm_ex_get_solutions_by_type(handle, + input_output_type, + input_output_type, + compute_type, + rocblas_gemm_flags_none, + solutions.data(), + &solution_size)); + // See rocblas/internal/rocblas-beta.h: the list_size parameter + // (solution_size here) is updated to the number of solution indices filled. + solutions.resize(std::min(static_cast(solution_size), solution_capacity)); + // Sort the solutions in ascending order to make the solution vector deterministic across runs + std::sort(solutions.begin(), solutions.end()); + + std::vector>>>> ret; + for (size_t i = 0; i < solutions.size(); ++i) { + auto solution = static_cast(solutions[i]); + auto callable = std::make_unique>(solution); + ret.emplace_back(std::make_pair(c10::str("Gemm_Rocblas_", solution), std::move(callable))); + } + return ret; +} + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/README.md b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c376503aff8c197465f306d296a69b0430c75c02 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/README.md @@ -0,0 +1,209 @@ +# TunableOp + +This directory implements a TunableOp interface. + +Some operations, such as GEMMs, could be implemented using more than one library or more than one technique. For +example, a GEMM could be implemented for CUDA or ROCm using either the blas or blasLt libraries. Further, ROCm's +rocblas and hipblaslt libraries allow the user to query for all possible algorithms and then choose one. How does one +know which implementation is the fastest and should be chosen? That's what TunableOp provides. + +## Enabling TunableOp and Tuning Separately +The TunableOp feature is enabled separately from enabling the tuning phase itself. Enabling TunableOp means that PyTorch +will replace any standard operators with their Tunable implementations. Any call to a TunableOp first checks whether it +has already been tuned for the given operator inputs. If so, it will immediately call the tuned operation; no further +tuning will take place even when the tuning setting is enabled. Instead if no tuning result is found, and tuning is +enabled, the TunableOp will benchmark every registered implementation of that operator for the given set of inputs and +select the fastest. + +## File Input and Output +The first time any TunableOp is invoked, the internal database of tuned operations will be prepared by attempting to +read the results from the given file. The default filename is 'tunableop_results.csv'. To support tuning when multiple +GPUs are used across multiple processes, the GPU device ordinal is automatically inserted into the filename to avoid +multiple processes overwriting the same file. + +If tuning is enabled and new tunings are discovered during the course of your workload, it will also write out to this +same filename with all tunings, both the ones it read in at startup as well as the new ones found at runtime. This can +be used, for example, to build up a tunings file across many workloads by reusing the same file. The output file is +automatically created when the application terminates. This behavior can be controlled by the C++ and Python APIs but +not the environment variables. + +Assuming you specified a filename, you'll end up with a CSV file with contents like so: + +``` +Validator,PT_VERSION,2.2.0 +Validator,ROCM_VERSION,6.0.0.0-12969-1544e39 +Validator,HIPBLASLT_VERSION,0.6.0-a9c5cc7 +Validator,ROCBLAS_VERSION,4.0.0-72e57364-dirty +GemmTunableOp_float_NT,nt_25088_4096_64,1219,1.262 +GemmTunableOp_float_NT,nt_4096_4096_64,1216,0.033 +``` + +Note the "Validator" lines. If you change a library version, or ROCm version, or PyTorch version, TunableOp will detect +this and reject the tunings file because the prior tunings are likely affected by other software changes. + +The remaining lines are the tuned solutions for each TunableOp encountered during your execution. Each line consists of +4 comma-separated fields: operator name, operator parameters, solution name, and average execution time. The execution +time is an optional field. The CSV file can be edited, but with caution. For example, the solution name (field 3) can be +changed to "Default" and it will fall back to the original PyTorch untuned implementation. Or, in the case of ROCm's +hipBLAS or hipBLASLt libraries, if you know the specific solution index you can override the solution that TunableOp +selected by replacing the value. The operator name and parameters (fields 1 and 2) are internally named and should not +be modified. In the case of GemmTunableOp, field 1 indicates the datatype and whether the inputs are transposed (T) or +not (N) and field 2 indicates the M, N, K input shapes. + +There is an option to enable verbose output but it is only recommended for debugging purposes. This will produce a lot +of diagnostic messages but may be useful to see if TunableOp is being used at all. Otherwise, TunableOp is completely +silent, besides file output, unless there is a warning or error during its use. + +## A Note on Tuning Behavior, Warmup, and Cache Effects +Tuning an operator consists of iterating through the list or registered implementations and profiling each one. The +profile is established by running a single implementation in a loop multiple times and taking the average execution +time. There is also an optional warmup phase prior to tuning that can help with reaching stable power states by the +hardware. During tuning of a workload the various hardware caches will more likely produce hits than when not tuning. +There are options for flushing the instruction cache and rotate the input tensors which might help produce a more +faithful profile of the tuned operator as if the operator were run within a larger workload instead of in a tight, +repetitive loop. + +By default, each possible solution for a given operator will be run for either 100 iterations or as many iterations that +can be run within 30ms, whichever is smaller, and its average execution will be calculated. The fastest solution among +all that were successfully profiled will be chosen. A profile might fail if the given solution doesn't achieve the same +accuracy as the default implementation or if the solution returns an error code. + +## Current Tunable Operators + +### TunableGemm for ROCm +Currently only a TunableGemm for ROCm is implemented. Note that CUDA builds of PyTorch will function correctly when +using TunableOp but the only solution available to CUDA builds is the 'Default' implementation i.e. the original cuBLAS +default, now called through TunableOp. Any call to at::cuda::blas::gemm() or ::bgemm() will be routed through TunableOp +when enabled. Calling gemm() for a given set of input arguments (transa, transb, m, n, k) will attempt to use the +fastest available implementation across both rocblas and hipblaslt. + +## Offline Tuning + +### Motivation +There are a couple of uses cases for offline tuning. + +One use case, is a workload with a high-memory utilization where one might run out of memory with regular tuning. + +Another use case would be a workload that is compute intensive to run and it would be more resource efficient to collect +the GEMMs for the workload once, and then tune repeatedly with different tuning parameters or libraries. + +### Workflow +There are basically two steps: +1) Set the environment variables to collect the untuned GEMM and this will generate `tunableop_untuned0.csv` +``` +PYTORCH_TUNABLEOP_ENABLED=1 +PYTORCH_TUNABLEOP_TUNING=0 +PYTORCH_TUNABLEOP_RECORD_UNTUNED=1 +... +``` +2) Run a Python script that reads the `tunableop_untuned0.csv` and generates the `tunableop_results0.csv`, like: +``` +import torch.cuda.tunable as tunable +import os + +os.putenv('PYTORCH_TUNABLEOP_ENABLED', '1') +os.putenv('PYTORCH_TUNABLEOP_TUNING', '1') +os.putenv('PYTORCH_TUNABLEOP_RECORD_UNTUNED', '0') +tunable.tune_gemm_in_file("tunableop_untuned0.csv") +``` + +It is also possible to take multiple untuned files and distribute the GEMMs for tuning to multiple GPUs +within a single node. In the first step, the GEMMs are first gathered and duplicate GEMMs are eliminated. +Next, the GEMMs are distributed to different GPUs for tuning. After all GEMMs are tuned, the results from +all the GPUs are then gathered into a single file whose base filename has `_full0` appended to it +(e.g. `tunableop_results_full0.csv`). Finally, this new file, containing the gathered results, will be +duplicated N times, once for each GPU as convenience to the user will run the workload with the tuned +configuration on N GPUs. + +``` +if __name__ == "__main__": + num_gpus = 8 # number of GPUs that will be used during the tuning process + tunable.mgpu_tune_gemm_in_file("tunableop_untuned?.csv", num_gpus) +``` + +Note that the usage of the `mgpu_tune_gemm_in_file` API is different from its single GPU counterpart +(`tune_gemm_in_file`). The body of the Python script that calls the API must be wrapped in `main()` as shown +due to the use of concurrent futures module. The argument to `mgpu_tune_gemm_in_file` must contain a wild card +expression (? or *) to generate the list of untuned files containing the GEMMs to be processed. The `num_gpus` +must between 1 and the total number of GPUs available. + +## Tuning Context +The behavior of TunableOp is currently manipulated through environment variables, the C++ interface of +at::cuda::tunable::getTuningContext(), or the `torch.cuda.tunable` python interfaces. The environment variables take +precedence over any setting you manipulate using the C++ or Python APIs. + +### Environment Variable Interface +Environment variables are cached the first time they are read. You cannot use the environment variable interface +programmatically since the settings become fixed. Use the C++ or Python APIs instead. + +| Environment Variable | Description | +| -------------------- | ----------- | +| PYTORCH_TUNABLEOP_ENABLED | Default is 0. Set to 1 to enable. | +| PYTORCH_TUNABLEOP_TUNING | Default is 1. Set to 0 to disable. | +| PYTORCH_TUNABLEOP_RECORD_UNTUNED | Default is 0. Set to 1 to enable. | +| PYTORCH_TUNABLEOP_UNTUNED_FILENAME | Default is 'tunableop_untuned.csv'. | +| PYTORCH_TUNABLEOP_VERBOSE | Default is 0. Set to 1 to enable basic logging. 2 for basic tuning status. 3 for full trace. | +| PYTORCH_TUNABLEOP_VERBOSE_FILENAME | Default is "err" for stderr. Set to "out" for stdout or a filename for capturing verbose logging. | +| PYTORCH_TUNABLEOP_FILENAME | Default is 'tunableop_results.csv'. | +| PYTORCH_TUNABLEOP_NUMERICAL_CHECK | Default is off. Set 'atol_rtol' to enable, for example "1e-5_1e-5". | +| PYTORCH_TUNABLEOP_ROCBLAS_ENABLED | Default is 1. Set to 0 to disable rocblas being considered during tuning. | +| PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED | Default is 1. Set to 0 to disable hipblaslt being considered during tuning. | +| PYTORCH_TUNABLEOP_MAX_TUNING_DURATION_MS | Default is 30. Unit is milliseconds. | +| PYTORCH_TUNABLEOP_MAX_TUNING_ITERATIONS | Default is 100. | +| PYTORCH_TUNABLEOP_CUBLASLT_REQUESTED_ALGO_COUNT | Default is 8. CUDA only. Number of cuBLASLt heuristic candidates to request. Values less than 1 are clamped to 1. | +| PYTORCH_TUNABLEOP_MAX_WARMUP_DURATION_MS | Default is 0, meaning it is not used. Unit is milliseconds. | +| PYTORCH_TUNABLEOP_MAX_WARMUP_ITERATIONS | Default is 0, meaning it is not used. | +| PYTORCH_TUNABLEOP_ICACHE_FLUSH_ENABLED | Default is 1. Set to 0 to disable. | +| PYTORCH_TUNABLEOP_ROTATING_BUFFER_SIZE | Default (or < 0) is to query L2 cache size. Set to 0 to disable. Otherwise, set to the number of MiB to use for the pool of operator parameters. For example, setting this to the size of your device's memory cache will guarantee that every tuning iteration will use a cold cache. | +| PYTORCH_TUNABLEOP_BLAS_LOG | Default is 0. Set to 1 to enable. Write BLAS parameters to tuning CSV file. | + +### Python Interface +All python APIs exist in the `torch.cuda.tunable` module. + +| Python API | Description | +| ---------- | ----------- | +| enable(val: bool = True) -> None | | +| is_enabled() -> bool | | +| tuning_enable(val: bool = True) -> None | Default is True. | +| tuning_is_enabled() -> bool | | +| record_untuned_enable(val: bool = True) -> None | Default is True. | +| record_untuned_is_enabled() -> bool | | +| set_max_tuning_duration(duration: int) -> None | | +| get_max_tuning_duration() -> int | | +| set_max_tuning_iterations(iterations: int) -> None | | +| get_max_tuning_iterations() -> int | | +| set_cublaslt_requested_algo_count(count: int) -> None | CUDA only. Values less than 1 are clamped to 1. | +| get_cublaslt_requested_algo_count() -> int | CUDA only. | +| set_filename(filename: str, insert_device_ordinal: bool = False) -> None | | +| get_filename() -> str | | +| set_numerical_check_tolerances(enable: bool, atol: float, rtol: float) -> None | Enable or disable numerical checking; atol and rtol default to 1e-5. +| get_results() -> Tuple[str, str, str, float] | | +| get_validators() -> Tuple[str, str] | | +| read_file(filename: Optional[str] = None) -> None | If filename not given, it will call get_filename(). | +| tune_gemm_in_file(filename: str) -> None | read an untuned file and tune GEMMs in it. | +| mgpu_tune_gemm_in_file(filename_pattern: str, num_gpus: int) -> None: -> None | read one or more untuned files and tune all unique GEMMs on one or more GPUs. | + +### C++ Interface +Example: +```C++ +#include + +at::cuda::tunable::getTuningContext()->EnableTunableOp(true); +``` + +| C++ API | Description | +| ------- | ----------- | +| void EnableTunableOp(bool value); | | +| bool IsTunableOpEnabled() const; | | +| void EnableTuning(bool value); | | +| bool IsTuningEnabled() const; | | +| void SetMaxTuningDurationMs(int max_duration_ms); | | +| int GetMaxTuningDurationMs() const; | | +| void SetMaxTuningIterations(int max_iter); | | +| int GetMaxTuningIterations() const; | | +| TuningResults GetTuningResults(); | | +| void SetFilename(const std::string& filename, bool insert_device_ordinal=false); | | +| std::string GetFilename() const; | | +| void WriteFileOnExit(bool value); | | +| bool ReadFile(const std::string& filename={}); | | +| bool WriteFile(const std::string& filename={}); | | diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/StreamTimer.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/StreamTimer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b7467ba9aaf693a01a8c308bad65416b3492bef --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/StreamTimer.cpp @@ -0,0 +1,64 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// + +#include +#include +#include + +namespace at::cuda::tunable { + +StreamTimer::StreamTimer() { + AT_CUDA_CHECK(cudaEventCreate(&start_)); + AT_CUDA_CHECK(cudaEventCreate(&end_)); +} + +StreamTimer::~StreamTimer() = default; + +void StreamTimer::Start() { + AT_CUDA_CHECK(cudaEventSynchronize(start_)); + AT_CUDA_CHECK(cudaEventRecord(start_, at::cuda::getCurrentCUDAStream())); +} + +void StreamTimer::End() { + AT_CUDA_CHECK(cudaEventRecord(end_, at::cuda::getCurrentCUDAStream())); + AT_CUDA_CHECK(cudaEventSynchronize(end_)); +} + +float StreamTimer::Duration() { + auto time = std::numeric_limits::quiet_NaN(); + // time is in ms with a resolution of 1 us + AT_CUDA_CHECK(cudaEventElapsedTime(&time, start_, end_)); + return time; +} + +StreamTimerNoSync::StreamTimerNoSync() { + AT_CUDA_CHECK(cudaEventCreate(&start_)); + AT_CUDA_CHECK(cudaEventCreate(&end_)); +} + +StreamTimerNoSync::~StreamTimerNoSync() = default; + +void StreamTimerNoSync::Start() { + AT_CUDA_CHECK(cudaEventRecord(start_, at::cuda::getCurrentCUDAStream())); +} + +void StreamTimerNoSync::End() { + AT_CUDA_CHECK(cudaEventRecord(end_, at::cuda::getCurrentCUDAStream())); +} + +float StreamTimerNoSync::Duration() { + auto time = std::numeric_limits::quiet_NaN(); + AT_CUDA_CHECK(cudaEventSynchronize(end_)); + // time is in ms with a resolution of 1 us + AT_CUDA_CHECK(cudaEventElapsedTime(&time, start_, end_)); + return time; +} + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/StreamTimer.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/StreamTimer.h new file mode 100644 index 0000000000000000000000000000000000000000..7431c68879522f42fbe4ace3c5c3cd7aebd3bd5a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/StreamTimer.h @@ -0,0 +1,50 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// +#pragma once + +#include + +#include + +namespace at::cuda::tunable { + +class StreamTimer : public ITimer { + public: + StreamTimer(); + ~StreamTimer() override; + + void Start() override; + + void End() override; + + float Duration() override; + + private: + cudaEvent_t start_{}; + cudaEvent_t end_{}; +}; + +class StreamTimerNoSync : public ITimer { + public: + StreamTimerNoSync(); + ~StreamTimerNoSync() override; + + void Start() override; + + void End() override; + + float Duration() override; + + private: + cudaEvent_t start_{}; + cudaEvent_t end_{}; +}; + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/Tunable.cpp b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/Tunable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0e05e0dfe5abc9f7f1322fac456c37560bee952 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/Tunable.cpp @@ -0,0 +1,939 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// + +#include +#include +#include +#include +#include +#include + + +#ifndef USE_ROCM +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +// for validators +#ifdef USE_ROCM +#ifdef _WIN32 +#include +#else +#include +#endif +#define ROCBLAS_BETA_FEATURES_API +#include +#include +#include +#endif + +namespace at::cuda::tunable { + +TuningContext* getTuningContext() { + static TuningContext tuning_context; + return &tuning_context; +} + +std::ostream& operator<<(std::ostream& stream, const ResultEntry& entry) { + static const bool blaslog = c10::utils::get_env("PYTORCH_TUNABLEOP_BLAS_LOG") == "1"; + if (!blaslog) { + return stream << entry.key_ << ',' << entry.time_; + } + else { + return stream << entry.key_ << ',' << entry.time_ << ",BLAS_PARAMS: " << entry.blas_sig_; + } +} + +// TuningResultsManager + +KernelMap TuningResultsManager::Lookup(const std::string& op_signature) { + std::scoped_lock l{lock_}; + auto it = results_.find(op_signature); + if (it == results_.cend()) { + return {}; + } + return it->second; // copied +} + +ResultEntry TuningResultsManager::Lookup(const std::string& op_signature, const std::string& params_signature) { + std::scoped_lock l{lock_}; + auto kernel_map_it = results_.find(op_signature); + if (kernel_map_it == results_.cend()) { + TUNABLE_LOG3("missing op_signature, returning null ResultEntry for ", op_signature, ",", params_signature); + return ResultEntry::Null(); + } + + const auto& km = kernel_map_it->second; + auto it = km.find(params_signature); + if (it == km.cend()) { + TUNABLE_LOG3("missing params_signature, returning null ResultEntry for ", op_signature, ",", params_signature); + return ResultEntry::Null(); + } + TUNABLE_LOG3("ResultEntry found for ", op_signature, ",", params_signature); + return it->second; +} + +void TuningResultsManager::AddImpl(const std::string& op_signature, + const std::string& params_signature, + ResultEntry best, + KernelMap& kernel_map) { + auto it = kernel_map.find(params_signature); + if (it != kernel_map.end()) { + if (it->second != best) { + TUNABLE_LOG1(op_signature, "(", params_signature, ") already has a best kernel ", + "id=", it->second, " selected, want to add a different best kernel ", best, + ", the new kernel id will be ignored."); + } + return; + } + + TUNABLE_LOG2(op_signature, "(", params_signature, ") -> ", best); + kernel_map.emplace(params_signature, std::move(best)); +} + +void TuningResultsManager::Add(const std::string& op_signature, const std::string& params_signature, ResultEntry best) { + bool is_new = false; + ResultEntry inserted = ResultEntry::Null(); + + // ---- mutate maps under results lock ---- + { + std::scoped_lock l{lock_}; + auto& km = results_[op_signature]; // creates if missing + is_new = (km.find(params_signature) == km.end()); + AddImpl(op_signature, params_signature, std::move(best), km); + if (is_new) { + inserted = km.at(params_signature); // snapshot for I/O after unlocking + } + } + if (!is_new) return; // only write once per unique (op, params) + + TuningContext* ctx = getTuningContext(); + if (ctx->IsTuningEnabled() && !ctx->IsRecordUntunedEnabled()) { + InitRealtimeAppend(ctx->GetFilename(), ctx->GetTuningResultsValidator().GetAllValidators()); + + if (is_new && realtime_out_ && realtime_out_->good()) { + AppendResultLine(op_signature, params_signature, inserted); + } + } + +} + +void TuningResultsManager::RecordUntuned( std::ofstream& untuned_file, const std::string& op_signature, + const std::string& params_signature, const std::string& blas_signature) { + std::scoped_lock l{lock_}; + if (!untuned_file.good()) { + TORCH_WARN_ONCE("failed to open file for writing; untuned gemm will not be saved"); + return; + } else { + bool isNew = false; + auto it = untuned_results_.find(op_signature); + if (it == untuned_results_.end()) { + it = untuned_results_.insert({op_signature, {}}).first; + isNew = true; + } + + auto it_kernel_map = it->second.find(params_signature); + if (it_kernel_map == it->second.end()) { + it->second.insert(params_signature); + isNew = true; + } + + if (isNew) { + static const bool blaslog = c10::utils::get_env("PYTORCH_TUNABLEOP_BLAS_LOG") == "1"; + if (!blaslog) { + untuned_file << op_signature << ',' << params_signature << std::endl; + } + else { + untuned_file << op_signature << ',' << params_signature << ",BLAS_PARAMS: " << blas_signature << std::endl; + } + TUNABLE_LOG3("Untuned,", op_signature, ",", params_signature); + } + } +} + +void TuningResultsManager::ClearUntuned() { + std::scoped_lock l{lock_}; + untuned_results_.clear(); +} + +void TuningResultsManager::InitRealtimeAppend(const std::string& filename, const std::unordered_map& validators) { + std::scoped_lock fl{realtime_file_mutex_}; + + if (realtime_out_ && realtime_out_->good() && realtime_filename_ == filename) { + return; + } + + if (realtime_out_ && realtime_filename_ != filename) { + realtime_out_->flush(); + realtime_out_->close(); + realtime_out_.reset(); + validators_written_ = false; + } + + bool file_exists = false; + bool file_empty = true; + + { + std::ifstream check_file(filename); + if (check_file.good()) { + file_exists = true; + file_empty = (check_file.peek() == std::ifstream::traits_type::eof()); + } + } + + realtime_out_ = std::make_unique(filename, std::ios::out | std::ios::app); + + if (!realtime_out_->good()) { + TORCH_WARN("TunableOp realtime append: failed to open '", filename,"'"); + realtime_out_.reset(); + return; + } + + if(!file_exists || file_empty) { + for(const auto& [key, val] : validators) { + (*realtime_out_) << "Validator," << key << ',' << val << std::endl; + realtime_out_->flush(); + } + validators_written_ = true; + + TUNABLE_LOG2("Wrote validators to realtime output file"); + } + + realtime_filename_ = filename; +} + +void TuningResultsManager::AppendResultLine(const std::string& op_sig, const std::string& param_sig, const ResultEntry& result) { + std::scoped_lock fl{realtime_file_mutex_}; + + if(!realtime_out_ || !realtime_out_->good()) { + return; + } + + (*realtime_out_) << op_sig << ',' << param_sig << ',' << result << std::endl; + realtime_out_->flush(); //ensure immediate write to disk + + TUNABLE_LOG3("Realtime append: ", op_sig, "(", param_sig, ") -> ", result); +} + +void TuningResultsManager::CloseRealtimeAppend() { + std::scoped_lock fl{realtime_file_mutex_}; + + + if(realtime_out_) { + realtime_out_->flush(); + realtime_out_->close(); + realtime_out_.reset(); + TUNABLE_LOG2("Closed realtime output file"); + } +} + +void TuningResultsManager::Delete(const std::string& op_signature, const std::string& params_signature) { + std::scoped_lock l{lock_}; + + auto it = results_.find(op_signature); + if (it == results_.end()) { + return; + } + + auto it2 = it->second.find(params_signature); + if (it2 == it->second.end()) { + return; + } + + TUNABLE_LOG2(op_signature, "(", params_signature, ")"); + it->second.erase(it2); +} + +void TuningResultsManager::DisjointMergeImpl( + const std::string& op_signature, + const KernelMap& kernel_map, + /*out*/ std::unordered_map& results) { + auto it = results.find(op_signature); + if (it == results.end()) { + for (const auto& [param_sig, kernel_id] : kernel_map) { + TUNABLE_LOG2(op_signature, "(", param_sig, ") -> ", kernel_id); + } + results[op_signature] = kernel_map; + return; + } + + for (const auto& [params_signature, best] : kernel_map) { + AddImpl(op_signature, params_signature, best, it->second); + } +} + +void TuningResultsManager::Load(const std::unordered_map& results_to_load) { + TUNABLE_LOG1("Loading results"); + std::scoped_lock l{lock_}; + for (const auto& [op_signature, kernel_map] : results_to_load) { + DisjointMergeImpl(op_signature, kernel_map, results_); + } +} + +ResultsMap TuningResultsManager::Dump() { + std::scoped_lock l{lock_}; + return results_; +} + +void TuningResultsManager::DisjointMerge(const std::string& op_signature, const KernelMap& kernel_map) { + std::scoped_lock l{lock_}; + DisjointMergeImpl(op_signature, kernel_map, results_); +} + +size_t TuningResultsManager::GetSize() { + size_t size = 0; + std::scoped_lock l{lock_}; + for (const auto& [op_signature, kernel_map] : results_) { + size += kernel_map.size(); + } + return size; +} + +// TuningResultsValidator + +TuningResultsValidator::TuningResultsValidator() { + RegisterValidator( + "PT_VERSION", + []() { return GetPyTorchVersion(); }, + [this](auto&& k) { return ValidatePyTorchVersion(std::forward(k)); }); +#ifndef USE_ROCM + auto register_exact_validator = [this](const char* name, auto getter) { + RegisterValidator(name, getter, [name, getter](auto&& k) { + std::string value = getter(); + TUNABLE_LOG1(name, " validation: expect ", k, " to match ", value); + return value == k ? OK : FAIL; + }); + }; + + register_exact_validator( + "CUBLASLT_VERSION", []() { return c10::str(cublasLtGetVersion()); }); + register_exact_validator("CUDA_DEVICE", []() { + const auto* prop = at::cuda::getCurrentDeviceProperties(); + return c10::str(prop->major, ".", prop->minor, ":", prop->name); + }); +#else + // hip + { + // HIP version is more accurate than ROCm version. User's environment could be a stock + // ROCm install but with a mix of newer components, making ROCm version meaningless. + std::string hip_version = c10::str(TORCH_HIP_VERSION); + RegisterValidator( + "HIP_VERSION", + [hip_version]() { return hip_version; }, + [hip_version](auto&& k) { + TUNABLE_LOG1("HIP_VERSION validation: expect ", k, " to match ", hip_version); + return hip_version == k ? OK : FAIL; + }); + } + // gfx arch + { + std::string gcn_arch_name = at::cuda::getCurrentDeviceProperties()->gcnArchName; + RegisterValidator( + "GCN_ARCH_NAME", + [gcn_arch_name]() { return gcn_arch_name; }, + [gcn_arch_name](auto&& k) { + TUNABLE_LOG1("GCN_ARCH_NAME validation: expect ", k, " to match ", gcn_arch_name); + return gcn_arch_name == k ? OK : FAIL; + }); + } + // rocblas + { + size_t rocblas_version_size; + rocblas_get_version_string_size(&rocblas_version_size); + std::string rocblas_version(rocblas_version_size - 1, '\0'); + rocblas_get_version_string(rocblas_version.data(), rocblas_version_size); + RegisterValidator( + "ROCBLAS_VERSION", + [rocblas_version]() { return rocblas_version; }, + [rocblas_version](auto&& k) { + TUNABLE_LOG1("ROCBLAS_VERSION validation: expect ", k, " to match ", rocblas_version); + return rocblas_version == k ? OK : FAIL; + }); + } + // hipblaslt + { + int version; + std::string revision(128, '\0'); + auto handle = at::cuda::getCurrentCUDABlasLtHandle(); + hipblasLtGetVersion(handle, &version); + hipblasLtGetGitRevision(handle, revision.data()); + std::string hipblaslt_version = + c10::str(version, "-", revision.c_str()); + RegisterValidator( + "HIPBLASLT_VERSION", + [hipblaslt_version]() { return hipblaslt_version; }, + [hipblaslt_version](auto&& k) { + TUNABLE_LOG1("HIPBLASLT_VERSION validation: expect ", k, " to match ", hipblaslt_version); + return hipblaslt_version == k ? OK : FAIL; + }); + } +#endif +} + +std::unordered_map TuningResultsValidator::GetAllValidators() const { + std::unordered_map ret; + for (const auto& [key, get_validate_func_pair] : validators_) { + const GetFunc& getter = get_validate_func_pair.first; + ret[key] = getter(); + } + return ret; +} + +static bool CheckMandatoryKeys( + const TuningResultsValidator::GetValidateFuncs& gv_funcs, + const std::unordered_map& to_check) { + bool passed = true; + for (const auto& k : TuningResultsValidator::mandatory_keys) { + if (gv_funcs.find(k) == gv_funcs.end()) { + passed = false; + TUNABLE_LOG1("key=\"", k, "\" is not registered for Get and Validate. "); + } + + if (to_check.find(k) == to_check.end()) { + passed = false; + TUNABLE_LOG1("key=\"", k, "\" is not provided for validation. "); + } + } + return passed; +} + +static bool CheckKeysMatching( + const TuningResultsValidator::GetValidateFuncs& gv_funcs, + const std::unordered_map& to_check) { + auto get_keys = [](const auto& it) -> std::string { return it.first; }; + std::vector required_keys; + std::vector provided_keys; + std::transform(gv_funcs.cbegin(), gv_funcs.cend(), std::back_inserter(required_keys), get_keys); + std::transform(to_check.cbegin(), to_check.cend(), std::back_inserter(provided_keys), get_keys); + std::sort(required_keys.begin(), required_keys.end()); + std::sort(provided_keys.begin(), provided_keys.end()); + + std::unordered_set intersection; + std::set_intersection(required_keys.cbegin(), required_keys.cend(), + provided_keys.cbegin(), provided_keys.cend(), + std::inserter(intersection, intersection.end())); + bool matched = true; + if (intersection.size() != required_keys.size()) { + matched = false; + for (const auto& k : required_keys) { + if (intersection.find(k) == intersection.end()) { + TORCH_WARN("Unmatched validator: \"", k, "\" is required, but the tuning results does not provide it. "); + } + } + } + if (intersection.size() != provided_keys.size()) { + matched = false; + for (const auto& k : provided_keys) { + if (intersection.find(k) == intersection.end()) { + TORCH_WARN("Unmatched validator: \"", k, "\" is provided, but pytorch is unable to consume it. "); + } + } + } + return matched; +} + +TuningStatus TuningResultsValidator::ValidateAll( + const std::unordered_map& to_validate) const { + if (!CheckMandatoryKeys(validators_, to_validate)) { + return FAIL; + } + if (!CheckKeysMatching(validators_, to_validate)) { + return FAIL; + } + + for (const auto& [key, value] : to_validate) { + const auto& it = validators_.find(key); + if (it == validators_.cend()) { + TORCH_WARN("Failed to lookup validator using key ", key); + for (const auto& [key2, val2] : validators_) { + TORCH_WARN("available key ", key2); + } + return FAIL; + } + const ValidateFunc& validator = it->second.second; + if (validator(value) != OK) { + TORCH_WARN("Failed validator: ", key); + return FAIL; + } + } + + return OK; +} + +void TuningResultsValidator::RegisterValidator(const std::string& key, const GetFunc& gf, const ValidateFunc& vf) { + if (validators_.find(key) != validators_.end()) { + TORCH_WARN("Attempting to re-register validator with key ", key); + } + else { + validators_[key] = std::make_pair(gf, vf); + } +} + +std::string TuningResultsValidator::GetPyTorchVersion() { + return TORCH_VERSION; +} + +TuningStatus TuningResultsValidator::ValidatePyTorchVersion(const std::string& value) const { + TUNABLE_LOG1("PT_VERSION validation: expect ", value, " to match ", GetPyTorchVersion()); + if (value == GetPyTorchVersion()) { + return OK; + } + return FAIL; +} + +// TuningContext + +TuningContext::TuningContext() : + enable_{false}, + tuning_enable_{true}, + record_untuned_enable_{false}, + manager_initialized_{false}, + numerics_check_enable_{false}, + max_tuning_duration_ms_{30}, + max_tuning_iterations_{100}, + cublaslt_requested_algo_count_{8}, + max_warmup_duration_ms_{0}, + max_warmup_iterations_{0}, + icache_flush_{true}, + rotating_buffer_size_{-1}, + results_count_from_input_file_{0}, + is_shutting_down_{false} +{ +} + +TuningContext::~TuningContext() { + is_shutting_down_ = true; + if (!manager_initialized_) { + // TuningResultsManager was never initialized, no tuning requested or performed. + // This can happen in a DDP job where a python process spawns other workers + // but doesn't do any computation itself. + return; + } + TUNABLE_LOG1("Closing File"); + GetTuningResultsManager().CloseRealtimeAppend(); // Since, we do instant logging by default now. + + if (untuned_file_.good()) { + untuned_file_.close(); + } +} + +void TuningContext::EnableTunableOp(bool value) { + enable_ = value; + if (value) { + TUNABLE_LOG1("Enable TunableOp"); + } + else { + TUNABLE_LOG1("Disable TunableOp"); + } +} + +bool TuningContext::IsTunableOpEnabled() const { + static const bool eval = c10::utils::get_env("PYTORCH_TUNABLEOP_ENABLED") == "1"; + if (eval) { + return true; + } + return enable_; +} + +void TuningContext::EnableTuning(bool value) { + tuning_enable_ = value; + if (value) { + TUNABLE_LOG1("Enable Tuning for TunableOp"); + } + else { + TUNABLE_LOG1("Disable Tuning for TunableOp"); + } +} + +void TuningContext::EnableRecordUntuned(bool value) { + record_untuned_enable_ = value; + if (value) { + TUNABLE_LOG1("Enable Record Untuned for TunableOp"); + } else { + TUNABLE_LOG1("Disable Record Untuned for TunableOp"); + TUNABLE_LOG1("Closing Untuned GEMM Results File"); + untuned_file_.close(); + manager_.ClearUntuned(); + } +} + +bool TuningContext::IsTuningEnabled() const { + static const bool eval = c10::utils::get_env("PYTORCH_TUNABLEOP_TUNING") == "0"; + if (eval) { + return false; + } + return tuning_enable_; +} + +bool TuningContext::IsRecordUntunedEnabled() const { + static const bool eval = c10::utils::get_env("PYTORCH_TUNABLEOP_RECORD_UNTUNED") == "1"; + if (eval) { + return true; + } + return record_untuned_enable_; +} + +std::ofstream& TuningContext::GetUntunedFile(){ + if (!untuned_file_.is_open()) { + const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_UNTUNED_FILENAME"); + std::string filename = (!env.has_value()) ? "tunableop_untuned.csv" : env.value(); + + std::string device = c10::str(int(c10::cuda::current_device())); + std::size_t found = filename.rfind('.'); + if (found != std::string::npos) { + filename.insert(found, device); + } else { + // all else fails, just append + filename.append(device); + } + + untuned_file_ = std::ofstream(filename, std::ios::out | std::ios::app); + } + return untuned_file_; +} + + +void TuningContext::EnableNumericsCheck(bool value) { + numerics_check_enable_ = value; +} + +NumericalCheckConfig TuningContext::GetNumericalCheckConfig() const { + const auto env_opt = c10::utils::get_env("PYTORCH_TUNABLEOP_NUMERICAL_CHECK"); + + if (!env_opt.has_value()) { + return numerics_cfg_; + } + + const std::string& env = env_opt.value(); + + if (env == "0") { + return NumericalCheckConfig(false, 1e-5, 1e-5); + } + + const size_t underscore = env.find('_'); + + TORCH_CHECK( + underscore != std::string::npos, + "Invalid PYTORCH_TUNABLEOP_NUMERICAL_CHECK format. " + "Expected 'atol_rtol', got: ", + env); + + double atol = 0.0; + double rtol = 0.0; + + try { + atol = std::stod(env.substr(0, underscore)); + rtol = std::stod(env.substr(underscore + 1)); + } catch (const std::exception& e) { + TORCH_CHECK(false, "Failed to parse PYTORCH_TUNABLEOP_NUMERICAL_CHECK: ", e.what()); + } + + TORCH_CHECK( atol > 0.0 && rtol > 0.0, "Tolerance values must be positive. atol=", atol, ", rtol=", rtol); + return NumericalCheckConfig(true, atol, rtol); +} + +void TuningContext::SetNumericalCheckConfig(bool enabled, double atol, double rtol) { + TORCH_CHECK(atol > 0.0 && rtol > 0.0, "Numerical check tolerances must be positive"); + numerics_cfg_ = {enabled, atol, rtol}; +} + +bool TuningContext::IsNumericsCheckEnabled() const { + const auto cfg = GetNumericalCheckConfig(); + return cfg.enabled || numerics_check_enable_; +} + +void TuningContext::SetMaxTuningDurationMs(int max_duration_ms) { + max_tuning_duration_ms_ = max_duration_ms < 0 ? 0 : max_duration_ms; +} + +int TuningContext::GetMaxTuningDurationMs() const { + static const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_MAX_TUNING_DURATION_MS"); + if (env.has_value()) { + int val = stoi(env.value()); + return val < 0 ? 0 : val; + } + return max_tuning_duration_ms_; +} + +void TuningContext::SetMaxTuningIterations(int max_iter) { + max_tuning_iterations_ = max_iter < 0 ? 0 : max_iter; +} + +int TuningContext::GetMaxTuningIterations() const { + static const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_MAX_TUNING_ITERATIONS"); + if (env.has_value()) { + int val = stoi(env.value()); + return val < 0 ? 0 : val; + } + return max_tuning_iterations_; +} + +void TuningContext::SetCublasLtRequestedAlgoCount(int count) { + cublaslt_requested_algo_count_ = std::max(1, count); +} + +int TuningContext::GetCublasLtRequestedAlgoCount() const { + static const auto env = c10::utils::get_env( + "PYTORCH_TUNABLEOP_CUBLASLT_REQUESTED_ALGO_COUNT"); + if (env.has_value()) { + try { + return std::max(1, std::stoi(env.value())); + } catch (const std::exception&) { + TORCH_WARN_ONCE( + "PYTORCH_TUNABLEOP_CUBLASLT_REQUESTED_ALGO_COUNT is not a valid " + "integer (got `", env.value(), "`). Falling back to the value set " + "via torch.cuda.tunable.set_cublaslt_requested_algo_count."); + } + } + return cublaslt_requested_algo_count_; +} + +void TuningContext::SetMaxWarmupDurationMs(int max_duration_ms) { + max_warmup_duration_ms_ = max_duration_ms < 0 ? 0 : max_duration_ms; +} + +int TuningContext::GetMaxWarmupDurationMs() const { + static const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_MAX_WARMUP_DURATION_MS"); + if (env.has_value()) { + int val = stoi(env.value()); + return val < 0 ? 0 : val; + } + return max_warmup_duration_ms_; +} + +void TuningContext::SetMaxWarmupIterations(int max_iter) { + max_warmup_iterations_ = max_iter < 0 ? 0 : max_iter; +} + +int TuningContext::GetMaxWarmupIterations() const { + static const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_MAX_WARMUP_ITERATIONS"); + if (env.has_value()) { + int val = stoi(env.value()); + return val < 0 ? 0 : val; + } + return max_warmup_iterations_; +} + +void TuningContext::EnableICacheFlush(bool value) { + icache_flush_ = value; +} + +bool TuningContext::IsICacheFlushEnabled() const { + static const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_ICACHE_FLUSH_ENABLED"); + if (env == "0") { + return false; + } + return icache_flush_; +} + +void TuningContext::SetRotatingBufferSize(int size) { + // Any negative rotating buffer size means l2_cache_size + // see GetRotatingBufferSize + // + // size is set in MB like the environment variable + constexpr int MB = 1024 * 1024; + rotating_buffer_size_ = size * MB; +} + +int TuningContext::GetRotatingBufferSize() const { + // If the environment variable is negative or not set, return the L2 cache size. + // The default rotating_buffer_size is -1, but this member function will + // return l2_cache size. + // This member function will always return a zero or a positive integer. + static const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_ROTATING_BUFFER_SIZE"); + int l2_cache_size = at::cuda::getCurrentDeviceProperties()->l2CacheSize; + if (env.has_value()) { // env variable is set + constexpr int MB = 1024 * 1024; + int val = stoi(env.value()); + return val < 0 ? l2_cache_size : val * MB; // env var is specified as MB, returned as bytes + } + else { // env variable is not set + if (rotating_buffer_size_ < 0) { + return l2_cache_size; + } + else { + return rotating_buffer_size_; + } + } +} + +TuningResultsManager& TuningContext::GetTuningResultsManager() { + c10::call_once(manager_init_once_, [this]() { + manager_initialized_ = true; + if (GetFilename().empty()) { + // if SetFilename() was not already called, call it now with the default or env var + const auto env = c10::utils::get_env("PYTORCH_TUNABLEOP_FILENAME"); + std::string filename = (!env.has_value()) ? "tunableop_results.csv" : env.value(); + SetFilename(filename, true); + } + auto filename = GetFilename(); + if (!filename.empty() && !IsRecordUntunedEnabled()) { + ReadFile(filename); + } + }); + return manager_; +} + +TuningResultsValidator& TuningContext::GetTuningResultsValidator() { + return validator_; +} + +TuningResults TuningContext::GetTuningResults() { + TuningResults tr; + tr.validators = GetTuningResultsValidator().GetAllValidators(); + tr.results = GetTuningResultsManager().Dump(); + return tr; +} + +TuningStatus TuningContext::LoadTuningResults(const TuningResults& tr) { + TORCH_CHECK(GetTuningResultsValidator().ValidateAll(tr.validators)); + GetTuningResultsManager().Load(tr.results); + return OK; +} + +void TuningContext::SetFilename(const std::string& filename, bool insert_device_ordinal) { + filename_ = filename; + + if (filename_.empty()) { + return; + } + + if (insert_device_ordinal) { + // differentiate filename based on device ordinal to avoid + // use case of one process per device writing to same file + std::string device = c10::str(int(c10::cuda::current_device())); + + // does filename contain %d to insert device ordinal in specific location? + const std::string TOKEN("%d"); + std::size_t found = filename_.find(TOKEN); + if (found != std::string::npos) { + filename_.replace(found, TOKEN.length(), device); + } + else { + // no %d present, so append device ordinal before final '.' + found = filename_.rfind('.'); + if (found != std::string::npos) { + filename_.insert(found, device); + } + else { + // all else fails, just append + filename_.append(device); + } + } + } +} + +std::string TuningContext::GetFilename() const { + return filename_; +} + +bool TuningContext::ReadFile(const std::string& filename_) { + std::string filename = filename_.empty() ? GetFilename() : filename_; + TUNABLE_LOG1("reading tuning results from ", filename); + ResultsMap results; + std::unordered_map validators; + std::string line; + std::ifstream file(filename); + if (!file) { + TUNABLE_LOG1("could not open ", filename, " for reading tuning results"); + return false; + } + while (std::getline(file, line)) { + if (line.empty()) { + continue; + } + std::string part; + std::vector parts; + std::stringstream line_as_stream(line); + while (std::getline(line_as_stream, part, ',')) { + parts.push_back(part); + } + if (parts[0] == "Validator" && parts.size() >= 3) { + validators[parts[1]] = parts[2]; + TUNABLE_LOG1("Validator ", parts[1], "=", parts[2]); + } + else if (parts.size() >= 4) { + results[parts[0]].emplace(parts[1], ResultEntry(parts[2], atof(parts[3].c_str()))); + } + else if (parts.size() >= 3) { + // the timestamp from the file is optional + results[parts[0]].emplace(parts[1], ResultEntry(parts[2], 0)); + } + else { + TUNABLE_LOG1("could not parse line: ", line); + } + } + if (GetTuningResultsValidator().ValidateAll(validators) != FAIL) { + manager_.Load(results); + results_count_from_input_file_ = manager_.GetSize(); + } + else { + TUNABLE_LOG1("results validator check failed"); + return false; + } + return true; +} + +namespace { + +struct MaybeDelete { + bool owns_pointer; + void operator()(std::ostream* os) const { if (owns_pointer) delete os; } +}; + +using OstreamPtr = std::unique_ptr; + +inline OstreamPtr get_stream(const std::string& filename) { + if (filename == "out") { + return OstreamPtr { &std::cout, MaybeDelete {false} }; + } + else if (filename == "err") { + return OstreamPtr { &std::cerr, MaybeDelete {false} }; + } + else { + return OstreamPtr { new std::ofstream {filename.c_str()}, MaybeDelete {true} }; + } +} + +} // anonymous namespace + +std::string TuningContext::GetLogFilename() const { + static const auto env_file = c10::utils::get_env("PYTORCH_TUNABLEOP_VERBOSE_FILENAME"); + static std::string val_file = env_file.has_value() ? env_file.value() : "err"; + return val_file; +} + +int TuningContext::GetLogLevel() const { + static const auto env_verbose = c10::utils::get_env("PYTORCH_TUNABLEOP_VERBOSE"); + static int val_verbose = env_verbose.has_value() ? stoi(env_verbose.value()) : 0; + return val_verbose; +} + +bool TuningContext::GetLogOkay() const { + return !is_shutting_down_; +} + +std::ostream& TuningContext::GetLog() const { + static auto streamptr = get_stream(GetLogFilename()); + return *streamptr; +} + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/Tunable.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/Tunable.h new file mode 100644 index 0000000000000000000000000000000000000000..eee11c29a7b351094642997850dc2ff2945c4eff --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/Tunable.h @@ -0,0 +1,270 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define TUNABLE_LOGV(LEVEL, ...) getTuningContext()->Log(LEVEL, __VA_ARGS__) +#define TUNABLE_LOG1(...) TUNABLE_LOGV(1, __VA_ARGS__) +#define TUNABLE_LOG2(...) TUNABLE_LOGV(2, __VA_ARGS__) +#define TUNABLE_LOG3(...) TUNABLE_LOGV(3, __VA_ARGS__) + +namespace at::cuda::tunable { + +enum TORCH_CUDA_CPP_API TuningStatus { + OK = 0, + FAIL = 1, + UNSUPPORTED = 2, +}; + +// Mapping from params signature to kernel id +class TORCH_CUDA_CPP_API ResultEntry { + public: + explicit ResultEntry(std::string key, double time) : key_(std::move(key)), time_(time) {} + explicit ResultEntry(std::string key, double time, std::string blas_sig ) : key_(std::move(key)), time_(time), blas_sig_(std::move(blas_sig)) {} + bool operator==(const ResultEntry& other) const { return key_ == other.key_; } + bool operator!=(const ResultEntry& other) const { return key_ != other.key_; } + operator std::string () { return key_; } + std::string GetKey() const { return key_; } + double GetTime() const { return time_; } + friend std::ostream& operator<<(std::ostream& stream, const ResultEntry& entry); + static ResultEntry Null() { return ResultEntry("Null", 0.0); } + static ResultEntry Default() { return ResultEntry("Default", 0.0); } + + private: + std::string key_; + double time_; + std::string blas_sig_; +}; + +typedef std::unordered_map KernelMap; +typedef std::unordered_map ResultsMap; +typedef std::unordered_map> UntunedMap; + +struct TORCH_CUDA_CPP_API TuningResults { + // Validates if these results are compatible with the libraries + std::unordered_map validators; + + // Mapping from Callable signature to Callable's tuning result + ResultsMap results; +}; + +class TORCH_CUDA_CPP_API TuningResultsManager { + public: + TuningResultsManager() = default; + ~TuningResultsManager() = default; + + KernelMap Lookup(const std::string& op_signature); + + ResultEntry Lookup(const std::string& op_signature, const std::string& params_signature); + + void AddImpl(const std::string& op_signature, + const std::string& params_signature, + ResultEntry best, + KernelMap& kernel_map); + + void Add(const std::string& op_signature, + const std::string& params_signature, + ResultEntry best); + + void Delete(const std::string& op_signature, const std::string& params_signature); + + void DisjointMergeImpl( + const std::string& op_signature, + const KernelMap& kernel_map, + /*out*/ ResultsMap& results); + + void Load(const ResultsMap& results_to_load); + + ResultsMap Dump(); + + void DisjointMerge(const std::string& op_signature, const KernelMap& kernel_map); + + size_t GetSize(); + + void RecordUntuned( std::ofstream& untuned_file, const std::string& op_signature, + const std::string& params_signature, const std::string& blas_signature); + void ClearUntuned(); + + void InitRealtimeAppend( + const std::string& filename, + const std::unordered_map& validators); + + void AppendResultLine(const std::string& op_sig, + const std::string& param_sig, + const ResultEntry& result); + + void CloseRealtimeAppend(); // For clean shutdown + private: + std::mutex lock_; + std::mutex realtime_file_mutex_; + std::unique_ptr realtime_out_; + std::string realtime_filename_; + ResultsMap results_; + UntunedMap untuned_results_; + bool validators_written_ = false; + +}; + +class TORCH_CUDA_CPP_API TuningResultsValidator { + public: + using GetFunc = std::function; + using ValidateFunc = std::function; + using GetValidateFuncs = std::unordered_map>; + + TuningResultsValidator(); + ~TuningResultsValidator() = default; + + std::unordered_map GetAllValidators() const; + TuningStatus ValidateAll(const std::unordered_map& to_validate) const; + void RegisterValidator(const std::string& key, const GetFunc& gf, const ValidateFunc& vf); + + protected: + static std::string GetPyTorchVersion() ; + TuningStatus ValidatePyTorchVersion(const std::string& value) const; + + public: + static constexpr const std::array mandatory_keys{"PT_VERSION"}; + + private: + GetValidateFuncs validators_; +}; + +struct NumericalCheckConfig { + bool enabled{false}; + double atol{1e-5}; + double rtol{1e-5}; + + NumericalCheckConfig() = default; + NumericalCheckConfig(bool e, double a, double r) : enabled(e), atol(a), rtol(r) {} +}; + + +class TORCH_CUDA_CPP_API TuningContext { + public: + TuningContext(); + ~TuningContext(); + TuningContext(TuningContext &) = delete; + TuningContext(TuningContext &&) = delete; + TuningContext &operator=(TuningContext &) = delete; + TuningContext &operator=(TuningContext &&) = delete; + + void EnableTunableOp(bool value); + bool IsTunableOpEnabled() const; + + void EnableTuning(bool value); + bool IsTuningEnabled() const; + + void EnableRecordUntuned(bool value); + bool IsRecordUntunedEnabled() const; + std::ofstream& GetUntunedFile(); + + void EnableNumericsCheck(bool value); + bool IsNumericsCheckEnabled() const; + void SetNumericalCheckConfig(bool enabled, double atol, double rtol); + NumericalCheckConfig GetNumericalCheckConfig() const; + + void SetMaxTuningDurationMs(int max_duration_ms); + int GetMaxTuningDurationMs() const; + + void SetMaxTuningIterations(int max_iter); + int GetMaxTuningIterations() const; + + void SetCublasLtRequestedAlgoCount(int count); + int GetCublasLtRequestedAlgoCount() const; + + void SetMaxWarmupDurationMs(int max_duration_ms); + int GetMaxWarmupDurationMs() const; + + void SetMaxWarmupIterations(int max_iter); + int GetMaxWarmupIterations() const; + + void EnableICacheFlush(bool value); + bool IsICacheFlushEnabled() const; + + void SetRotatingBufferSize(int size); + int GetRotatingBufferSize() const; + + TuningResultsManager& GetTuningResultsManager(); + + TuningResultsValidator& GetTuningResultsValidator(); + + TuningResults GetTuningResults(); + + TuningStatus LoadTuningResults(const TuningResults& tr); + + void SetFilename(const std::string& filename, bool insert_device_ordinal=false); + std::string GetFilename() const; + + bool ReadFile(const std::string& filename={}); + + template + void Log(int level, Types... args) { + if (GetLogOkay() && GetLogLevel() >= level) { + GetLog() << c10::str(args...) << std::endl; + } + } + + private: + std::string GetLogFilename() const; + int GetLogLevel() const; + bool GetLogOkay() const; + std::ostream& GetLog() const; + + bool enable_; + bool tuning_enable_; + bool record_untuned_enable_; + bool manager_initialized_; + bool numerics_check_enable_; + int max_tuning_duration_ms_; + int max_tuning_iterations_; + int cublaslt_requested_algo_count_; + int max_warmup_duration_ms_; + int max_warmup_iterations_; + bool icache_flush_; + int rotating_buffer_size_; + mutable TuningResultsManager manager_; + mutable c10::once_flag manager_init_once_; + TuningResultsValidator validator_; + std::string filename_; + std::ofstream untuned_file_; + size_t results_count_from_input_file_; + bool is_shutting_down_; + + NumericalCheckConfig numerics_cfg_; +}; + +TORCH_CUDA_CPP_API TuningContext* getTuningContext(); + +class ITimer { + public: + ITimer() = default; + virtual ~ITimer() = default; + + virtual void Start() = 0; + virtual void End() = 0; + + /// Computes the elapsed time in milliseconds between Start() and End() + virtual float Duration() = 0; +}; + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/TunableGemm.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/TunableGemm.h new file mode 100644 index 0000000000000000000000000000000000000000..3494fed935e79a29894c9102966ed3829b1f2f46 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/TunableGemm.h @@ -0,0 +1,352 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// +#pragma once + +#include +#ifdef USE_ROCM +#include +#include +#else +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::cuda::tunable { + +template +class DefaultGemmOp : public Callable> { + public: + TuningStatus Call(const GemmParams* params) override { + at::cuda::blas::gemm_internal( + params->transa, params->transb, + params->m, params->n, params->k, + params->alpha, + params->a, params->lda, + params->b, params->ldb, + params->beta, + params->c, params->ldc); + return OK; + } +}; + +static bool _transposeBoolFromChar(char op) { + return op == 't' || op == 'T'; +} + +template +class DefaultGemmAndBiasOp : public Callable> { + public: + TuningStatus Call(const GemmAndBiasParams* params) override { + at::cuda::blas::gemm_and_bias( + _transposeBoolFromChar(params->transa), + _transposeBoolFromChar(params->transb), + params->m, params->n, params->k, + params->alpha, + params->a, params->lda, + params->b, params->ldb, + params->bias, + params->c, params->ldc, + params->activation); + return OK; + } +}; + +template +class DefaultGemmStridedBatchedOp : public Callable> { + public: + TuningStatus Call(const GemmStridedBatchedParams* params) override { + at::cuda::blas::bgemm_internal( + params->transa, params->transb, + params->m, params->n, params->k, + params->alpha, + params->a, params->lda, params->stride_a, + params->b, params->ldb, params->stride_b, + params->beta, + params->c, params->ldc, params->stride_c, + params->batch); + return OK; + } +}; + +template +class DefaultScaledGemmOp : public Callable> { + public: + TuningStatus Call(const ScaledGemmParams* params) override { + at::cuda::blas::scaled_gemm( + params->transa, + params->transb, + params->m, + params->n, + params->k, + params->a, + params->a_scale_ptr, + params->lda, + params->a_dtype, + params->a_scale_dtype, + params->a_scaling_type, + params->b, + params->b_scale_ptr, + params->ldb, + params->b_dtype, + params->b_scale_dtype, + params->b_scaling_type, + params->bias_ptr, + params->bias_dtype, + params->c, + params->c_scale_ptr, + params->ldc, + params->c_dtype, + params->use_fast_accum, + std::nullopt /* alpha */); + return OK; + } +}; + +template +inline bool IsZero(T v) { + return v == 0.0f; +} + +template <> +inline bool IsZero(BFloat16 v) { + return v.x == 0; +} + +template <> +inline bool IsZero(Half v) { + return float(v) == 0.0f; +} + +template <> +inline bool IsZero(c10::complex v) { + return v == 0.0; +} + +template <> +inline bool IsZero(c10::complex v) { + return v == 0.0f; +} + +template +inline const char* TypeName(T v) { + return "unknown"; +} + +template <> +inline const char* TypeName(float v) { + if (at::globalContext().allowTF32CuBLAS()) { + return "tf32"; + } else { + return "float"; + } +} + +template <> +inline const char* TypeName(double v) { + return "double"; +} + +template <> +inline const char* TypeName(BFloat16 v) { + return "BFloat16"; +} + +template <> +inline const char* TypeName(Half v) { + return "Half"; +} + +template <> +inline const char* TypeName(Float8_e4m3fn v) { + return "Float8_e4m3fn"; +} + +template <> +inline const char* TypeName(Float8_e5m2 v) { + return "Float8_e5m2"; +} + +template <> +inline const char* TypeName(Float8_e4m3fnuz v) { + return "Float8_e4m3fnuz"; +} + +template <> +inline const char* TypeName(Float8_e5m2fnuz v) { + return "Float8_e5m2fnuz"; +} + +template <> +inline const char* TypeName(Float8_e8m0fnu v) { + return "Float8_e8m0fnu"; +} + +template <> +inline const char* TypeName(c10::complex v) { + return "c10::complex"; +} + +template <> +inline const char* TypeName(c10::complex v) { + return "c10::complex"; +} + +template +class GemmTunableOp + : public +#ifdef USE_ROCM + TunableOp> +#else + CublasltGemmTunableOp> +#endif +{ + public: + GemmTunableOp() { + this->RegisterOp(std::string("Default"), std::make_unique>()); + +#ifdef USE_ROCM + static const auto env_rocblas = c10::utils::check_env("PYTORCH_TUNABLEOP_ROCBLAS_ENABLED"); + if (!env_rocblas.has_value() || env_rocblas.value()) { + for (auto&& [name, op] : GetRocBlasGemmTypeStringAndOps()) { + this->RegisterOp(std::move(name), std::move(op)); + } + } + + static const auto env_hipblaslt = c10::utils::check_env("PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED"); + if (!env_hipblaslt.has_value() || env_hipblaslt.value()) { + // disallow tuning of hipblaslt with c10::complex + if constexpr ( + !std::is_same_v> && + !std::is_same_v>) { + for (auto&& [name, op] : GetHipBlasLtGemmTypeStringAndOps()) { + this->RegisterOp(std::move(name), std::move(op)); + } + } + } +#endif + + this->RegisterOp(std::string("Default"), std::make_unique>()); + } + + std::string Signature() override { + return fmt::sprintf("GemmTunableOp_%s_%c%c", TypeName(T{}), BlasOpToString(ALayout), BlasOpToString(BLayout)); + } +}; + +template +class GemmAndBiasTunableOp + : public +#ifdef USE_ROCM + TunableOp> +#else + CublasltGemmTunableOp> +#endif +{ + public: + GemmAndBiasTunableOp() { + this->RegisterOp(std::string("Default"), std::make_unique>()); + +#ifdef USE_ROCM + static const auto env_hipblaslt = c10::utils::check_env("PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED"); + if (!env_hipblaslt.has_value() || env_hipblaslt.value()) { + // disallow tuning of hipblaslt with c10::complex + if constexpr ( + !std::is_same_v> && + !std::is_same_v>) { + for (auto&& [name, op] : GetHipBlasLtGemmAndBiasTypeStringAndOps()) { + this->RegisterOp(std::move(name), std::move(op)); + } + } + } +#endif + + this->RegisterOp(std::string("Default"), std::make_unique>()); + } + + std::string Signature() override { + return fmt::sprintf("GemmAndBiasTunableOp_%s_%c%c", TypeName(T{}), BlasOpToString(ALayout), BlasOpToString(BLayout)); + } +}; + +template +class GemmStridedBatchedTunableOp + : public +#ifdef USE_ROCM + TunableOp> +#else + CublasltGemmTunableOp> +#endif +{ + public: + GemmStridedBatchedTunableOp() { + this->RegisterOp(std::string("Default"), std::make_unique>()); + +#ifdef USE_ROCM + static const auto env_rocblas = c10::utils::check_env("PYTORCH_TUNABLEOP_ROCBLAS_ENABLED"); + if (!env_rocblas.has_value() || env_rocblas.value()) { + for (auto&& [name, op] : GetRocBlasGemmStridedBatchedTypeStringAndOps()) { + this->RegisterOp(std::move(name), std::move(op)); + } + } + + static const auto env_hipblaslt = c10::utils::check_env("PYTORCH_TUNABLEOP_HIPBLASLT_ENABLED"); + if (!env_hipblaslt.has_value() || env_hipblaslt.value()) { + // disallow tuning of hipblaslt with c10::complex + if constexpr ( + !std::is_same_v> && + !std::is_same_v>) { + for (auto&& [name, op] : GetHipBlasLtGemmStridedBatchedTypeStringAndOps()) { + this->RegisterOp(std::move(name), std::move(op)); + } + } + } +#endif + + this->RegisterOp(std::string("Default"), std::make_unique>()); + } + + std::string Signature() override { + return fmt::sprintf("GemmStridedBatchedTunableOp_%s_%c%c", TypeName(T{}), BlasOpToString(ALayout), BlasOpToString(BLayout)); + } +}; + +template +class ScaledGemmTunableOp : public TunableOp> { + public: + ScaledGemmTunableOp() { + this->RegisterOp(std::string("Default"), std::make_unique>()); + +#ifdef USE_ROCM + for (auto&& [name, op] : GetHipBlasLtScaledGemmTypeStringAndOps()) { + this->RegisterOp(std::move(name), std::move(op)); + } +#endif + + this->RegisterOp(std::string("Default"), std::make_unique>()); + } + + std::string Signature() override { + return fmt::sprintf("ScaledGemmTunableOp_%s_%s_%s_%c%c", + TypeName(AT{}), + TypeName(BT{}), + TypeName(CT{}), + BlasOpToString(ALayout), BlasOpToString(BLayout)); + } +}; + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/TunableOp.h b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/TunableOp.h new file mode 100644 index 0000000000000000000000000000000000000000..5a44f67fd2558b3302409289c460470cc16b7693 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cuda/tunable/TunableOp.h @@ -0,0 +1,507 @@ +// Original TunableOp is from onnxruntime. +// https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/core/framework/tunable.h +// https://github.com/microsoft/onnxruntime/tree/main/onnxruntime/core/providers/rocm/tunable +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +// +// Adapting TunableOp into PyTorch +// Copyright (c) Advanced Micro Devices, Inc. +// +#pragma once + +#include +#include +#include +#include +#ifndef USE_ROCM +#include +#endif + +#ifndef _WIN32 +#include +#endif + +#ifndef USE_ROCM +#include +#endif +#include +#include +#include +#include + +namespace at::cuda::tunable { + +template +class Callable { + public: + virtual ~Callable() = default; + virtual TuningStatus Call(const ParamsT* /*unused*/) { + return FAIL; + } + virtual TuningStatus IsSupported(const ParamsT* params) { + return Call(params); + } +}; + +namespace { + +/** http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance */ + +class Stats { + public: + Stats() { + _n = 0UL; + _mean = 0.0; + _M2 = 0.0; + _sum = 0.0; + _min = 0.0; + _max = 0.0; + } + + void sample_value(const double x) { + double delta = 0; + _sum = _sum + x; + if (0UL == _n) { + _min = x; + _max = x; + } + else { + _min = _min < x ? _min : x; + _max = _max > x ? _max : x; + } + _n = _n + 1UL; + delta = x - _mean; + _mean = _mean + delta/_n; + _M2 = _M2 + delta * (x - _mean); + } + + double variance() const { + return _M2/(_n-1); + } + + double stddev() const { + return std::sqrt(variance()); + } + + unsigned long _n; + double _mean; + double _M2; + double _sum; + double _min; + double _max; +}; + +class FixedSizeStack { + private: + std::deque stack; + const size_t max_size; + + public: + FixedSizeStack(size_t size) : max_size(size) {} + + void push(const std::string& value) { + if (stack.size() >= max_size) { + stack.pop_front(); // Remove the oldest entry + } + stack.push_back(value); // Add new entry + } + + auto rbegin() { return stack.rbegin(); } + auto rend() { return stack.rend(); } +}; + +} // anonymous namespace + +template +class TunableOp { + public: + virtual ~TunableOp() = default; + + TuningStatus operator()(const ParamsT* params) { + ResultEntry result = ResultEntry::Null(); + TuningContext* ctx = getTuningContext(); + if (ctx->IsTunableOpEnabled()) { + auto& mgr = ctx->GetTuningResultsManager(); + auto op_sig = Signature(); + auto params_sig = params->Signature(); + auto blas_sig = params->BLASSignature(); + result = mgr.Lookup(op_sig, params_sig); + // If there is not previous tuning result been found, we do the tuning iff tuning is enabled + if (result == ResultEntry::Null()) { + bool should_record_untuned = !ctx->IsTuningEnabled(); + if (ctx->IsTuningEnabled()) { +#ifndef USE_ROCM + bool is_capturing = + c10::cuda::currentStreamCaptureStatusMayInitCtx() != + c10::cuda::CaptureStatus::None; + if (!is_capturing) { + RegisterOpCandidates(params); + result = FindFastest(params); + mgr.Add(op_sig, params_sig, result); + } else { + should_record_untuned = true; + } +#else + result = FindFastest(params); + mgr.Add(op_sig, params_sig, result); +#endif + } + if (should_record_untuned && ctx->IsRecordUntunedEnabled()) { + // or record the gemm into file + mgr.RecordUntuned(ctx->GetUntunedFile(), op_sig, params_sig, blas_sig); + } + } + } + else { + result = ResultEntry::Default(); + } + if (result == ResultEntry::Null()) { + TUNABLE_LOG2("no result, using default"); + result = ResultEntry::Default(); + } + auto* op = GetOp(result.GetKey()); +#ifndef USE_ROCM + if (op == nullptr && RegisterOpForResult(result, params)) { + op = GetOp(result.GetKey()); + } +#endif + if (op == nullptr) { + TUNABLE_LOG2("missing candidate ", result, ", using default"); + result = ResultEntry::Default(); + op = GetOp(result.GetKey()); + } + TORCH_CHECK(op != nullptr); + return op->Call(params); + } + + virtual std::string Signature() { + // According to C++17 standard https://wg21.link/n4659 section 15.7.4 + // > if the operand of typeid refers to the + // > object under construction or destruction, typeid yields the std::type_info object representing the constructor + // > or destructor’s class. + // So delay the op signature generation. + c10::call_once(signature_init_once_, [this]() { signature_ = CreateSignature(); }); + return signature_; + } + + protected: + void RegisterOp(const std::string& name, std::unique_ptr> op) { +#ifndef USE_ROCM + std::scoped_lock l{ops_lock_}; +#endif + this->op_names_.emplace_back(name); + this->ops_.emplace(name, std::move(op)); + } + + bool HasOp(const std::string& name) const { +#ifndef USE_ROCM + std::scoped_lock l{ops_lock_}; +#endif + return this->ops_.find(name) != this->ops_.end(); + } + + Callable* GetOp(const std::string& name) const { +#ifndef USE_ROCM + std::scoped_lock l{ops_lock_}; +#endif + auto it = ops_.find(name); + return it == ops_.end() ? nullptr : it->second.get(); + } + + std::vector OpNames() const { +#ifndef USE_ROCM + std::scoped_lock l{ops_lock_}; +#endif + return op_names_; + } + + virtual void RegisterOpCandidates(const ParamsT* /*params*/) {} + + virtual std::vector CandidateNames(const ParamsT* /*params*/) const { + return OpNames(); + } + +#ifndef USE_ROCM + virtual bool RegisterOpForResult( + const ResultEntry& /*result*/, + const ParamsT* /*params*/) { + return false; + } +#endif + + private: + static void WarmUp(Callable *op, const std::vector ¶m, size_t num_iter, size_t &offset) { + TuningContext* ctx = getTuningContext(); + bool do_flush = ctx->IsICacheFlushEnabled(); + for (size_t i = 0; i < num_iter; i++) { + if (do_flush) { + at::cuda::flush_icache(); + } + TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK); + } + } + + static double ProfileSimple(Callable *op, const std::vector ¶m, size_t num_iter, size_t &offset) { + TuningContext* ctx = getTuningContext(); + bool do_flush = ctx->IsICacheFlushEnabled(); + StreamTimerNoSync timer{}; + + // Small Mandatory Warmup + // Reduces outliers + for (size_t i = 0; i < 2; i++) { + TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK); + } + + timer.Start(); + for (size_t i = 0; i < num_iter; i++) { + if (do_flush) { + at::cuda::flush_icache(); + } + TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK); + } + timer.End(); + return timer.Duration() / num_iter; + } + + static Stats ProfileStats(Callable *op, const std::vector ¶m, size_t num_iter, size_t &offset) { + TuningContext* ctx = getTuningContext(); + bool do_flush = ctx->IsICacheFlushEnabled(); + std::vector timer(num_iter); + + // Small Mandatory Warmup + // Reduces outliers + for (size_t i = 0; i < 2; i++) { + TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK); + } + + for (size_t i = 0; i < num_iter; i++) { + timer[i].Start(); + TORCH_CHECK(op->Call(param[(i+offset++)%param.size()]) == OK); + timer[i].End(); + if (do_flush) { + at::cuda::flush_icache(); + } + } + Stats s; + for (size_t i = 0; i < num_iter; i++) { + s.sample_value(timer[i].Duration()); + } + return s; + } + + protected: + virtual ResultEntry FindFastest(const ParamsT* params) { + TuningContext* ctx = getTuningContext(); + auto op_sig = Signature(); + auto params_sig = params->Signature(); + auto blas_sig = params->BLASSignature(); + auto candidate_names = CandidateNames(params); + TUNABLE_LOG2("finding fastest for ", op_sig, '(', params_sig, ')', " out of ", candidate_names.size(), " candidates"); + auto min_duration_ms = std::numeric_limits::infinity(); + std::string id_name = "Default"; + ParamsT* reference_params = nullptr; + auto top_solns = FixedSizeStack(5); + + // numeric check option is controlled by non-static env var, so check it once per tuned operator + bool do_numerics_check = ctx->IsNumericsCheckEnabled(); + + // calculate a reference answer for numerical check + if (do_numerics_check) { + reference_params = params->DeepCopy(false); + auto* default_op = GetOp(ResultEntry::Default().GetKey()); + TORCH_CHECK(default_op != nullptr); + TORCH_CHECK(default_op->Call(reference_params) == OK); + } + + // need copies of params to reuse + // make as many copies as will fill the requested rotating buffer size, if requested + // rotating_size guaranteed to be >= 0 even though GetRotatingBufferSize() returns int + size_t rotating_size = ctx->GetRotatingBufferSize(); + bool use_buffer_rotation = (rotating_size > 0); + size_t param_size = params->GetSize(use_buffer_rotation); + size_t param_count = (rotating_size / param_size) + 1; + constexpr size_t MB = 1024ull*1024; + if (use_buffer_rotation) { + TUNABLE_LOG2("Rotating buffer ", rotating_size/MB, " MiB. ", + "Needed Size: ", param_size/MB, " MiB. ", + "Needed number of param copies: ", param_count); + } + TORCH_CHECK(param_count > 0); + + std::vector reusable_params(param_count); + for (size_t i = 0; i < param_count; i++) { + reusable_params[i] = params->DeepCopy(use_buffer_rotation); + } + + // for rotating buffer + size_t offset = 0; + + for (size_t i = 0; i < candidate_names.size(); i++) { + auto* candidate = GetOp(candidate_names[i]); // borrow pointer + TORCH_CHECK(candidate != nullptr); + + auto status = candidate->Call(reusable_params[0]); + if (status != OK) { + TUNABLE_LOG3("├──unsupported id=", i, ", ", op_sig, '(', params_sig, ") ", candidate_names[i]); + continue; + } + + // collect a small profile + int approx_num_iter = 3; + auto s = ProfileStats(candidate, reusable_params, approx_num_iter, offset); + double approx_duration = s._mean; + // bail if too slow + if (approx_duration > 1.5 * min_duration_ms) { + TUNABLE_LOG3("├──skip slow instance id=", i, ", ", op_sig, '(', params_sig, ") ", candidate_names[i]); + continue; + } + + // 2nd phase skip, more aggressive + approx_num_iter = 10; + s = ProfileStats(candidate, reusable_params, approx_num_iter, offset); + approx_duration = s._mean; + // bail if too slow + if (approx_duration > 1.15 * min_duration_ms) { + TUNABLE_LOG3("├──2nd skip slow instance id=", i, ", ", op_sig, '(', params_sig, ") ", candidate_names[i]); + continue; + } + + if (do_numerics_check) { + ParamsT* numerical_params = params->DeepCopy(false); + auto status = candidate->Call(numerical_params); + if (status != OK) { + numerical_params->Delete(); + TUNABLE_LOG3("├──unsupported id=", i, ", ", op_sig, '(', params_sig, ") ", candidate_names[i]); + continue; + } + status = reference_params->NumericalCheck(numerical_params); + numerical_params->Delete(); + if (status != OK) { + TUNABLE_LOG3("├──numerics check failed for id=", i, ", ", op_sig, '(', params_sig, ") ", candidate_names[i]); + continue; + } + } + + // for warmup does user set max duration, max iters, or both? + // warmup is skipped by default, i.e. warmup_iter = 0 + // warmup will be set to the non-zero value of max_warmup_duration + // or max_warmup_iter + // if both are non-zero, we take the smaller of the two. + double max_warmup_duration = ctx->GetMaxWarmupDurationMs(); + int max_warmup_iter = ctx->GetMaxWarmupIterations(); + int warmup_iter = 0; // default + if (max_warmup_duration > 0) { + int duration_iters = max_warmup_duration / approx_duration; + if (max_warmup_iter > 0) { + warmup_iter = std::min(max_warmup_iter, duration_iters); + } + else { + warmup_iter = duration_iters; + } + } + else if (max_warmup_iter > 0) { + warmup_iter = max_warmup_iter; + } + + // for tuning does user set max duration, max iters, or both? + double max_tuning_duration = ctx->GetMaxTuningDurationMs(); + int max_tuning_iter = ctx->GetMaxTuningIterations(); + int tuning_iter = 100; // default + if (max_tuning_duration > 0) { + int duration_iters = max_tuning_duration / approx_duration; + if (max_tuning_iter > 0) { + tuning_iter = std::min(max_tuning_iter, duration_iters); + } + else { + tuning_iter = duration_iters; + } + } + else if (max_tuning_iter > 0) { + tuning_iter = max_tuning_iter; + } + // tuning must run at least 1 iteration + tuning_iter = std::max(1, tuning_iter); + + // do the full warmup followed by tuning + double warmup_ms = warmup_iter * approx_duration; + double tuning_ms = tuning_iter * approx_duration; + TUNABLE_LOG3("├──tuning using " + "warmup iters ", warmup_iter, " [", warmup_ms, " ms] " + "and tuning iters ", tuning_iter, " [", tuning_ms, " ms] ", + "instance id=", i, ", ", op_sig, "(", params_sig, ") ", candidate_names[i]); + TUNABLE_LOG3("├──offset at ", offset); + WarmUp(candidate, reusable_params, warmup_iter, offset); + s = ProfileStats(candidate, reusable_params, tuning_iter, offset); + auto s_stddev = s.stddev(); + // Assume normal distribution. + // Solution with smallest mean + 2*sigma will be a better solution? + // if ((s._mean + 2*s_stddev) < (min_duration_ms + 2*min_stddev_ms)) { + if (s._mean < min_duration_ms) { + TUNABLE_LOG3("├──found better instance id=", i, ". " , s._mean, "ms. ", candidate_names[i], + " min ", s._min, + " max ", s._max, + " mean ", s._mean, + " std ", s_stddev); + min_duration_ms = s._mean; + id_name = candidate_names[i]; + std::string current_soln = std::to_string(s._mean) + " " + candidate_names[i]; + top_solns.push(current_soln); + } + else { + TUNABLE_LOG3("├──found slower instance id=", i, ". " , s._mean, "ms. ", candidate_names[i], + " min ", s._min, + " max ", s._max, + " mean ", s._mean, + " std ", s_stddev); + } + } + + for (size_t i = 0; i < reusable_params.size(); i++) { + reusable_params[i]->Delete(); + } + if (reference_params) { + reference_params->Delete(); + } + + TUNABLE_LOG2("└──found fastest for ", op_sig, '(', params_sig, ") ", id_name); + TUNABLE_LOG2("└──top five solutions for ", op_sig, '(', params_sig, ") "); + for (auto it = top_solns.rbegin(); it != top_solns.rend(); ++it) { + TUNABLE_LOG2(" ", *it); + } + return ResultEntry(id_name, min_duration_ms, blas_sig); + } + + private: + std::string CreateSignature() { +#ifndef _WIN32 + const auto* name = typeid(*this).name(); + // NOLINTNEXTLINE(*array*) + char buf[256]; + size_t buf_len = 256; + abi::__cxa_demangle(name, buf, &buf_len, nullptr); + buf[255] = '\0'; + return buf; +#else + return typeid(*this).name(); +#endif + } + + mutable c10::once_flag signature_init_once_; + std::string signature_; + + std::unordered_map>> ops_; + std::vector op_names_; +#ifndef USE_ROCM + mutable std::mutex ops_lock_; +#endif +}; + +struct OpParams { + OpParams() = default; + OpParams(const OpParams&) = default; + virtual ~OpParams() = default; + virtual std::string Signature() const = 0; + virtual std::string BLASSignature() const = 0; +}; + +} // namespace at::cuda::tunable diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/AutocastRNN.cpp b/western_ai/usa/pytorch/aten/src/ATen/cudnn/AutocastRNN.cpp new file mode 100644 index 0000000000000000000000000000000000000000..077cb6bdf20eb166a446ddd65b4f73a35a69d229 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/AutocastRNN.cpp @@ -0,0 +1,127 @@ +#include +#include + +// pulls in AT_CUDNN_ENABLED() as defined by cmake +#include + +#if AT_CUDNN_ENABLED() +#include +#endif + + +namespace at::autocast { + +/******************************************************************************** +Autocast wrapper for CuDNN RNNs (the weight reflattening needs special attention) +********************************************************************************/ + +// To be registered for the "_cudnn_rnn(...)" schema. +// _cudnn_rnn is autograd-exposed (test_autocast_cudnn_rnn in test_cuda.py includes a test to confirm) +static std::tuple +_cudnn_rnn_cast_reflatten(const Tensor & input, + TensorList weight, + int64_t weight_stride0, + const std::optional& weight_buf_opt, + const Tensor& hx, + const std::optional& cx, + int64_t mode, + int64_t hidden_size, + int64_t proj_size, + int64_t num_layers, + bool batch_first, + double dropout, + bool train, + bool bidirectional, + IntArrayRef batch_sizes, + const std::optional& dropout_state) { +#if AT_CUDNN_ENABLED() + c10::impl::ExcludeDispatchKeyGuard no_autocast(DispatchKey::Autocast); + + for (const auto& t : weight) { + TORCH_CHECK(weight[0].scalar_type() == t.scalar_type(), "Weight scalar types do not match."); + } + // weight_stride0 is the number of weight tensors per layer and direction, as seen by model.parameters(). + // If bias is enabled, there are 4 such tensors (ih and hh weights, ih and hh biases). + // If bias is not enabled, there are 2 (ih and hh weights). + // This organization holds for all rnn types (RNN, GRU, and LSTM). If LSTM with projections is + // used, additional hr weight is added. + if (proj_size > 0) { + TORCH_INTERNAL_ASSERT((weight_stride0 == 3) || (weight_stride0 == 5), + "weight_stride0 must be 3 (if no bias) or 5 (if bias) for LSTM with projections. Received ", + weight_stride0); + } else { + TORCH_INTERNAL_ASSERT((weight_stride0 == 2) || (weight_stride0 == 4), + "weight_stride0 must be 2 (if no bias) or 4 (if bias). Received ", + weight_stride0); + } + + + Tensor weight_buf, redispatch_weight_buf; + std::vector redispatch_weight; + // There's an implicit contract here with native/cudnn/RNN.cpp:_cudnn_impl, which calls at:_cudnn_rnn. + // Code here assumes if _cudnn_impl passes weight_buf_opt containing a defined tensor, that tensor + // is valid flat storage of the weights in their incoming dtype. + if (weight_buf_opt.has_value()) { + weight_buf = *weight_buf_opt; + } + bool needs_cast_and_flatten = (weight_buf.defined() ? + // weight_buf is valid. Only change it if it's eligible and not already FP16. + is_eligible(weight_buf) && (weight_buf.scalar_type() != at::kHalf) : + // weight_buf is not valid. Only create it if other weights are eligible and not already FP16. + is_eligible(weight[0]) && (weight[0].scalar_type() != at::kHalf)); + if (needs_cast_and_flatten) { + // Casts weight tensors to FP16 and ensures all weights for all layers are views into a large flat buffer, + // with the right locations and layouts expected by cudnn. + // This is (and should be) autograd-exposed. + bool include_bias = true; + if (weight_stride0 == 2 || (weight_stride0 == 3 && proj_size > 0)) { + include_bias = false; + } + std::tie(redispatch_weight_buf, redispatch_weight) = + at::native::cudnn_rnn::copy_weights_to_flat_buf_views( + weight, + weight_stride0, + input.size(-1), + mode, + hidden_size, + proj_size, + num_layers, + batch_first, + bidirectional, + /*flat_buf_datatype=*/at::native::getCudnnDataTypeFromScalarType(at::kHalf), // could just hardcode CUDNN_DATA_HALF + /*flat_buf_options=*/weight[0].options().dtype(at::kHalf), + /*set_orig_weights_to_flat_buf=*/false, + /*allow_type_change=*/true, + /*include_bias=*/include_bias); + } + return at::_cudnn_rnn( + cached_cast(at::kHalf, input), + needs_cast_and_flatten ? TensorList(redispatch_weight) : weight, + weight_stride0, + needs_cast_and_flatten ? redispatch_weight_buf : weight_buf, + cached_cast(at::kHalf, hx), + cached_cast(at::kHalf, cx), + mode, + hidden_size, + proj_size, + num_layers, + batch_first, + dropout, + train, + bidirectional, + batch_sizes, + dropout_state); +#else // AT_CUDNN_ENABLED() + TORCH_CHECK(false, "autocast::_cudnn_rnn_cast_reflatten: ATen not compiled with cuDNN support"); + return {Tensor{}, Tensor{}, Tensor{}, Tensor{}, Tensor{}}; // never reached, placates the compiler +#endif // AT_CUDNN_ENABLED() +} + +namespace { +TORCH_LIBRARY_IMPL(aten, Autocast, m) { + m.impl("_cudnn_rnn", + TORCH_FN((&at::autocast::_cudnn_rnn_cast_reflatten))); +} +} // anonymous namespace + +} // namespace at::autocast diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Descriptors.cpp b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Descriptors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1414b840a46a05f5989e5859afdfe524803f6b48 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Descriptors.cpp @@ -0,0 +1,197 @@ +#include + +#include + +#include +#include +#include + +// NOLINTBEGIN(*c-arrays*) +namespace at::native { + +namespace { + +inline cudnnDataType_t getDataType(const at::Tensor& t) { + auto scalar_type = t.scalar_type(); + if (scalar_type == at::kFloat) { + return CUDNN_DATA_FLOAT; + } else if (scalar_type == at::kHalf) { + return CUDNN_DATA_HALF; + } else if (scalar_type == at::kDouble) { + return CUDNN_DATA_DOUBLE; + } + else if (scalar_type == at::kBFloat16) { + return CUDNN_DATA_BFLOAT16; + } else if (scalar_type == at::kQInt8) { + return CUDNN_DATA_INT8; + } + TORCH_CHECK(false, "TensorDescriptor does not support ", scalar_type); +} + +} // anonymous namespace + +void RNNDataDescriptor::set(const at::Tensor &t, const cudnnRNNDataLayout_t layout, const int maxSeqLength, const int batchSize, const int vectorSize, const int* seqLengthArray) { + set(getDataType(t), layout, maxSeqLength, batchSize, vectorSize, seqLengthArray); +} + +void TensorDescriptor::set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad) { + set(getDataType(t), t.sizes(), t.strides(), pad, + memory_format == at::MemoryFormat::ChannelsLast || + memory_format == at::MemoryFormat::ChannelsLast3d); +} + +void TensorDescriptor::set(const at::Tensor &t, size_t pad) { + auto memory_format = t.suggest_memory_format(); + set(getDataType(t), t.sizes(), t.strides(), pad, + memory_format == at::MemoryFormat::ChannelsLast || + memory_format == at::MemoryFormat::ChannelsLast3d); +} + +void TensorDescriptor::set(cudnnDataType_t datatype, IntArrayRef t_sizes, IntArrayRef t_strides, size_t pad) { + set(datatype, t_sizes, t_strides, pad, + is_channels_last_strides_2d(t_sizes, t_strides) || + is_channels_last_strides_3d(t_sizes, t_strides)); +} + +void TensorDescriptor::set(cudnnDataType_t datatype, IntArrayRef t_sizes, IntArrayRef t_strides, size_t pad, bool nhwc) { + size_t dim = t_sizes.size(); + if (dim > CUDNN_DIM_MAX || pad > CUDNN_DIM_MAX) + TORCH_CHECK(false, "cuDNN supports only up to ", CUDNN_DIM_MAX, " dimensions"); + int size[CUDNN_DIM_MAX]; + int stride[CUDNN_DIM_MAX]; + for (const auto i : c10::irange(dim)) { + size[i] = static_cast(t_sizes[i]); + stride[i] = static_cast(t_strides[i]); + } + for (const auto i : c10::irange(dim, pad)) { + size[i] = 1; + stride[i] = 1; + } + set(datatype, static_cast(std::max(dim, pad)), size, stride, nhwc); +} + +std::string cudnnTypeToString(cudnnDataType_t dtype) { + switch (dtype) { + case CUDNN_DATA_FLOAT: + return "CUDNN_DATA_FLOAT"; + case CUDNN_DATA_DOUBLE: + return "CUDNN_DATA_DOUBLE"; + case CUDNN_DATA_HALF: + return "CUDNN_DATA_HALF"; + case CUDNN_DATA_BFLOAT16: + return "CUDNN_DATA_BFLOAT16"; + case CUDNN_DATA_INT8: + return "CUDNN_DATA_INT8"; + case CUDNN_DATA_INT32: + return "CUDNN_DATA_INT32"; + case CUDNN_DATA_INT8x4: + return "CUDNN_DATA_INT8x4"; + case CUDNN_DATA_UINT8: + return "CUDNN_DATA_UINT8"; + case CUDNN_DATA_UINT8x4: + return "CUDNN_DATA_UINT8x4"; + default: + std::ostringstream oss; + oss << "(unknown data-type " << static_cast(dtype) << ')'; + return oss.str(); + } +} + +std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d) { + out << "TensorDescriptor " << static_cast(d.desc()) << '\n'; + int nbDims = 0; + int dimA[CUDNN_DIM_MAX]; + int strideA[CUDNN_DIM_MAX]; + cudnnDataType_t dtype{}; + cudnnGetTensorNdDescriptor(d.desc(), CUDNN_DIM_MAX, &dtype, &nbDims, dimA, strideA); + out << " type = " << cudnnTypeToString(dtype) << '\n'; + out << " nbDims = " << nbDims << '\n'; + // Read out only nbDims of the arrays! + out << " dimA = "; + for (auto i : ArrayRef{dimA, static_cast(nbDims)}) { + out << i << ", "; + } + out << '\n'; + out << " strideA = "; + for (auto i : ArrayRef{strideA, static_cast(nbDims)}) { + out << i << ", "; + } + out << '\n'; + return out; +} + +void TensorDescriptor::print() { std::cout << *this; } + +void FilterDescriptor::set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad) { + auto dim = t.ndimension(); + if (dim > CUDNN_DIM_MAX || pad > CUDNN_DIM_MAX) + TORCH_CHECK(false, "cuDNN supports only up to ", CUDNN_DIM_MAX, " dimensions"); + // NB: It is possible for this test to be insufficient, because the + // Tensor passed in to set the filter descriptor may not be the actual + // Tensor whose data pointer is passed to cuDNN. Nevertheless, + // that is the common case, so we can catch most client errors with this test. + TORCH_CHECK(t.is_contiguous(memory_format), + "cuDNN filters (a.k.a. weights) must be contiguous in desired memory_format\n", + "Weight sizes: ", t.sizes(), "\n", + "Weight strides: ", t.strides(), "\n", + "cuDNN suggested memory_format: ", memory_format); + + std::array size; + for (const auto i : c10::irange(dim)) { + size[i] = static_cast(t.size(i)); + } + for (const auto i : c10::irange(dim, pad)) { + size[i] = 1; + } + dim = std::max(dim, pad); + cudnnTensorFormat_t filter_format{}; + switch(memory_format) { + case at::MemoryFormat::Contiguous: + filter_format = CUDNN_TENSOR_NCHW; + break; + case at::MemoryFormat::ChannelsLast: + case at::MemoryFormat::ChannelsLast3d: + filter_format = CUDNN_TENSOR_NHWC; + break; + default: + TORCH_INTERNAL_ASSERT(false, "unsupported memory_format for cuDNN filters"); + } + set(getDataType(t), static_cast(dim), size.data(), filter_format); +} + +std::string cudnnMemoryFormatToString(cudnnTensorFormat_t tformat) { + switch (tformat) { + case CUDNN_TENSOR_NCHW: + return "CUDNN_TENSOR_NCHW"; + case CUDNN_TENSOR_NHWC: + return "CUDNN_TENSOR_NHWC"; + default: + std::ostringstream oss; + oss << "(unknown cudnn tensor format " << static_cast(tformat) << ')'; + return oss.str(); + } +} + +std::ostream& operator<<(std::ostream & out, const FilterDescriptor& d) { + out << "FilterDescriptor " << static_cast(d.desc()) << '\n'; + int nbDims = 0; + int dimA[CUDNN_DIM_MAX]; + cudnnDataType_t dtype{}; + cudnnTensorFormat_t tformat{}; + cudnnGetFilterNdDescriptor(d.desc(), CUDNN_DIM_MAX, &dtype, &tformat, &nbDims, dimA); + out << " type = " << cudnnTypeToString(dtype) << '\n'; + out << " tensor_format = " << cudnnMemoryFormatToString(tformat) << '\n'; + out << " nbDims = " << nbDims << '\n'; + // Read out only nbDims of the arrays! + out << " dimA = "; + for (auto i : ArrayRef{dimA, static_cast(nbDims)}) { + out << i << ", "; + } + out << '\n'; + return out; +} + +void FilterDescriptor::print() { std::cout << *this; } + +} +// NOLINTEND(*c-arrays*) diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Descriptors.h b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Descriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..eb474fc22ba0c6998cc8b316d206ddf34bb39377 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Descriptors.h @@ -0,0 +1,410 @@ +#pragma once + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#if defined(CUDNN_VERSION) && CUDNN_VERSION >= 8907 +#define USE_CUDNN_RNN_V8_API +#endif + +namespace at::native { + +std::string cudnnTypeToString(cudnnDataType_t dtype); + +// TODO: Add constructors for all of the descriptors + +inline int dataSize(cudnnDataType_t dataType) +{ + switch (dataType) { + case CUDNN_DATA_BFLOAT16: + case CUDNN_DATA_HALF: return 2; + case CUDNN_DATA_FLOAT: return 4; + default: return 8; + } +} + +// NOTE [ cudnn fixSizeOneDimStride ] +// The stride for a size-1 dimensions is not uniquely determined; in +// fact, it can be anything you want, because the fact that the +// tensor is size 1 at this dimension means that you will never actually +// try advancing your pointer by this stride. +// +// However, CuDNN has a much more stringent requirement on strides: +// if you are passing a contiguous input, it better be the case +// that the stride for dim i is the product of the sizes of dims +// i+1 to the end. This stride is indeed uniquely determined. This +// function modifies 'stride' in place so this invariant holds. +template +static inline void fixSizeOneDimStride(int dim, const T *size, T *stride, bool nhwc) { + int64_t z = 1; + int index = 0; + std::vector permutation(dim); + + if (nhwc) { + permutation[index++] = 1; + } + for (int d = dim-1; d > 1; d--) { + permutation[index++] = d; + } + if (!nhwc) { + permutation[index++] = 1; + } + permutation[index++] = 0; + for (int d : permutation) { + if (size[d] == 1) { + stride[d] = z; + } else { + z *= size[d]; + } + } +} + +template +struct DescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + AT_CUDNN_CHECK(dtor(x)); + } + } +}; + +// A generic class for wrapping cuDNN descriptor types. All you need +// is to give the underlying type the Descriptor_t points to (usually, +// if it's cudnnTensorDescriptor_t it points to cudnnTensorStruct), +// the constructor and the destructor. Subclasses are responsible +// for defining a set() function to actually set the descriptor. +// +// Descriptors default construct to a nullptr, and have a descriptor +// initialized the first time you call set() or any other initializing +// function. +template +// NOLINTNEXTLINE(bugprone-exception-escape) +class TORCH_CUDA_CPP_API Descriptor { + public: + // TODO: Figure out why const-correctness doesn't work here + + // Use desc() to access the underlying descriptor pointer in + // a read-only fashion. Most client code should use this. + // If the descriptor was never initialized, this will return + // nullptr. + T* desc() const { return desc_.get(); } + T* desc() { return desc_.get(); } + + // Use mut_desc() to access the underlying descriptor pointer + // if you intend to modify what it points to (e.g., using + // cudnnSetFooDescriptor). This will ensure that the descriptor + // is initialized. Code in this file will use this function. + T* mut_desc() { init(); return desc_.get(); } +protected: + void init() { + if (desc_ == nullptr) { + T* raw_desc = nullptr; + AT_CUDNN_CHECK(ctor(&raw_desc)); + desc_.reset(raw_desc); + } + } +private: + std::unique_ptr> desc_; +}; + +class TORCH_CUDA_CPP_API RNNDataDescriptor : public Descriptor< + cudnnRNNDataStruct, + &cudnnCreateRNNDataDescriptor, + &cudnnDestroyRNNDataDescriptor> { +public: + void set(const at::Tensor &t, cudnnRNNDataLayout_t layout, int maxSeqLength, int batchSize, int vectorSize, const int* seqLengthArray); +private: + void set(cudnnDataType_t dataType, cudnnRNNDataLayout_t layout, int maxSeqLength, int batchSize, int vectorSize, const int* seqLengthArray) { + AT_CUDNN_CHECK(cudnnSetRNNDataDescriptor(mut_desc(), dataType, layout, maxSeqLength, batchSize, vectorSize, seqLengthArray, nullptr)); + } +}; + +class TORCH_CUDA_CPP_API TensorDescriptor : public Descriptor< + cudnnTensorStruct, + &cudnnCreateTensorDescriptor, + &cudnnDestroyTensorDescriptor> { + public: + TensorDescriptor() = default; + explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) { + set(t, pad); + } + + // Note [CuDNN broadcast padding] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // pad specifies the minimum dimensionality of the tensor descriptor + // we produce (it doesn't have anything to do with, e.g., convolution + // padding). If 't' is lower-dimensional than 'pad', the remaining + // dimensions (on the right) are padded with ones. This doesn't + // affect the underlying data layout. This is particularly useful for + // dealing with a peculiarity of the CuDNN API, which is that broadcasting in CuDNN is + // done in two steps: first, the client code is expected to pad out + // (the dimensions) input tensors to be the same dimension as the + // target broadcast, and then second, CuDNN takes of actually + // broadcasting size 1 dimensions. + + void set(const at::Tensor &t, size_t pad = 0); + void set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad = 0); + void set(cudnnDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0); + + void print(); + +private: + void set(cudnnDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad, bool nhwc); + + void set(cudnnDataType_t dataType, int dim, int* size, int* stride, bool nhwc) { + std::vector strides_copy(stride, stride + dim); + fixSizeOneDimStride(dim, size, strides_copy.data(), nhwc); + AT_CUDNN_CHECK(cudnnSetTensorNdDescriptor(mut_desc(), dataType, dim, size, strides_copy.data())); + } +}; + +std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d); + +class TORCH_CUDA_CPP_API FilterDescriptor : public Descriptor< + cudnnFilterStruct, + &cudnnCreateFilterDescriptor, + &cudnnDestroyFilterDescriptor> { + public: + void set(const at::Tensor &t, int64_t pad = 0) { + set(t, at::MemoryFormat::Contiguous, pad); + } + + void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0); + + void print(); +private: + void set(cudnnDataType_t dataType, int dim, int* size, cudnnTensorFormat_t filter_format) { + AT_CUDNN_CHECK(cudnnSetFilterNdDescriptor(mut_desc(), dataType, filter_format, dim, size)); + } +}; + +std::ostream& operator<<(std::ostream & out, const FilterDescriptor& d); + +struct TORCH_CUDA_CPP_API ConvolutionDescriptor + : public Descriptor< + cudnnConvolutionStruct, + &cudnnCreateConvolutionDescriptor, + &cudnnDestroyConvolutionDescriptor> { + void set(cudnnDataType_t dataType, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool allow_tf32) { + cudnnDataType_t mathType = dataType; + if (dataType == CUDNN_DATA_HALF) mathType = CUDNN_DATA_FLOAT; + AT_CUDNN_CHECK(cudnnSetConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, + CUDNN_CROSS_CORRELATION, mathType)); + AT_CUDNN_CHECK(cudnnSetConvolutionGroupCount(mut_desc(), groups)); + // See Note [behavior of cudnnFind and cudnnGet] + AT_CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_DEFAULT_MATH)); + if(dataType == CUDNN_DATA_HALF) { + AT_CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_TENSOR_OP_MATH)); + } else if (dataType == CUDNN_DATA_FLOAT && !allow_tf32) { + AT_CUDNN_CHECK(cudnnSetConvolutionMathType(mut_desc(), CUDNN_FMA_MATH)); + } + } +}; + +struct TORCH_CUDA_CPP_API SpatialTransformerDescriptor + : public Descriptor< + cudnnSpatialTransformerStruct, + &cudnnCreateSpatialTransformerDescriptor, + &cudnnDestroySpatialTransformerDescriptor> { + void set(cudnnDataType_t dataType, int dim, int* size) { + AT_CUDNN_CHECK(cudnnSetSpatialTransformerNdDescriptor(mut_desc(), CUDNN_SAMPLER_BILINEAR, dataType, dim, size)); + } +}; + +// NOLINTNEXTLINE(bugprone-exception-escape) +struct TORCH_CUDA_CPP_API DropoutDescriptor + : public Descriptor< + cudnnDropoutStruct, + &cudnnCreateDropoutDescriptor, + &cudnnDestroyDropoutDescriptor> { + at::Tensor state; + + // Initialize a dropout descriptor's RNG state. + // WARNING: This function is very expensive, avoid calling this function! + void initialize_rng(cudnnHandle_t handle, float dropout, long long int seed, const TensorOptions& options) { + TORCH_INTERNAL_ASSERT(dropout > 0, "dropout must be nonzero; otherwise call set_no_dropout"); + size_t state_size = 0; + AT_CUDNN_CHECK(cudnnDropoutGetStatesSize(handle, &state_size)); + AT_ASSERT(options.device().type() == kCUDA); + AT_ASSERT(options.dtype() == kByte); + state = at::empty({static_cast(state_size)}, options); + AT_CUDNN_CHECK(cudnnSetDropoutDescriptor(mut_desc(), handle, dropout, state.data_ptr(), state_size, seed)); + } + + // Restore a dropout descriptor given a dropout probability and existing RNG state. + void set(cudnnHandle_t handle, float dropout, const at::Tensor& state) { + TORCH_INTERNAL_ASSERT(dropout > 0, "dropout must be nonzero; otherwise call set_no_dropout"); + void *state_ptr = state.data_ptr(); + size_t state_size = state.size(0); + // NB: The seed doesn't actually matter, so we give a dummy value + AT_CUDNN_CHECK(cudnnRestoreDropoutDescriptor(mut_desc(), handle, dropout, state_ptr, state_size, 0 /* seed */)); + } + + // Restore a dropout descriptor corresponding to no dropout + void set_no_dropout(cudnnHandle_t handle) { + // NB: seed doesn't matter when dropout = 0, because no random number + // initialization actually takes place when there is no dropout. + // NB: Empirically, cudnnSetDropoutDescriptor is cheap when + // dropout == 0 + AT_CUDNN_CHECK(cudnnSetDropoutDescriptor(mut_desc(), handle, 0 /* dropout */, nullptr, 0 /* state_size */, 0 /* seed */)); + } +}; + +struct TORCH_CUDA_CPP_API RNNDescriptor : public Descriptor< + cudnnRNNStruct, + &cudnnCreateRNNDescriptor, + &cudnnDestroyRNNDescriptor> { + DropoutDescriptor dropout_desc_; + void set(cudnnHandle_t handle, +#ifdef USE_CUDNN_RNN_V8_API + int input_size, + bool packed, +#endif + int hidden_size, int proj_size, int num_layers, DropoutDescriptor&& dropout_desc, + cudnnRNNInputMode_t input_mode, cudnnDirectionMode_t bidirectional, + cudnnRNNMode_t mode, cudnnDataType_t datatype, cudnnDataType_t input_type, cudnnRNNAlgo_t algo, bool allow_tf32) { + dropout_desc_ = std::move(dropout_desc); +#ifndef USE_CUDNN_RNN_V8_API + AT_CUDNN_CHECK(cudnnSetRNNDescriptor_v6( + handle, + mut_desc(), + hidden_size, + num_layers, + dropout_desc_.desc(), + input_mode, + bidirectional, + mode, + algo, + datatype)); + if (proj_size != 0) { + AT_CUDNN_CHECK(cudnnSetRNNProjectionLayers( + handle, + /*rnnDesc=*/mut_desc(), + /*recProjSize=*/proj_size, + /*outProjSize=*/0)); + } + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + if (prop->major >= 7) { + if (input_type == CUDNN_DATA_HALF) { + cudnnSetRNNMatrixMathType(mut_desc(), CUDNN_TENSOR_OP_MATH); + } + else if (input_type == CUDNN_DATA_FLOAT && !allow_tf32) { + cudnnSetRNNMatrixMathType(mut_desc(), CUDNN_FMA_MATH); + } + else { + // Technically, as the default it's not necessary to explicitly + // set this. + cudnnSetRNNMatrixMathType(mut_desc(), CUDNN_DEFAULT_MATH); + } + } +#else + cudaDeviceProp* prop = at::cuda::getCurrentDeviceProperties(); + auto math_type = CUDNN_DEFAULT_MATH; + if (prop->major >= 7) { + if (input_type == CUDNN_DATA_HALF) { + math_type = CUDNN_TENSOR_OP_MATH; + } else if (!allow_tf32) { + math_type = CUDNN_FMA_MATH; + } + } + AT_CUDNN_CHECK(cudnnSetRNNDescriptor_v8( + mut_desc(), + algo, + mode, + CUDNN_RNN_DOUBLE_BIAS, + bidirectional, + input_mode, + input_type, + datatype, + math_type, + input_size, + hidden_size, + proj_size ? proj_size : hidden_size, + num_layers, + dropout_desc_.desc(), + packed ? CUDNN_RNN_PADDED_IO_DISABLED : CUDNN_RNN_PADDED_IO_ENABLED)); +#endif + } +}; + +struct TORCH_CUDA_CPP_API CTCLossDescriptor + : public Descriptor< + cudnnCTCLossStruct, + &cudnnCreateCTCLossDescriptor, + &cudnnDestroyCTCLossDescriptor> { + void set(cudnnDataType_t datatype) { + AT_CUDNN_CHECK(cudnnSetCTCLossDescriptor(mut_desc(), datatype)); + } + void setEx( + cudnnDataType_t datatype, + cudnnLossNormalizationMode_t normMode, + cudnnNanPropagation_t gradMode) { + AT_CUDNN_CHECK( + cudnnSetCTCLossDescriptorEx(mut_desc(), datatype, normMode, gradMode)); + } + void set_v8_v9( + cudnnDataType_t datatype, + cudnnLossNormalizationMode_t normMode, + cudnnNanPropagation_t gradMode, + int maxLabelLength) { +#if defined(CUDNN_VERSION) && CUDNN_VERSION >= 90000 + auto gradModev9 = CUDNN_CTC_ZERO_OOB_GRADIENTS; + if (gradMode == cudnnNanPropagation_t::CUDNN_PROPAGATE_NAN) { + gradModev9 = CUDNN_CTC_SKIP_OOB_GRADIENTS; + } + AT_CUDNN_CHECK( + cudnnSetCTCLossDescriptor_v9(mut_desc(), datatype, normMode, gradModev9, maxLabelLength)); +#else + AT_CUDNN_CHECK( + cudnnSetCTCLossDescriptor_v8(mut_desc(), datatype, normMode, gradMode, maxLabelLength)); +#endif + } + +}; + +struct TORCH_CUDA_CPP_API ActivationDescriptor + : public Descriptor< + cudnnActivationStruct, + &cudnnCreateActivationDescriptor, + &cudnnDestroyActivationDescriptor> { + void set(cudnnActivationMode_t mode) { + AT_ASSERT( + mode == CUDNN_ACTIVATION_RELU, + "TODO: support more cuDNN activation modes"); + AT_CUDNN_CHECK(cudnnSetActivationDescriptor( + mut_desc(), + mode, + cudnnNanPropagation_t::CUDNN_NOT_PROPAGATE_NAN, + std::numeric_limits::max())); + } +}; + +union Constant +{ + float f; + double d; + Constant(cudnnDataType_t dataType, double value) { + if (dataType == CUDNN_DATA_HALF || dataType == CUDNN_DATA_FLOAT) { + f = static_cast(value); + } else { + d = value; + } + } +}; + +} // namespace diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handle.cpp b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ac24e51972b159aa3b7128501a2d2eec1e82e55 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handle.cpp @@ -0,0 +1,57 @@ +#include +#include +#include + +#include + +namespace at::native { +namespace { + +void createCuDNNHandle(cudnnHandle_t* handle) { + AT_CUDNN_CHECK(cudnnCreate(handle)); +} + +void destroyCuDNNHandle(cudnnHandle_t /*handle*/) { + // this is because of something dumb in the ordering of + // destruction. Sometimes atexit, the cuda context (or something) + // would already be destroyed by the time this gets destroyed. It + // happens in fbcode setting. @colesbury and I decided to not destroy + // the handle as a workaround. + // - @soumith + // + // Further note: this is now disabled globally, because we are seeing + // the same issue as mentioned above in CUDA 11 CI. + // - @zasdfgbnm + // + // #ifdef NO_CUDNN_DESTROY_HANDLE + // #else + // cudnnDestroy(handle); + // #endif +} + +using CudnnPoolType = at::cuda::DeviceThreadHandlePool< + cudnnHandle_t, + createCuDNNHandle, + destroyCuDNNHandle>; + +} // namespace + +cudnnHandle_t getCudnnHandle() { + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(c10::cuda::GetDevice(&device)); + + // Thread local PoolWindows are lazily-initialized + // to avoid initialization issues that caused hangs on Windows. + // See: https://github.com/pytorch/pytorch/pull/22405 + // This thread local unique_ptrs will be destroyed when the thread terminates, + // releasing its reserved handles back to the pool. + static auto pool = std::make_shared(); + thread_local std::unique_ptr myPoolWindow( + pool->newPoolWindow()); + + auto handle = myPoolWindow->reserve(device); + AT_CUDNN_CHECK(cudnnSetStream(handle, c10::cuda::getCurrentCUDAStream())); + return handle; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handle.h b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handle.h new file mode 100644 index 0000000000000000000000000000000000000000..a665e4bc5178a8aabc654630ace47112a5320961 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handle.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +namespace at::native { + +TORCH_CUDA_CPP_API cudnnHandle_t getCudnnHandle(); +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handles.h b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handles.h new file mode 100644 index 0000000000000000000000000000000000000000..65b5d4454879ad165c8e002fc5df4c400da9303a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Handles.h @@ -0,0 +1,2 @@ +#pragma once +#include diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/README.md b/western_ai/usa/pytorch/aten/src/ATen/cudnn/README.md new file mode 100644 index 0000000000000000000000000000000000000000..29243501d4982b1aca29121a9f41befdff5a19cd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/README.md @@ -0,0 +1,4 @@ +All files living in this directory are written with the assumption that cuDNN is available, +which means that these code are not guarded by `#if AT_CUDNN_ENABLED()`. Therefore, whenever +you need to use definitions from here, please guard the `#include` and +definition usages with `#if AT_CUDNN_ENABLED()` macro, e.g. [native/cudnn/BatchNorm.cpp](../native/cudnn/BatchNorm.cpp). diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Types.cpp b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f6ac075b8855bf6cd6fdd4f0377b8fe98a9843a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Types.cpp @@ -0,0 +1,38 @@ +#include + + +#include + +namespace at::native { + +cudnnDataType_t getCudnnDataTypeFromScalarType(const at::ScalarType dtype) { + if (dtype == c10::kQInt8 || dtype == at::kChar) { + return CUDNN_DATA_INT8; + } else if (dtype == at::kFloat) { + return CUDNN_DATA_FLOAT; + } else if (dtype == at::kDouble) { + return CUDNN_DATA_DOUBLE; + } else if (dtype == at::kHalf) { + return CUDNN_DATA_HALF; + } else if (dtype == at::kBFloat16) { + return CUDNN_DATA_BFLOAT16; + } else if (dtype == at::kInt) { + return CUDNN_DATA_INT32; + } else if (dtype == at::kByte) { + return CUDNN_DATA_UINT8; + } + TORCH_CHECK(false, + "getCudnnDataTypeFromScalarType() not supported for ", + toString(dtype) + ); +} + +cudnnDataType_t getCudnnDataType(const at::Tensor& tensor) { + return getCudnnDataTypeFromScalarType(tensor.scalar_type()); +} + +int64_t cudnn_version() { + return CUDNN_VERSION; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Types.h b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Types.h new file mode 100644 index 0000000000000000000000000000000000000000..9c72a414ecf38465ab0ae97d7bc33dde57eb23ba --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Types.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace at::native { + +TORCH_CUDA_CPP_API cudnnDataType_t +getCudnnDataTypeFromScalarType(const at::ScalarType dtype); +cudnnDataType_t getCudnnDataType(const at::Tensor& tensor); + +int64_t cudnn_version(); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/Utils.h b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..49631ab2886c9e45fd1d2848bdff025f4f4ecfe7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/Utils.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include +#include + +namespace at::native { + +// cuDNN has a buggy check for tensor being contiguous (that is, it does +// not ignore stride for dimension that is equal to 0). This function +// makes tensors which have zero stride contiguous, by setting the +// strides to 1 as cuDNN likes. +inline Tensor contiguousIfZeroInStrides(const Tensor& t) { + for (auto s : t.strides()) { + if (s == 0) + return t.contiguous(); + } + return t; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/cudnn/cudnn-wrapper.h b/western_ai/usa/pytorch/aten/src/ATen/cudnn/cudnn-wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..3bfceed839d414e01190bb9276170393b9f00e9c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/cudnn/cudnn-wrapper.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +#define STRINGIFY(x) #x +#define STRING(x) STRINGIFY(x) + +#if CUDNN_MAJOR < 8 || (CUDNN_MAJOR == 8 && CUDNN_MINOR < 5) +#pragma message("CuDNN v" STRING( \ + CUDNN_MAJOR) " found, but need at least CuDNN v8. You can get the latest version of CuDNN from https://developer.nvidia.com/cudnn or disable CuDNN with USE_CUDNN=0") +#pragma message "We strongly encourage you to move to 8.5 and above." +#pragma message "This message is intended to annoy you enough to update." +#endif + +#undef STRINGIFY +#undef STRING diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/AcceleratorHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/AcceleratorHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..6232222bf66da9c38bff011b37406b12331e1e5e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/AcceleratorHooksInterface.h @@ -0,0 +1,96 @@ +#pragma once + +#include + +#include +#include +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter") + +namespace at { + +// AcceleratorHooksInterface is a shared interface provided by all +// accelerators to allow generic code. +// This interface is hook-based as it corresponds to all the functions +// that are going to be called in a generic way from the CPU code. + +struct TORCH_API AcceleratorHooksInterface { + // This should never actually be implemented, but it is used to + // squelch -Werror=non-virtual-dtor + virtual ~AcceleratorHooksInterface() = default; + + // Whether this backend was enabled at compilation time. + // This function should NEVER throw. + virtual bool isBuilt() const { + return false; + } + + // Whether this backend can be used at runtime, meaning it was built, + // its runtime dependencies are available (driver) and at least one + // supported device can be used. + // This function should NEVER throw. This function should NOT initialize the context + // on any device (result of hasPrimaryContext below should not change). + // While it is acceptable for this function to poison fork, it is + // recommended to avoid doing so whenever possible. + virtual bool isAvailable() const { + return false; + } + + // Whether the device at device_index is fully initialized or not. + virtual bool hasPrimaryContext(DeviceIndex device_index) const = 0; + + virtual void init() const { + TORCH_CHECK(false, "Backend doesn`t support init()"); + } + + virtual DeviceIndex deviceCount() const { + return 0; + } + + virtual void setCurrentDevice(DeviceIndex device) const { + TORCH_CHECK(false, "Backend doesn't support setCurrentDevice()"); + } + + virtual DeviceIndex getCurrentDevice() const { + TORCH_CHECK(false, "Backend doesn't support getCurrentDevice()"); + return -1; + } + + virtual DeviceIndex exchangeDevice(DeviceIndex device) const { + TORCH_CHECK(false, "Backend doesn't support exchangeDevice()"); + return -1; + } + + virtual DeviceIndex maybeExchangeDevice(DeviceIndex device) const { + TORCH_CHECK(false, "Backend doesn't support maybeExchangeDevice()"); + return -1; + } + + virtual bool isPinnedPtr(const void* data) const { + return false; + } + + virtual Allocator* getPinnedMemoryAllocator() const { + TORCH_CHECK(false, "Backend doesn't support getPinnedMemoryAllocator()"); + return nullptr; + } + + virtual Device getDeviceFromPtr(void* data) const { + TORCH_CHECK(false, "Backend doesn't support getDeviceFromPtr()"); + } + + virtual const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const { + TORCH_CHECK(false, "Backend doesn`t support getDefaultGenerator()"); + } + + virtual Generator getNewGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const { + TORCH_CHECK(false, "Backend doesn`t support getNewGenerator()"); + } +}; + +} // namespace at + +C10_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/CPUGuardImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/CPUGuardImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac1da2c537625dda0a9e6016424e97c58eb55acb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/CPUGuardImpl.cpp @@ -0,0 +1,7 @@ +#include + +namespace at::detail { + +C10_REGISTER_GUARD_IMPL(CPU, c10::impl::NoOpDeviceGuardImpl) + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/CUDAHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/CUDAHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..11628fcc86a835453a28a3bf85e392302c45fefb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/CUDAHooksInterface.cpp @@ -0,0 +1,46 @@ +#include + +namespace at { +namespace detail { + +// NB: We purposely leak the CUDA hooks object. This is because under some +// situations, we may need to reference the CUDA hooks while running destructors +// of objects which were constructed *prior* to the first invocation of +// getCUDAHooks. The example which precipitated this change was the fused +// kernel cache in the JIT. The kernel cache is a global variable which caches +// both CPU and CUDA kernels; CUDA kernels must interact with CUDA hooks on +// destruction. Because the kernel cache handles CPU kernels too, it can be +// constructed before we initialize CUDA; if it contains CUDA kernels at program +// destruction time, you will destruct the CUDA kernels after CUDA hooks has +// been unloaded. In principle, we could have also fixed the kernel cache store +// CUDA kernels in a separate global variable, but this solution is much +// simpler. +// +// CUDAHooks doesn't actually contain any data, so leaking it is very benign; +// you're probably losing only a word (the vptr in the allocated object.) + +const CUDAHooksInterface& getCUDAHooks() { + auto create_impl = [] { +#if !defined C10_MOBILE + auto hooks = CUDAHooksRegistry()->Create("CUDAHooks", CUDAHooksArgs{}); + if (hooks) { + return hooks; + } +#endif + return std::make_unique(); + }; + // NB: The static initialization here implies that if you try to call any CUDA + // functionality before libATen_cuda.so is loaded, CUDA is permanently + // disabled for that copy of ATen. In principle, we can relax this + // restriction, but you might have to fix some code. See getVariableHooks() + // for an example where we relax this restriction (but if you try to avoid + // needing a lock, be careful; it doesn't look like Registry.h is thread + // safe...) + static auto hooks = create_impl(); + return *hooks; +} +} // namespace detail + +C10_DEFINE_REGISTRY(CUDAHooksRegistry, CUDAHooksInterface, CUDAHooksArgs) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/CUDAHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/CUDAHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..ec88b40180d4f530af7dcbd007d0b91f216bf134 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/CUDAHooksInterface.h @@ -0,0 +1,258 @@ +#pragma once + +#include +#include +#include + +#include + +// NB: Class must live in `at` due to limitations of Registry.h. +namespace at { + +// Forward-declares at::cuda::NVRTC +namespace cuda { +struct NVRTC; +} // namespace cuda + +#ifdef _MSC_VER +constexpr const char* CUDA_HELP = + "PyTorch splits its backend into two shared libraries: a CPU library " + "and a CUDA library; this error has occurred because you are trying " + "to use some CUDA functionality, but the CUDA library has not been " + "loaded by the dynamic linker for some reason. The CUDA library MUST " + "be loaded, EVEN IF you don't directly use any symbols from the CUDA library! " + "One common culprit is a lack of -INCLUDE:?warp_size@cuda@at@@YAHXZ " + "in your link arguments; many dynamic linkers will delete dynamic library " + "dependencies if you don't depend on any of their symbols. You can check " + "if this has occurred by using link on your binary to see if there is a " + "dependency on *_cuda.dll library."; +#else +constexpr const char* CUDA_HELP = + "PyTorch splits its backend into two shared libraries: a CPU library " + "and a CUDA library; this error has occurred because you are trying " + "to use some CUDA functionality, but the CUDA library has not been " + "loaded by the dynamic linker for some reason. The CUDA library MUST " + "be loaded, EVEN IF you don't directly use any symbols from the CUDA library! " + "One common culprit is a lack of -Wl,--no-as-needed in your link arguments; many " + "dynamic linkers will delete dynamic library dependencies if you don't " + "depend on any of their symbols. You can check if this has occurred by " + "using ldd on your binary to see if there is a dependency on *_cuda.so " + "library."; +#endif + +// The CUDAHooksInterface is an omnibus interface for any CUDA functionality +// which we may want to call into from CPU code (and thus must be dynamically +// dispatched, to allow for separate compilation of CUDA code). How do I +// decide if a function should live in this class? There are two tests: +// +// 1. Does the *implementation* of this function require linking against +// CUDA libraries? +// +// 2. Is this function *called* from non-CUDA ATen code? +// +// (2) should filter out many ostensible use-cases, since many times a CUDA +// function provided by ATen is only really ever used by actual CUDA code. +// +// TODO: Consider putting the stub definitions in another class, so that one +// never forgets to implement each virtual function in the real implementation +// in CUDAHooks. This probably doesn't buy us much though. +struct TORCH_API CUDAHooksInterface : AcceleratorHooksInterface { + // This should never actually be implemented, but it is used to + // squelch -Werror=non-virtual-dtor + ~CUDAHooksInterface() override = default; + + // Initialize THCState and, transitively, the CUDA state + void init() const override { + TORCH_CHECK(false, "Cannot initialize CUDA without ATen_cuda library. ", CUDA_HELP); + } + + const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK( + false, + "Cannot get default CUDA generator without ATen_cuda library. ", + CUDA_HELP); + } + + Generator getNewGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK( + false, + "Cannot get CUDA generator without ATen_cuda library. ", + CUDA_HELP); + } + + Device getDeviceFromPtr(void* /*data*/) const override { + TORCH_CHECK(false, "Cannot get device of pointer on CUDA without ATen_cuda library. ", CUDA_HELP); + } + + bool isPinnedPtr(const void* /*data*/) const override { + return false; + } + + virtual bool hasCUDA() const { + return false; + } + + virtual bool hasCUDART() const { + return false; + } + + virtual bool hasMAGMA() const { + return false; + } + + virtual bool hasCuDNN() const { + return false; + } + + virtual bool hasCuSOLVER() const { + return false; + } + + virtual bool hasCuBLASLt() const { + return false; + } + + virtual bool hasROCM() const { + return false; + } + + virtual bool hasCKSDPA() const { + return false; + } + + virtual bool hasCKGEMM() const { + return false; + } + + virtual const at::cuda::NVRTC& nvrtc() const { + TORCH_CHECK(false, "NVRTC requires CUDA. ", CUDA_HELP); + } + + bool hasPrimaryContext(DeviceIndex device_index) const override { + TORCH_CHECK(false, "Cannot call hasPrimaryContext(", device_index, ") without ATen_cuda library. ", CUDA_HELP); + } + + virtual DeviceIndex current_device() const { + return -1; + } + + Allocator* getPinnedMemoryAllocator() const override { + TORCH_CHECK(false, "Pinned memory requires CUDA. ", CUDA_HELP); + } + + virtual Allocator* getCUDADeviceAllocator() const { + TORCH_CHECK(false, "CUDADeviceAllocator requires CUDA. ", CUDA_HELP); + } + + virtual bool compiledWithCuDNN() const { + return false; + } + + virtual bool compiledWithMIOpen() const { + return false; + } + + virtual bool supportsDilatedConvolutionWithCuDNN() const { + return false; + } + + virtual bool supportsDepthwiseConvolutionWithCuDNN() const { + return false; + } + + virtual bool supportsBFloat16ConvolutionWithCuDNNv8() const { + return false; + } + + virtual bool supportsBFloat16RNNWithCuDNN() const { + return false; + } + + virtual long versionCuDNN() const { + TORCH_CHECK(false, "Cannot query cuDNN version without ATen_cuda library. ", CUDA_HELP); + } + + virtual long versionRuntimeCuDNN() const { + TORCH_CHECK(false, "Cannot query cuDNN version without ATen_cuda library. ", CUDA_HELP); + } + + virtual long versionCuDNNFrontend() const { + TORCH_CHECK(false, "Cannot query cuDNN Frontend version without ATen_cuda library. ", CUDA_HELP); + } + + virtual long versionMIOpen() const { + TORCH_CHECK(false, "Cannot query MIOpen version without ATen_cuda library. ", CUDA_HELP); + } + + virtual long versionHipBLASLt() const { + TORCH_CHECK(false, "Cannot query HipBLASLt version without ATen_cuda library. ", CUDA_HELP); + } + + virtual long versionCUDART() const { + TORCH_CHECK(false, "Cannot query CUDART version without ATen_cuda library. ", CUDA_HELP); + } + + virtual std::string showConfig() const { + TORCH_CHECK(false, "Cannot query detailed CUDA version without ATen_cuda library. ", CUDA_HELP); + } + + virtual double batchnormMinEpsilonCuDNN() const { + TORCH_CHECK(false, + "Cannot query batchnormMinEpsilonCuDNN() without ATen_cuda library. ", CUDA_HELP); + } + + virtual int64_t cuFFTGetPlanCacheMaxSize(DeviceIndex /*device_index*/) const { + TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP); + } + + virtual void cuFFTSetPlanCacheMaxSize(DeviceIndex /*device_index*/, int64_t /*max_size*/) const { + TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP); + } + + virtual int64_t cuFFTGetPlanCacheSize(DeviceIndex /*device_index*/) const { + TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP); + } + + virtual void cuFFTClearPlanCache(DeviceIndex /*device_index*/) const { + TORCH_CHECK(false, "Cannot access cuFFT plan cache without ATen_cuda library. ", CUDA_HELP); + } + + virtual int getNumGPUs() const { + return 0; + } + +#ifdef USE_ROCM + virtual bool isGPUArch(const std::vector& /*archs*/, DeviceIndex = -1 /*device_index*/) const { + TORCH_CHECK(false, "Cannot check GPU arch without ATen_cuda library. ", CUDA_HELP); + } + + virtual const std::vector& getHipblasltPreferredArchs() const { + static const std::vector empty; + TORCH_CHECK(false, "Cannot get hipBLASLt preferred archs without ATen_cuda library. ", CUDA_HELP); + return empty; + } + + virtual const std::vector& getHipblasltSupportedArchs() const { + static const std::vector empty; + TORCH_CHECK(false, "Cannot get hipBLASLt supported archs without ATen_cuda library. ", CUDA_HELP); + return empty; + } +#endif + + virtual void deviceSynchronize(DeviceIndex /*device_index*/) const { + TORCH_CHECK(false, "Cannot synchronize CUDA device without ATen_cuda library. ", CUDA_HELP); + } +}; + +struct TORCH_API CUDAHooksArgs {}; + +TORCH_DECLARE_REGISTRY(CUDAHooksRegistry, CUDAHooksInterface, CUDAHooksArgs); +#define REGISTER_CUDA_HOOKS(clsname) \ + C10_REGISTER_CLASS(CUDAHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const CUDAHooksInterface& getCUDAHooks(); +} // namespace detail +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/FunctionTraits.h b/western_ai/usa/pytorch/aten/src/ATen/detail/FunctionTraits.h new file mode 100644 index 0000000000000000000000000000000000000000..cdc1da3339d1fb158746e531597831e530c41b5a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/FunctionTraits.h @@ -0,0 +1,103 @@ +#pragma once + +#include +#include + +// Modified from https://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda + +// Fallback, anything with an operator() +template +struct function_traits : public function_traits { +}; + +// Pointers to class members that are themselves functors. +// For example, in the following code: +// template +// struct S { +// func_t f; +// }; +// template +// S make_s(func_t f) { +// return S { .f = f }; +// } +// +// auto s = make_s([] (int, float) -> double { /* ... */ }); +// +// function_traits traits; +template +struct function_traits : public function_traits { +}; + +// Const class member functions +template +struct function_traits : public function_traits { +}; + +// Reference types +template +struct function_traits : public function_traits {}; +template +struct function_traits : public function_traits {}; + +// Free functions +template +struct function_traits { + // arity is the number of arguments. + enum { arity = sizeof...(Args) }; + + using ArgsTuple = std::tuple; + using result_type = ReturnType; + + template + struct arg + { + using type = std::tuple_element_t>; + // the i-th argument is equivalent to the i-th tuple element of a tuple + // composed of those arguments. + }; +}; + +template +struct nullary_function_traits { + using traits = function_traits; + using result_type = typename traits::result_type; +}; + +template +struct unary_function_traits { + using traits = function_traits; + using result_type = typename traits::result_type; + using arg1_t = typename traits::template arg<0>::type; +}; + +template +struct binary_function_traits { + using traits = function_traits; + using result_type = typename traits::result_type; + using arg1_t = typename traits::template arg<0>::type; + using arg2_t = typename traits::template arg<1>::type; +}; + + +// Traits for calling with c10::guts::invoke, where member_functions have a first argument of ClassType +template +struct invoke_traits : public function_traits{ +}; + +template +struct invoke_traits : public invoke_traits{ +}; + +template +struct invoke_traits : public invoke_traits{ +}; + +template +struct invoke_traits : + public function_traits { +}; + +template +struct invoke_traits : + public function_traits { +}; diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/HIPHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/HIPHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..adc2be412622ef3edfbfb5eadf42d4e8ab7e3d2b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/HIPHooksInterface.cpp @@ -0,0 +1,24 @@ +#include + +namespace at { +namespace detail { + +// See getCUDAHooks for some more commentary +const HIPHooksInterface& getHIPHooks() { + auto create_impl = [] { +#if !defined C10_MOBILE + auto hooks = HIPHooksRegistry()->Create("HIPHooks", HIPHooksArgs{}); + if (hooks) { + return hooks; + } +#endif + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} +} // namespace detail + +C10_DEFINE_REGISTRY(HIPHooksRegistry, HIPHooksInterface, HIPHooksArgs) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/HIPHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/HIPHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..ae3c683975570bde30f3ff63360f88d6f5a3eef7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/HIPHooksInterface.h @@ -0,0 +1,65 @@ +#pragma once + +#include +#include +#include + +#include + +// NB: Class must live in `at` due to limitations of Registry.h. +namespace at { + +// The HIPHooksInterface is an omnibus interface for any HIP functionality +// which we may want to call into from CPU code (and thus must be dynamically +// dispatched, to allow for separate compilation of HIP code). See +// CUDAHooksInterface for more detailed motivation. +struct TORCH_API HIPHooksInterface : AcceleratorHooksInterface { + // This should never actually be implemented, but it is used to + // squelch -Werror=non-virtual-dtor + ~HIPHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize HIP without ATen_hip library."); + } + + const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK(false, "Cannot initialize HIP without ATen_hip library."); + } + + virtual bool hasHIP() const { + return false; + } + + virtual c10::DeviceIndex current_device() const { + return -1; + } + + bool isPinnedPtr(const void* /*data*/ ) const override { + return false; + } + + Allocator* getPinnedMemoryAllocator() const override { + TORCH_CHECK(false, "Pinned memory requires HIP."); + } + + virtual int getNumGPUs() const { + return 0; + } + + bool hasPrimaryContext(DeviceIndex /*device_index*/ ) const override { + TORCH_CHECK(false, "Cannot check primary context without ATen_hip library."); + } +}; + +struct TORCH_API HIPHooksArgs {}; + +TORCH_DECLARE_REGISTRY(HIPHooksRegistry, HIPHooksInterface, HIPHooksArgs); +#define REGISTER_HIP_HOOKS(clsname) \ + C10_REGISTER_CLASS(HIPHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const HIPHooksInterface& getHIPHooks(); + +} // namespace detail +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/HPUHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/HPUHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a4bb294286cd045da2a0bb6cc089c4a645dff09 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/HPUHooksInterface.cpp @@ -0,0 +1,22 @@ +#include + +namespace at { +namespace detail { + +TORCH_API const at::HPUHooksInterface& getHPUHooks() { + auto create_impl = [] { + auto hooks = HPUHooksRegistry()->Create("HPUHooks", HPUHooksArgs{}); + if (hooks) { + return hooks; + } + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} + +} // namespace detail + +C10_DEFINE_REGISTRY(HPUHooksRegistry, HPUHooksInterface, HPUHooksArgs) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/HPUHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/HPUHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..4f81eac04bfe1e1dca73ddd6b59467a0bebd657d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/HPUHooksInterface.h @@ -0,0 +1,57 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace at { + +struct TORCH_API HPUHooksInterface : AcceleratorHooksInterface { + ~HPUHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize HPU without HPU backend"); + } + + virtual bool hasHPU() const { + return false; + } + + Device getDeviceFromPtr(void* /*data*/) const override { + TORCH_CHECK( + false, "Cannot get device of pointer on HPU without HPU backend"); + } + + bool isPinnedPtr(const void* /*data*/) const override { + return false; + } + + Allocator* getPinnedMemoryAllocator() const override { + TORCH_CHECK( + false, + "You should register `HPUHooksInterface` for HPU before call `getPinnedMemoryAllocator`."); + } + + bool hasPrimaryContext( + [[maybe_unused]] DeviceIndex device_index) const override { + TORCH_CHECK( + false, + "You should register `HPUHooksInterface` for HPU before call `hasPrimaryContext`."); + } +}; + +struct TORCH_API HPUHooksArgs {}; + +TORCH_DECLARE_REGISTRY(HPUHooksRegistry, HPUHooksInterface, HPUHooksArgs); +#define REGISTER_HPU_HOOKS(clsname) \ + C10_REGISTER_CLASS(HPUHooksRegistry, clsname, clsname) + +namespace detail { + +TORCH_API const at::HPUHooksInterface& getHPUHooks(); + +} // namespace detail +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/IPUHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/IPUHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a4ca87ead2a477437c24a074a56e09271894f77 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/IPUHooksInterface.cpp @@ -0,0 +1,22 @@ +#include + +namespace at { +namespace detail { + +const IPUHooksInterface& getIPUHooks() { + auto create_impl = [] { + auto hooks = IPUHooksRegistry()->Create("IPUHooks"); + if (hooks) { + return hooks; + } + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} + +} // namespace detail + +C10_DEFINE_REGISTRY(IPUHooksRegistry, IPUHooksInterface) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/IPUHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/IPUHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..69f5c9ff8ec26a8c31a1753718d9364492378344 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/IPUHooksInterface.h @@ -0,0 +1,44 @@ +#pragma once + +#include + +#include +#include +#include + +namespace at { + +struct TORCH_API IPUHooksInterface : AcceleratorHooksInterface { + ~IPUHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library."); + } + + bool hasPrimaryContext(DeviceIndex /*device_index*/) const override { + TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library."); + return false; + } + + const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library."); + } + + Generator getNewGenerator( + DeviceIndex /*device_index*/ = -1) const override { + TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library."); + } +}; + +// Deprecated: no longer used internally, kept for ABI compatibility. +struct TORCH_API IPUHooksArgs {}; + +TORCH_DECLARE_REGISTRY(IPUHooksRegistry, IPUHooksInterface); +#define REGISTER_IPU_HOOKS(clsname) \ + C10_REGISTER_CLASS(IPUHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const IPUHooksInterface& getIPUHooks(); +} // namespace detail +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MAIAHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/MAIAHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d5f322886dc33af6bc8594036a7350a90263faef --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MAIAHooksInterface.cpp @@ -0,0 +1,23 @@ +#include + +namespace at { +namespace detail { + +// See getCUDAHooks for some more commentary +const MAIAHooksInterface& getMAIAHooks() { + auto create_impl = [] { + auto hooks = MAIAHooksRegistry()->Create("MAIAHooks"); + if (hooks) { + return hooks; + } + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} +} // namespace detail + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +C10_DEFINE_REGISTRY(MAIAHooksRegistry, MAIAHooksInterface) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MAIAHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/MAIAHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..7bab6fe05bd31a9b2b9c481a80846c141c8c2afa --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MAIAHooksInterface.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +#include + +// NB: Class must live in `at` due to limitations of Registry.h. +namespace at { + +struct TORCH_API MAIAHooksInterface : AcceleratorHooksInterface { + // This should never actually be implemented, but it is used to + // squelch -Werror=non-virtual-dtor + ~MAIAHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize MAIA without ATen_maia library."); + } + + bool hasPrimaryContext(DeviceIndex /*device_index*/) const override { + TORCH_CHECK(false, "Cannot initialize MAIA without ATen_maia library."); + return false; + } + + virtual std::string showConfig() const { + TORCH_CHECK(false, "Cannot query detailed MAIA version information."); + } +}; + +// Deprecated: no longer used internally, kept for ABI compatibility. +struct TORCH_API MAIAHooksArgs {}; + +TORCH_DECLARE_REGISTRY(MAIAHooksRegistry, MAIAHooksInterface); +#define REGISTER_MAIA_HOOKS(clsname) \ + C10_REGISTER_CLASS(MAIAHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const MAIAHooksInterface& getMAIAHooks(); +} // namespace detail + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MPSHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/MPSHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2315c16a9b0017a6b0852f280fd66ff8c1218241 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MPSHooksInterface.cpp @@ -0,0 +1,25 @@ +// Copyright © 2022 Apple Inc. + +#include + +namespace at { +namespace detail { + +const MPSHooksInterface& getMPSHooks() { + auto create_impl = [] { +#if !defined C10_MOBILE + auto hooks = MPSHooksRegistry()->Create("MPSHooks"); + if (hooks) { + return hooks; + } +#endif + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} +} // namespace detail + +C10_DEFINE_REGISTRY(MPSHooksRegistry, MPSHooksInterface) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MPSHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/MPSHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..234ef5fa8946c9e43069f50409aaf2ca25779f83 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MPSHooksInterface.h @@ -0,0 +1,129 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#include + +#include +#include +#include + +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter") +namespace at { + +struct TORCH_API MPSHooksInterface : AcceleratorHooksInterface { + // this fails the implementation if MPSHooks functions are called, but + // MPS backend is not present. + #define FAIL_MPSHOOKS_FUNC(func) \ + TORCH_CHECK(false, "Cannot execute ", func, "() without MPS backend."); + + ~MPSHooksInterface() override = default; + + // Initialize the MPS library state + void init() const override { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual bool hasMPS() const { + return false; + } + virtual bool isOnMacOSorNewer(unsigned major = 13, unsigned minor = 0) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + FAIL_MPSHOOKS_FUNC(__func__); + } + Generator getNewGenerator( + [[maybe_unused]] DeviceIndex device_index) const override { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual Allocator* getMPSDeviceAllocator() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void deviceSynchronize() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void commitStream() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void* getCommandBuffer() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void* getDispatchQueue() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void emptyCache() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual size_t getCurrentAllocatedMemory() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual size_t getDriverAllocatedMemory() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual size_t getRecommendedMaxMemory() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual size_t getMaxBufferLength() const { + return 0; + } + virtual void setMemoryFraction(double /*ratio*/) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void profilerStartTrace(const std::string& mode, bool waitUntilCompleted) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void profilerStopTrace() const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual uint32_t acquireEvent(bool enable_timing) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + Device getDeviceFromPtr(void* data) const override { + TORCH_CHECK(false, "Cannot get device of pointer on MPS without ATen_mps library. "); + } + virtual void releaseEvent(uint32_t event_id) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void recordEvent(uint32_t event_id) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void waitForEvent(uint32_t event_id) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual void synchronizeEvent(uint32_t event_id) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual bool queryEvent(uint32_t event_id) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + virtual double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id) const { + FAIL_MPSHOOKS_FUNC(__func__); + } + bool hasPrimaryContext(DeviceIndex device_index) const override { + FAIL_MPSHOOKS_FUNC(__func__); + } + bool isPinnedPtr(const void* data) const override { + return false; + } + Allocator* getPinnedMemoryAllocator() const override { + FAIL_MPSHOOKS_FUNC(__func__); + } + #undef FAIL_MPSHOOKS_FUNC +}; + +// Deprecated: no longer used internally, kept for ABI compatibility. +struct TORCH_API MPSHooksArgs {}; + +TORCH_DECLARE_REGISTRY(MPSHooksRegistry, MPSHooksInterface); +#define REGISTER_MPS_HOOKS(clsname) \ + C10_REGISTER_CLASS(MPSHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const MPSHooksInterface& getMPSHooks(); + +} // namespace detail +} // namespace at +C10_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MTIAHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/MTIAHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1932952ca13518f80b80c8ba35b80e3f5a6ee00 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MTIAHooksInterface.cpp @@ -0,0 +1,30 @@ +#include + +namespace at { +namespace detail { + +const MTIAHooksInterface& getMTIAHooks() { + auto create_impl = [] { + auto hooks = MTIAHooksRegistry()->Create("MTIAHooks"); + if (hooks) { + return hooks; + } + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} + +bool isMTIAHooksBuilt() { + return MTIAHooksRegistry()->Has("MTIAHooks"); +} + +} // namespace detail + +bool MTIAHooksInterface::isAvailable() const { + return detail::isMTIAHooksBuilt() && detail::getMTIAHooks().deviceCount() > 0; +} + +C10_DEFINE_REGISTRY(MTIAHooksRegistry, MTIAHooksInterface) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MTIAHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/MTIAHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..c2abebfe8a8353db165f824028e5c257a3fdc27e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MTIAHooksInterface.h @@ -0,0 +1,214 @@ +#pragma once + +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include +namespace at { +class Context; +} + +namespace at { +constexpr const char* MTIA_HELP = + "The MTIA backend requires MTIA extension for PyTorch;" + "this error has occurred because you are trying " + "to use some MTIA's functionality without MTIA extension included."; + +struct TORCH_API MTIAHooksInterface : AcceleratorHooksInterface { +// this fails the implementation if MTIAHooks functions are called, but +// MTIA backend is not present. +#define FAIL_MTIAHOOKS_FUNC(func) TORCH_CHECK(false, "Cannot execute ", func, "() without MTIA backend."); + + ~MTIAHooksInterface() override = default; + + void init() const override { + // Avoid logging here, since MTIA needs init devices first then it will know + // how many devices are available. Make it as no-op if mtia extension is not + // dynamically loaded. + return; + } + + virtual bool hasMTIA() const { + return false; + } + + DeviceIndex deviceCount() const override { + return 0; + } + + virtual void deviceSynchronize(c10::DeviceIndex /*device_index*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual std::string showConfig() const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + bool hasPrimaryContext(DeviceIndex /*device_index*/) const override { + return false; + } + + void setCurrentDevice(DeviceIndex /*device*/) const override { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + DeviceIndex getCurrentDevice() const override { + FAIL_MTIAHOOKS_FUNC(__func__); + return -1; + } + + DeviceIndex exchangeDevice(DeviceIndex /*device*/) const override { + FAIL_MTIAHOOKS_FUNC(__func__); + return -1; + } + + DeviceIndex maybeExchangeDevice(DeviceIndex /*device*/) const override { + FAIL_MTIAHOOKS_FUNC(__func__); + return -1; + } + + virtual c10::Stream getCurrentStream(DeviceIndex /*device*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return c10::Stream::unpack3(-1, 0, c10::DeviceType::MTIA); + } + + virtual int64_t getCurrentRawStream(DeviceIndex /*device*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return -1; + } + + virtual c10::Stream getDefaultStream(DeviceIndex /*device*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return c10::Stream::unpack3(-1, 0, c10::DeviceType::MTIA); + } + + virtual void setCurrentStream(const c10::Stream& /*stream*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + bool isPinnedPtr(const void* /*data*/) const override { + return false; + } + + Allocator* getPinnedMemoryAllocator() const override { + FAIL_MTIAHOOKS_FUNC(__func__); + return nullptr; + } + + virtual PyObject* memoryStats(DeviceIndex /*device*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return nullptr; + } + + virtual PyObject* getDeviceCapability(DeviceIndex /*device*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return nullptr; + } + + virtual PyObject* getDeviceProperties(DeviceIndex device) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return nullptr; + } + + virtual void emptyCache() const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void recordMemoryHistory(const std::optional& /*enabled*/, + const std::string& /*stacks*/, + size_t /*max_entries*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual PyObject* memorySnapshot(const std::optional& local_path) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return nullptr; + } + + virtual DeviceIndex getDeviceCount() const { + FAIL_MTIAHOOKS_FUNC(__func__); + return 0; + } + + virtual void resetPeakMemoryStats(DeviceIndex /*device*/) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void attachOutOfMemoryObserver(PyObject* observer) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return; + } + + bool isAvailable() const override; + + /* MTIAGraph related APIs */ + virtual int64_t mtiagraphCreate(bool keep_graph = false) const { + FAIL_MTIAHOOKS_FUNC(__func__); + return -1; + } + + virtual void mtiagraphDestroy(int64_t handle) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void mtiagraphCaptureBegin(int64_t handle, MempoolId_t pool) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void mtiagraphCaptureEnd(int64_t handle) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void mtiagraphInstantiate(int64_t handle) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void mtiagraphReplay(int64_t handle) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual void mtiagraphReset(int64_t handle) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual MempoolId_t mtiagraphPool(int64_t handle) const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + virtual MempoolId_t graphPoolHandle() const { + FAIL_MTIAHOOKS_FUNC(__func__); + } + + const Generator& getDefaultGenerator(DeviceIndex /*device_index*/) const override { + FAIL_MTIAHOOKS_FUNC(__func__); + static Generator dummy_generator; + return dummy_generator; + } + + Generator getNewGenerator(DeviceIndex /*device_index*/) const override { + FAIL_MTIAHOOKS_FUNC(__func__); + static Generator dummy_generator; + return dummy_generator; + } +}; + +// Deprecated: no longer used internally, kept for ABI compatibility. +struct TORCH_API MTIAHooksArgs {}; + +TORCH_DECLARE_REGISTRY(MTIAHooksRegistry, MTIAHooksInterface); +#define REGISTER_MTIA_HOOKS(clsname) C10_REGISTER_CLASS(MTIAHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const MTIAHooksInterface& getMTIAHooks(); +TORCH_API bool isMTIAHooksBuilt(); +} // namespace detail +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/MetaGuardImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/MetaGuardImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5ec1f4711889afa4ef09ae81caf9e2edc57ef3f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/MetaGuardImpl.cpp @@ -0,0 +1,8 @@ +#include +#include + +namespace at::detail { + +C10_REGISTER_GUARD_IMPL(Meta, c10::impl::NoOpDeviceGuardImpl) + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/PrivateUse1HooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/PrivateUse1HooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90dad0211f98e46e5baee585bc8e8e1ae1c0b72e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/PrivateUse1HooksInterface.cpp @@ -0,0 +1,29 @@ +#include + +namespace at { + +static PrivateUse1HooksInterface* privateuse1_hooks = nullptr; +static std::mutex _hooks_mutex_lock; + +TORCH_API void RegisterPrivateUse1HooksInterface(at::PrivateUse1HooksInterface* hook_) { + std::lock_guard lock(_hooks_mutex_lock); + TORCH_CHECK(privateuse1_hooks == nullptr, "PrivateUse1HooksInterface only could be registered once."); + privateuse1_hooks = hook_; +} + +TORCH_API bool isPrivateUse1HooksRegistered() { + return privateuse1_hooks != nullptr; +} + +namespace detail { + +TORCH_API const at::PrivateUse1HooksInterface& getPrivateUse1Hooks() { + TORCH_CHECK( + privateuse1_hooks != nullptr, + "Please register PrivateUse1HooksInterface by `RegisterPrivateUse1HooksInterface` first."); + return *privateuse1_hooks; +} + +} // namespace detail + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/PrivateUse1HooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/PrivateUse1HooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..3d4c3e7916ad628b21e67e9e7644200e6f2570c1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/PrivateUse1HooksInterface.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter") + +namespace at { + +struct TORCH_API PrivateUse1HooksInterface : AcceleratorHooksInterface { +#define FAIL_PRIVATEUSE1HOOKS_FUNC(func) \ + TORCH_CHECK_NOT_IMPLEMENTED( \ + false, \ + "You should register `PrivateUse1HooksInterface`", \ + "by `RegisterPrivateUse1HooksInterface` and implement `", \ + func, \ + "` at the same time for PrivateUse1."); + + ~PrivateUse1HooksInterface() override = default; + + bool isBuilt() const override { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + bool isAvailable() const override { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + const at::Generator& getDefaultGenerator( + c10::DeviceIndex device_index) const override { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + Generator getNewGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + // TODO(FFFrog): Preserved for BC and will be removed in the future. + if (at::GetGeneratorPrivate().has_value()) + return at::GetGeneratorForPrivateuse1(device_index); + + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + at::Device getDeviceFromPtr(void* data) const override { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + bool isPinnedPtr(const void* data) const override { + return false; + } + + Allocator* getPinnedMemoryAllocator() const override { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + bool hasPrimaryContext(DeviceIndex device_index) const override { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + + void init() const override {} + virtual void resizePrivateUse1Bytes( + const c10::Storage& storage, + size_t newsize) const { + FAIL_PRIVATEUSE1HOOKS_FUNC(__func__); + } + +#undef FAIL_PRIVATEUSE1HOOKS_FUNC +}; + +struct TORCH_API PrivateUse1HooksArgs {}; + +TORCH_API void RegisterPrivateUse1HooksInterface( + at::PrivateUse1HooksInterface* hook_); + +TORCH_API bool isPrivateUse1HooksRegistered(); + +namespace detail { + +TORCH_API const at::PrivateUse1HooksInterface& getPrivateUse1Hooks(); + +} // namespace detail + +} // namespace at + +C10_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/XLAHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/XLAHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..833db098ab7a97e7f4e9a55b981869ae0340a662 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/XLAHooksInterface.cpp @@ -0,0 +1,23 @@ +#include + +namespace at { +namespace detail { + +const XLAHooksInterface& getXLAHooks() { + auto create_impl = [] { + // Create XLA hooks using the registry + auto hooks = XLAHooksRegistry()->Create("torch_xla::detail::XLAHooks"); + if (hooks) { + return hooks; + } + // If hooks creation fails, fall back to default implementation + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} +} // namespace detail + +C10_DEFINE_REGISTRY(XLAHooksRegistry, XLAHooksInterface) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/XLAHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/XLAHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..4a42a9da7db384912da4e6a040dae0f1bd081841 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/XLAHooksInterface.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include +#include + +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter") + +namespace at { + +constexpr const char* XLA_HELP = + "This error has occurred because you are trying " + "to use some XLA functionality, but the XLA library has not been " + "loaded by the dynamic linker. You must load xla libraries by `import torch_xla`"; + +struct TORCH_API XLAHooksInterface : AcceleratorHooksInterface { + ~XLAHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize XLA without torch_xla library. ", XLA_HELP); + } + + virtual bool hasXLA() const { + return false; + } + + virtual std::string showConfig() const { + TORCH_CHECK( + false, + "Cannot query detailed XLA version without torch_xla library. ", + XLA_HELP); + } + + const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK( + false, "Cannot get default XLA generator without torch_xla library. ", XLA_HELP); + } + + Generator getNewGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK(false, "Cannot get XLA generator without torch_xla library. ", XLA_HELP); + } + + DeviceIndex getCurrentDevice() const override { + TORCH_CHECK(false, "Cannot get current XLA device without torch_xla library. ", XLA_HELP); + } + + Device getDeviceFromPtr(void* /*data*/) const override { + TORCH_CHECK(false, "Cannot get device of pointer on XLA without torch_xla library. ", XLA_HELP); + } + + Allocator* getPinnedMemoryAllocator() const override { + TORCH_CHECK(false, "Cannot get XLA pinned memory allocator without torch_xla library. ", XLA_HELP); + } + + bool isPinnedPtr(const void* data) const override { + return false; + } + + bool hasPrimaryContext(DeviceIndex device_index) const override { + TORCH_CHECK(false, "Cannot query primary context without torch_xla library. ", XLA_HELP); + } + +}; + +// Deprecated: no longer used internally, kept for ABI compatibility. +struct TORCH_API XLAHooksArgs {}; + +TORCH_DECLARE_REGISTRY(XLAHooksRegistry, XLAHooksInterface); +#define REGISTER_XLA_HOOKS(clsname) \ + C10_REGISTER_CLASS(XLAHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const XLAHooksInterface& getXLAHooks(); +} // namespace detail +} // namespace at +C10_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/XPUHooksInterface.cpp b/western_ai/usa/pytorch/aten/src/ATen/detail/XPUHooksInterface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..644c9a955f340eb82785fc7421f5442720d3d2fd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/XPUHooksInterface.cpp @@ -0,0 +1,21 @@ +#include + +namespace at { +namespace detail { + +const XPUHooksInterface& getXPUHooks() { + auto create_impl = [] { + auto hooks = XPUHooksRegistry()->Create("XPUHooks"); + if (hooks) { + return hooks; + } + return std::make_unique(); + }; + static auto hooks = create_impl(); + return *hooks; +} +} // namespace detail + +C10_DEFINE_REGISTRY(XPUHooksRegistry, XPUHooksInterface) + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/detail/XPUHooksInterface.h b/western_ai/usa/pytorch/aten/src/ATen/detail/XPUHooksInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..b59e51efb27b10c1c952ca9fc293ac12858bc9ac --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/detail/XPUHooksInterface.h @@ -0,0 +1,95 @@ +#pragma once + +#include +#include +#include + +#include + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter") + +namespace at { + +namespace xpu { +// Forward-declares at::xpu::LevelZero +struct LevelZero; +} // namespace xpu + + +struct TORCH_API XPUHooksInterface : AcceleratorHooksInterface{ + ~XPUHooksInterface() override = default; + + void init() const override { + TORCH_CHECK(false, "Cannot initialize XPU without ATen_xpu library."); + } + + virtual bool hasXPU() const { + return false; + } + + virtual std::string showConfig() const { + TORCH_CHECK( + false, + "Cannot query detailed XPU version without ATen_xpu library."); + } + + virtual int32_t getGlobalIdxFromDevice(const Device& device) const { + TORCH_CHECK(false, "Cannot get XPU global device index without ATen_xpu library."); + } + + const Generator& getDefaultGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK( + false, "Cannot get default XPU generator without ATen_xpu library."); + } + + Generator getNewGenerator( + [[maybe_unused]] DeviceIndex device_index = -1) const override { + TORCH_CHECK(false, "Cannot get XPU generator without ATen_xpu library."); + } + + virtual DeviceIndex getNumGPUs() const { + return 0; + } + + virtual DeviceIndex current_device() const { + TORCH_CHECK(false, "Cannot get current device on XPU without ATen_xpu library."); + } + + Device getDeviceFromPtr(void* /*data*/) const override { + TORCH_CHECK(false, "Cannot get device of pointer on XPU without ATen_xpu library."); + } + + virtual void deviceSynchronize(DeviceIndex /*device_index*/) const { + TORCH_CHECK(false, "Cannot synchronize XPU device without ATen_xpu library."); + } + + Allocator* getPinnedMemoryAllocator() const override { + TORCH_CHECK(false, "Cannot get XPU pinned memory allocator without ATen_xpu library."); + } + + bool isPinnedPtr(const void* data) const override { + return false; + } + + bool hasPrimaryContext(DeviceIndex device_index) const override { + TORCH_CHECK(false, "Cannot query primary context without ATen_xpu library."); + } + + virtual const at::xpu::LevelZero& level_zero() const { + TORCH_CHECK(false, "Level zero requires XPU."); + } +}; + +// Deprecated: no longer used internally, kept for ABI compatibility. +struct TORCH_API XPUHooksArgs {}; + +TORCH_DECLARE_REGISTRY(XPUHooksRegistry, XPUHooksInterface); +#define REGISTER_XPU_HOOKS(clsname) \ + C10_REGISTER_CLASS(XPUHooksRegistry, clsname, clsname) + +namespace detail { +TORCH_API const XPUHooksInterface& getXPUHooks(); +} // namespace detail +} // namespace at +C10_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/div_rtn.h b/western_ai/usa/pytorch/aten/src/ATen/div_rtn.h new file mode 100644 index 0000000000000000000000000000000000000000..4a6d088b798c2ac96e58107db224a35ba5c9e8c8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/div_rtn.h @@ -0,0 +1,11 @@ +#pragma once + +// Integer division rounding to -Infinity +template +static inline T div_rtn(T x, T y) { + int q = x / y; + int r = x % y; + if ((r != 0) && ((r < 0) != (y < 0))) + --q; + return q; +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/dlpack.h b/western_ai/usa/pytorch/aten/src/ATen/dlpack.h new file mode 100644 index 0000000000000000000000000000000000000000..333faa2b7e238faccc9bef3708854af4f37fa485 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/dlpack.h @@ -0,0 +1,641 @@ +/*! + * Copyright (c) 2017 - by Contributors + * \file dlpack.h + * \brief The common header of DLPack. + */ +#ifndef DLPACK_DLPACK_H_ +#define DLPACK_DLPACK_H_ + +/** + * \brief Compatibility with C++ + */ +#ifdef __cplusplus +#define DLPACK_EXTERN_C extern "C" +#else +#define DLPACK_EXTERN_C +#endif + +/*! \brief The current major version of dlpack */ +#define DLPACK_MAJOR_VERSION 1 + +/*! \brief The current minor version of dlpack */ +#define DLPACK_MINOR_VERSION 3 + +/*! \brief DLPACK_DLL prefix for windows */ +#ifdef _WIN32 +#ifdef DLPACK_EXPORTS +#define DLPACK_DLL __declspec(dllexport) +#else +#define DLPACK_DLL __declspec(dllimport) +#endif +#else +#define DLPACK_DLL +#endif + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + * \brief The DLPack version. + * + * A change in major version indicates that we have changed the + * data layout of the ABI - DLManagedTensorVersioned. + * + * A change in minor version indicates that we have added new + * code, such as a new device type, but the ABI is kept the same. + * + * If an obtained DLPack tensor has a major version that disagrees + * with the version number specified in this header file + * (i.e. major != DLPACK_MAJOR_VERSION), the consumer must call the deleter + * (and it is safe to do so). It is not safe to access any other fields + * as the memory layout will have changed. + * + * In the case of a minor version mismatch, the tensor can be safely used as + * long as the consumer knows how to interpret all fields. Minor version + * updates indicate the addition of enumeration values. + */ +typedef struct { + /*! \brief DLPack major version. */ + uint32_t major; + /*! \brief DLPack minor version. */ + uint32_t minor; +} DLPackVersion; + +/*! + * \brief The device type in DLDevice. + */ +#ifdef __cplusplus +typedef enum : int32_t { +#else +typedef enum { +#endif + /*! \brief CPU device */ + kDLCPU = 1, + /*! \brief CUDA GPU device */ + kDLCUDA = 2, + /*! + * \brief Pinned CUDA CPU memory by cudaMallocHost + */ + kDLCUDAHost = 3, + /*! \brief OpenCL devices. */ + kDLOpenCL = 4, + /*! \brief Vulkan buffer for next generation graphics. */ + kDLVulkan = 7, + /*! \brief Metal for Apple GPU. */ + kDLMetal = 8, + /*! \brief Verilog simulator buffer */ + kDLVPI = 9, + /*! \brief ROCm GPUs for AMD GPUs */ + kDLROCM = 10, + /*! + * \brief Pinned ROCm CPU memory allocated by hipMallocHost + */ + kDLROCMHost = 11, + /*! + * \brief Reserved extension device type, + * used for quickly test extension device + * The semantics can differ depending on the implementation. + */ + kDLExtDev = 12, + /*! + * \brief CUDA managed/unified memory allocated by cudaMallocManaged + */ + kDLCUDAManaged = 13, + /*! + * \brief Unified shared memory allocated on a oneAPI non-partititioned + * device. Call to oneAPI runtime is required to determine the device + * type, the USM allocation type and the sycl context it is bound to. + * + */ + kDLOneAPI = 14, + /*! \brief GPU support for next generation WebGPU standard. */ + kDLWebGPU = 15, + /*! \brief Qualcomm Hexagon DSP */ + kDLHexagon = 16, + /*! \brief Microsoft MAIA devices */ + kDLMAIA = 17, + /*! \brief AWS Trainium */ + kDLTrn = 18, +} DLDeviceType; + +/*! + * \brief A Device for Tensor and operator. + */ +typedef struct { + /*! \brief The device type used in the device. */ + DLDeviceType device_type; + /*! + * \brief The device index. + * For vanilla CPU memory, pinned memory, or managed memory, this is set to 0. + */ + int32_t device_id; +} DLDevice; + +/*! + * \brief The type code options DLDataType. + */ +typedef enum { + /*! \brief signed integer */ + kDLInt = 0U, + /*! \brief unsigned integer */ + kDLUInt = 1U, + /*! \brief IEEE floating point */ + kDLFloat = 2U, + /*! + * \brief Opaque handle type, reserved for testing purposes. + * Frameworks need to agree on the handle data type for the exchange to be well-defined. + */ + kDLOpaqueHandle = 3U, + /*! \brief bfloat16 */ + kDLBfloat = 4U, + /*! + * \brief complex number + * (C/C++/Python layout: compact struct per complex number) + */ + kDLComplex = 5U, + /*! \brief boolean */ + kDLBool = 6U, + /*! \brief FP8 data types */ + kDLFloat8_e3m4 = 7U, + kDLFloat8_e4m3 = 8U, + kDLFloat8_e4m3b11fnuz = 9U, + kDLFloat8_e4m3fn = 10U, + kDLFloat8_e4m3fnuz = 11U, + kDLFloat8_e5m2 = 12U, + kDLFloat8_e5m2fnuz = 13U, + kDLFloat8_e8m0fnu = 14U, + /*! \brief FP6 data types + * Setting bits != 6 is currently unspecified, and the producer must ensure it is set + * while the consumer must stop importing if the value is unexpected. + */ + kDLFloat6_e2m3fn = 15U, + kDLFloat6_e3m2fn = 16U, + /*! \brief FP4 data types + * Setting bits != 4 is currently unspecified, and the producer must ensure it is set + * while the consumer must stop importing if the value is unexpected. + */ + kDLFloat4_e2m1fn = 17U, +} DLDataTypeCode; + +/*! + * \brief The data type the tensor can hold. The data type is assumed to follow the + * native endian-ness. An explicit error message should be raised when attempting to + * export an array with non-native endianness + * + * Examples + * - float: type_code = 2, bits = 32, lanes = 1 + * - float4(vectorized 4 float): type_code = 2, bits = 32, lanes = 4 + * - int8: type_code = 0, bits = 8, lanes = 1 + * - std::complex: type_code = 5, bits = 64, lanes = 1 + * - bool: type_code = 6, bits = 8, lanes = 1 (as per common array library convention, the underlying storage size of bool is 8 bits) + * - float8_e4m3: type_code = 8, bits = 8, lanes = 1 (packed in memory) + * - float6_e3m2fn: type_code = 16, bits = 6, lanes = 1 (packed in memory) + * - float4_e2m1fn: type_code = 17, bits = 4, lanes = 1 (packed in memory) + * + * When a sub-byte type is packed, DLPack requires the data to be in little bit-endian, i.e., + * for a packed data set D ((D >> (i * bits)) && bit_mask) stores the i-th element. + */ +typedef struct { + /*! + * \brief Type code of base types. + * We keep it uint8_t instead of DLDataTypeCode for minimal memory + * footprint, but the value should be one of DLDataTypeCode enum values. + * */ + uint8_t code; + /*! + * \brief Number of bits, common choices are 8, 16, 32. + */ + uint8_t bits; + /*! \brief Number of lanes in the type, used for vector types. */ + uint16_t lanes; +} DLDataType; + +/*! + * \brief Plain C Tensor object, does not manage memory. + */ +typedef struct { + /*! + * \brief The data pointer points to the allocated data. This will be CUDA + * device pointer or cl_mem handle in OpenCL. It may be opaque on some device + * types. This pointer is always aligned to 256 bytes as in CUDA. The + * `byte_offset` field should be used to point to the beginning of the data. + * + * Note that as of Nov 2021, multiple libraries (CuPy, PyTorch, TensorFlow, + * TVM, perhaps others) do not adhere to this 256 byte alignment requirement + * on CPU/CUDA/ROCm, and always use `byte_offset=0`. This must be fixed + * (after which this note will be updated); at the moment it is recommended + * to not rely on the data pointer being correctly aligned. + * + * For given DLTensor, the size of memory required to store the contents of + * data is calculated as follows: + * + * \code{.c} + * static inline size_t GetDataSize(const DLTensor* t) { + * size_t size = 1; + * for (tvm_index_t i = 0; i < t->ndim; ++i) { + * size *= t->shape[i]; + * } + * size *= (t->dtype.bits * t->dtype.lanes + 7) / 8; + * return size; + * } + * \endcode + * + * Note that if the tensor is of size zero, then the data pointer should be + * set to `NULL`. + */ + void* data; + /*! \brief The device of the tensor */ + DLDevice device; + /*! \brief Number of dimensions */ + int32_t ndim; + /*! \brief The data type of the pointer*/ + DLDataType dtype; + /*! + * \brief The shape of the tensor + * + * When ndim == 0, shape can be set to NULL. + */ + int64_t* shape; + /*! + * \brief strides of the tensor (in number of elements, not bytes), + * can not be NULL if ndim != 0, must points to + * an array of ndim elements that specifies the strides, + * so consumer can always rely on strides[dim] being valid for 0 <= dim < ndim. + * + * When ndim == 0, strides can be set to NULL. + * + * \note Before DLPack v1.2, strides can be NULL to indicate contiguous data. + * This is not allowed in DLPack v1.2 and later. The rationale + * is to simplify the consumer handling. + */ + int64_t* strides; + /*! \brief The offset in bytes to the beginning pointer to data */ + uint64_t byte_offset; +} DLTensor; + +/*! + * \brief C Tensor object, manage memory of DLTensor. This data structure is + * intended to facilitate the borrowing of DLTensor by another framework. It is + * not meant to transfer the tensor. When the borrowing framework doesn't need + * the tensor, it should call the deleter to notify the host that the resource + * is no longer needed. + * + * \note This data structure is used as Legacy DLManagedTensor + * in DLPack exchange and is deprecated after DLPack v0.8 + * Use DLManagedTensorVersioned instead. + * This data structure may get renamed or deleted in future versions. + * + * \sa DLManagedTensorVersioned + */ +typedef struct DLManagedTensor { + /*! \brief DLTensor which is being memory managed */ + DLTensor dl_tensor; + /*! \brief the context of the original host framework of DLManagedTensor in + * which DLManagedTensor is used in the framework. It can also be NULL. + */ + void * manager_ctx; + /*! + * \brief Destructor - this should be called + * to destruct the manager_ctx which backs the DLManagedTensor. It can be + * NULL if there is no way for the caller to provide a reasonable destructor. + * The destructor deletes the argument self as well. + */ + void (*deleter)(struct DLManagedTensor * self); +} DLManagedTensor; + +// bit masks used in the DLManagedTensorVersioned + +/*! \brief bit mask to indicate that the tensor is read only. */ +#define DLPACK_FLAG_BITMASK_READ_ONLY (1UL << 0UL) + +/*! + * \brief bit mask to indicate that the tensor is a copy made by the producer. + * + * If set, the tensor is considered solely owned throughout its lifetime by the + * consumer, until the producer-provided deleter is invoked. + */ +#define DLPACK_FLAG_BITMASK_IS_COPIED (1UL << 1UL) + +/*! + * \brief bit mask to indicate that whether a sub-byte type is packed or padded. + * + * The default for sub-byte types (ex: fp4/fp6) is assumed packed. This flag can + * be set by the producer to signal that a tensor of sub-byte type is padded. + */ +#define DLPACK_FLAG_BITMASK_IS_SUBBYTE_TYPE_PADDED (1UL << 2UL) + +/*! + * \brief A versioned and managed C Tensor object, manage memory of DLTensor. + * + * This data structure is intended to facilitate the borrowing of DLTensor by + * another framework. It is not meant to transfer the tensor. When the borrowing + * framework doesn't need the tensor, it should call the deleter to notify the + * host that the resource is no longer needed. + * + * \note This is the current standard DLPack exchange data structure. + */ +typedef struct DLManagedTensorVersioned { + /*! + * \brief The API and ABI version of the current managed Tensor + */ + DLPackVersion version; + /*! + * \brief the context of the original host framework. + * + * Stores DLManagedTensorVersioned is used in the + * framework. It can also be NULL. + */ + void *manager_ctx; + /*! + * \brief Destructor. + * + * This should be called to destruct manager_ctx which holds the DLManagedTensorVersioned. + * It can be NULL if there is no way for the caller to provide a reasonable + * destructor. The destructor deletes the argument self as well. + */ + void (*deleter)(struct DLManagedTensorVersioned *self); + /*! + * \brief Additional bitmask flags information about the tensor. + * + * By default the flags should be set to 0. + * + * \note Future ABI changes should keep everything until this field + * stable, to ensure that deleter can be correctly called. + * + * \sa DLPACK_FLAG_BITMASK_READ_ONLY + * \sa DLPACK_FLAG_BITMASK_IS_COPIED + */ + uint64_t flags; + /*! \brief DLTensor which is being memory managed */ + DLTensor dl_tensor; +} DLManagedTensorVersioned; + +//---------------------------------------------------------------------- +// DLPack `__dlpack_c_exchange_api__` fast exchange protocol definitions +//---------------------------------------------------------------------- +/*! + * \brief Request a producer library to create a new tensor. + * + * Create a new `DLManagedTensorVersioned` within the context of the producer + * library. The allocation is defined via the prototype DLTensor. + * + * This function is exposed by the framework through the DLPackExchangeAPI. + * + * \param prototype The prototype DLTensor. Only the dtype, ndim, shape, + * and device fields are used. + * \param out The output DLManagedTensorVersioned. + * \param error_ctx Context for `SetError`. + * \param SetError The function to set the error. + * \return The owning DLManagedTensorVersioned* or NULL on failure. + * SetError is called exactly when NULL is returned (the implementer + * must ensure this). + * \note - As a C function, must not thrown C++ exceptions. + * - Error propagation via SetError to avoid any direct need + * of Python API. Due to this `SetError` may have to ensure the GIL is + * held since it will presumably set a Python error. + * + * \sa DLPackExchangeAPI + */ +typedef int (*DLPackManagedTensorAllocator)( // + DLTensor* prototype, DLManagedTensorVersioned** out, void* error_ctx, // + void (*SetError)(void* error_ctx, const char* kind, const char* message) // +); + +/*! + * \brief Exports a PyObject* Tensor/NDArray to a DLManagedTensorVersioned. + * + * This function does not perform any stream synchronization. The consumer should query + * DLPackCurrentWorkStream to get the current work stream and launch kernels on it. + * + * This function is exposed by the framework through the DLPackExchangeAPI. + * + * \param py_object The Python object to convert. Must have the same type + * as the one the `DLPackExchangeAPI` was discovered from. + * \return The owning DLManagedTensorVersioned* or NULL on failure with a + * Python exception set. If the data cannot be described using DLPack + * this should be a BufferError if possible. + * \note - As a C function, must not thrown C++ exceptions. + * + * \sa DLPackExchangeAPI, DLPackCurrentWorkStream + */ +typedef int (*DLPackManagedTensorFromPyObjectNoSync)( // + void* py_object, // + DLManagedTensorVersioned** out // +); + +/*! + * \brief Exports a PyObject* Tensor/NDArray to a provided DLTensor. + * + * This function provides a faster interface for temporary, non-owning, + * exchange. The producer (implementer) still owns the memory of data, strides, + * shape. The liveness of the DLTensor and the data it views is only guaranteed + * until control is returned. + * + * This function currently assumes that the producer (implementer) can fill + * in the DLTensor shape and strides without the need for temporary allocations. + * + * This function does not perform any stream synchronization. The consumer + * should query DLPackCurrentWorkStream to get the current work stream and + * launch kernels on it. + * + * This function is exposed by the framework through the DLPackExchangeAPI. + * + * \param py_object The Python object to convert. Must have the same type + * as the one the `DLPackExchangeAPI` was discovered from. + * \param out The output DLTensor, whose space is pre-allocated on stack. + * \return 0 on success, -1 on failure with a Python exception set. + * \note - As a C function, must not thrown C++ exceptions. + * + * \sa DLPackExchangeAPI, DLPackCurrentWorkStream + */ +typedef int (*DLPackDLTensorFromPyObjectNoSync)( // + void* py_object, // + DLTensor* out // +); + +/*! + * \brief Obtain the current work stream of a device. + * + * Obtain the current work stream of a device from the producer framework. + * For example, it should map to torch.cuda.current_stream in PyTorch. + * + * When device_type is kDLCPU, the consumer do not have to query the stream + * and the producer can simply return NULL when queried. + * The consumer do not have to do anything on stream sync or setting. + * So CPU only framework can just provide a dummy implementation that + * always set out_current_stream[0] to NULL. + * + * \param device_type The device type. + * \param device_id The device id. + * \param out_current_stream The output current work stream. + * + * \return 0 on success, -1 on failure with a Python exception set. + * \note - As a C function, must not thrown C++ exceptions. + * + * \sa DLPackExchangeAPI + */ +typedef int (*DLPackCurrentWorkStream)( // + DLDeviceType device_type, // + int32_t device_id, // + void** out_current_stream // +); + +/*! + * \brief Imports a DLManagedTensorVersioned to a PyObject* Tensor/NDArray. + * + * Convert an owning DLManagedTensorVersioned* to the Python tensor of the + * producer (implementer) library with the correct type. + * + * This function does not perform any stream synchronization. + * + * This function is exposed by the framework through the DLPackExchangeAPI. + * + * \param tensor The DLManagedTensorVersioned to convert the ownership of the + * tensor is stolen. + * \param out_py_object The output Python object. + * \return 0 on success, -1 on failure with a Python exception set. + * + * \sa DLPackExchangeAPI + */ +typedef int (*DLPackManagedTensorToPyObjectNoSync)( // + DLManagedTensorVersioned* tensor, // + void** out_py_object // +); + +/*! + * \brief DLPackExchangeAPI stable header. + * \sa DLPackExchangeAPI + */ +typedef struct DLPackExchangeAPIHeader { + /*! + * \brief The provided DLPack version the consumer must check major version + * compatibility before using this struct. + */ + DLPackVersion version; + /*! + * \brief Optional pointer to an older DLPackExchangeAPI in the chain. + * + * It must be NULL if the framework does not support older versions. + * If the current major version is larger than the one supported by the + * consumer, the consumer may walk this to find an earlier supported version. + * + * \sa DLPackExchangeAPI + */ + struct DLPackExchangeAPIHeader* prev_api; +} DLPackExchangeAPIHeader; + +/*! + * \brief Framework-specific function pointers table for DLPack exchange. + * + * Additionally to `__dlpack__()` we define a C function table sharable by + * + * Python implementations via `__dlpack_c_exchange_api__`. + * This attribute must be set on the type as a Python PyCapsule + * with name "dlpack_exchange_api". + * + * A consumer library may use a pattern such as: + * + * \code + * + * PyObject *api_obj = type(tensor_obj).__dlpack_c_exchange_api__; // as C-code + * MyDLPackExchangeAPI *api = PyCapsule_GetPointer(api_obj, "dlpack_exchange_api"); + * if (api == NULL && PyErr_Occurred()) { goto handle_error; } + * + * \endcode + * + * Note that this must be defined on the type. The consumer should look up the + * attribute on the type and may cache the result for each unique type. + * + * The precise API table is given by: + * \code + * struct MyDLPackExchangeAPI : public DLPackExchangeAPI { + * MyDLPackExchangeAPI() { + * header.version.major = DLPACK_MAJOR_VERSION; + * header.version.minor = DLPACK_MINOR_VERSION; + * header.prev_version_api = nullptr; + * + * managed_tensor_allocator = MyDLPackManagedTensorAllocator; + * managed_tensor_from_py_object_no_sync = MyDLPackManagedTensorFromPyObjectNoSync; + * managed_tensor_to_py_object_no_sync = MyDLPackManagedTensorToPyObjectNoSync; + * dltensor_from_py_object_no_sync = MyDLPackDLTensorFromPyObjectNoSync; + * current_work_stream = MyDLPackCurrentWorkStream; + * } + * + * static const DLPackExchangeAPI* Global() { + * static MyDLPackExchangeAPI inst; + * return &inst; + * } + * }; + * \endcode + * + * Guidelines for leveraging DLPackExchangeAPI: + * + * There are generally two kinds of consumer needs for DLPack exchange: + * - N0: library support, where consumer.kernel(x, y, z) would like to run a kernel + * with the data from x, y, z. The consumer is also expected to run the kernel with the same + * stream context as the producer. For example, when x, y, z is torch.Tensor, + * consumer should query exchange_api->current_work_stream to get the + * current stream and launch the kernel with the same stream. + * This setup is necessary for no synchronization in kernel launch and maximum compatibility + * with CUDA graph capture in the producer. + * This is the desirable behavior for library extension support for frameworks like PyTorch. + * - N1: data ingestion and retention + * + * Note that obj.__dlpack__() API should provide useful ways for N1. + * The primary focus of the current DLPackExchangeAPI is to enable faster exchange N0 + * with the support of the function pointer current_work_stream. + * + * Array/Tensor libraries should statically create and initialize this structure + * then return a pointer to DLPackExchangeAPI as an int value in Tensor/Array. + * The DLPackExchangeAPI* must stay alive throughout the lifetime of the process. + * + * One simple way to do so is to create a static instance of DLPackExchangeAPI + * within the framework and return a pointer to it. The following code + * shows an example to do so in C++. It should also be reasonably easy + * to do so in other languages. + */ +typedef struct DLPackExchangeAPI { + /*! + * \brief The header that remains stable across versions. + */ + DLPackExchangeAPIHeader header; + /*! + * \brief Producer function pointer for DLPackManagedTensorAllocator + * This function must not be NULL. + * \sa DLPackManagedTensorAllocator + */ + DLPackManagedTensorAllocator managed_tensor_allocator; + /*! + * \brief Producer function pointer for DLPackManagedTensorFromPyObject + * This function must be not NULL. + * \sa DLPackManagedTensorFromPyObject + */ + DLPackManagedTensorFromPyObjectNoSync managed_tensor_from_py_object_no_sync; + /*! + * \brief Producer function pointer for DLPackManagedTensorToPyObject + * This function must be not NULL. + * \sa DLPackManagedTensorToPyObject + */ + DLPackManagedTensorToPyObjectNoSync managed_tensor_to_py_object_no_sync; + /*! + * \brief Producer function pointer for DLPackDLTensorFromPyObject + * This function can be NULL when the producer does not support this function. + * \sa DLPackDLTensorFromPyObjectNoSync + */ + DLPackDLTensorFromPyObjectNoSync dltensor_from_py_object_no_sync; + /*! + * \brief Producer function pointer for DLPackCurrentWorkStream + * This function must be not NULL. + * \sa DLPackCurrentWorkStream + */ + DLPackCurrentWorkStream current_work_stream; +} DLPackExchangeAPI; + +#ifdef __cplusplus +} // DLPACK_EXTERN_C +#endif +#endif // DLPACK_DLPACK_H_ diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/ADInterpreters.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/ADInterpreters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..11add31464bd858fba1d3bebb4a280ba28582052 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/ADInterpreters.cpp @@ -0,0 +1,240 @@ +#include +#include +#include +#include + +namespace at::functorch { + +constexpr size_t default_bitset_size = 64; + +static void checkForInvalidMutationOnCaptures( + const c10::OperatorHandle& op, + const torch::jit::Stack* stack, + int64_t cur_level) { + if (!isInplaceOp(op.schema())) { + return; + } + auto args = torch::jit::last(stack, op.schema().arguments().size()); + auto mutated_arg = unwrapIfDead(args[0].toTensor()); + auto* wrapper = maybeGetTensorWrapper(mutated_arg); + if (wrapper && wrapper->level() == cur_level && !(wrapper->is_immutable())) { + return; + } + TORCH_CHECK(false, + "During a grad (vjp, jvp, grad, etc) transform, the function provided ", + "attempted to call in-place operation (", op.schema().operator_name(), ") ", + "that would mutate a captured Tensor. This is not supported; please rewrite ", + "the function being transformed to explicitly accept the mutated Tensor(s) ", + "as inputs."); +} + +static Tensor materializeGradWrappers(const Tensor& tensor, int64_t current_level) { + if (!tensor.defined()) { + return tensor; + } + // TensorWrapper creation may call dispatcher ops (e.g. aten.sym_storage_offset). + // We need to ensure that they pass through the functorch stack properly. + // In order to do that, we want to call those dispatcher ops at the next layer, + // hence we disable DynamicLayerFrontMode so the call to the op automatically + // goes to DynamicLayerBackMode which will then send it to the next layer. + c10::impl::ExcludeDispatchKeyGuard guard(c10::DispatchKey::FuncTorchDynamicLayerFrontMode); + auto* wrapper = maybeGetTensorWrapper(tensor); + if (!wrapper) { + return makeTensorWrapper(tensor, current_level, /*is_immutable=*/true); + } + auto level = wrapper->level(); + TORCH_INTERNAL_ASSERT(level.has_value() && level <= current_level, "escaped?"); + if (level == current_level) { + TORCH_INTERNAL_ASSERT(tensor.defined()); + return tensor; + } + return makeTensorWrapper(tensor, current_level, /*is_immutable=*/true); +} + +Tensor GradInterpreterPtr::lift(const Tensor& tensor) const { + return materializeGradWrappers(tensor, level()); +} + +Tensor JvpInterpreterPtr::lift(const Tensor& tensor) const { + return materializeGradWrappers(tensor, level()); +} + +static void autogradBasedTransformProcess( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + int64_t current_level, + TransformType transform_type) { + // if is a grad transform, and the operation is in-place, and the mutated + // argument is not currently wrapped in a TensorWrapper, then we need to + // error out otherwise the result is silently incorrect + checkForInvalidMutationOnCaptures(op, stack, current_level); + + // materialize live GradWrappers + auto maybeTransformGradWrappers = [&](const Tensor& tensor) { + return materializeGradWrappers(tensor, current_level); + }; + auto num_args = op.schema().arguments().size(); + foreachTensorInplace(*stack, static_cast(stack->size() - num_args), static_cast(stack->size()), maybeTransformGradWrappers); + + setup_dispatch_key_tls(transform_type, {}); + op.callBoxed(stack); +} + +static void autogradBasedTransformSendToNext( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + const Interpreter& interpreter, + TransformType transform_type, + std::optional prev_grad_mode, + std::optional prev_fwd_grad_mode, + bool grad_special_case) { + auto current_level = interpreter.level(); + if (transform_type == TransformType::Grad) { + TORCH_INTERNAL_ASSERT(prev_grad_mode.has_value()); + } + if (transform_type == TransformType::Jvp) { + TORCH_INTERNAL_ASSERT(prev_fwd_grad_mode.has_value()); + } + auto unwrap = [&](const Tensor& tensor) { + if (!tensor.defined()) { + return tensor; + } + auto* maybe_tensor_wrapper = maybeGetTensorWrapper(tensor); + if (!maybe_tensor_wrapper) { + return tensor; + } + auto tensor_wrapper_level = maybe_tensor_wrapper->level().value(); + TORCH_INTERNAL_ASSERT(tensor_wrapper_level <= current_level); + if (tensor_wrapper_level == current_level) { + return maybe_tensor_wrapper->value(); + } + return tensor; + }; + auto wrap = [&](const Tensor& tensor, bool is_immutable) { + if (!tensor.defined()) { + return tensor; + } + return makeTensorWrapper(tensor, interpreter, is_immutable); + }; + + // TODO: we only need to do the following (marked with !) on in-place functions + // that modify sizes or strides. There aren't many of them. + // If autograd dispatch key: + // 1. (!) Put a copy of all of the args onto the stack + // 2. Unwrap all the args in the copy set + // 3. Call the operator + // 4. Wrap the output + // 5. (!) refreshMetadata for all the args in the original set + // 6. (!) Pop those args off. + + // Step 1 & 2 + auto args_size = op.schema().arguments().size(); + const auto ret_size = op.schema().returns().size(); + // Step 1 + auto front = static_cast(stack->size()) - args_size; + for (const auto arg_idx : c10::irange(0, args_size)) { + stack->push_back((*stack)[front + arg_idx]); + } + + std::bitset outputs_aliasing_immutable; // set = 1 for all bits + if(!grad_special_case) { + for (auto idx = stack->size() - args_size; idx < stack->size(); idx++) { + const auto ivalue = (*stack)[idx]; + if (!ivalue.isTensor()) { + continue; // only input that can be aliased is a tensor, not a tensor list (expect in ops without returns) + } + const auto& tensor = ivalue.toTensor(); + auto* maybe_tensor_wrapper = maybeGetTensorWrapper(tensor); + if (!maybe_tensor_wrapper || maybe_tensor_wrapper->is_immutable()) { + // if the input is immutable, we find if it aliases anything, noting that + // args are in reverse order on stack, so the last arg is at the top of the stack + const auto relative_pos = idx - (stack->size() - args_size); + const auto aliased_out = findAliasedOutput(op.schema(), static_cast(relative_pos)); + if (aliased_out.has_value()) { + outputs_aliasing_immutable.flip(*aliased_out); // each output aliases at most one input, so we can only hit this once + } + } + } + } + + // Step 2 + foreachTensorInplace(*stack, static_cast(stack->size() - args_size), static_cast(stack->size()), unwrap); + + // See NOTE [grad and vjp interaction with no_grad] + std::optional grad_guard; + if (transform_type == TransformType::Grad && prev_grad_mode.has_value() && *prev_grad_mode == false) { + grad_guard.emplace(*prev_grad_mode); + } + std::optional fw_grad_guard; + if (transform_type == TransformType::Jvp && + prev_fwd_grad_mode.has_value() && prev_fwd_grad_mode.value() == false) { + fw_grad_guard.emplace(*prev_fwd_grad_mode); + } + + // Re-dispatch + if (getDynamicLayerStack().empty()) { + sanityCheckStack(op, stack); + } + + // Step 4, 5, 6 + + op.callBoxed(stack); + + // Step 4 + foreachTensorInplaceWithFlag(*stack, static_cast(stack->size() - ret_size), static_cast(stack->size()), outputs_aliasing_immutable, wrap); + + // Step 5 + auto args_front = stack->size() - args_size - ret_size; + for (const auto arg_idx : c10::irange(0, args_size)) { + auto& ivalue = (*stack)[args_front + arg_idx]; + if (!ivalue.isTensor()) { + continue; + } + auto maybe_tensor_wrapper = maybeGetTensorWrapper(ivalue.toTensor()); + if (!maybe_tensor_wrapper) { + continue; + } + maybe_tensor_wrapper->refreshMetadata(); + } + + // Step 6 + stack->erase(stack->end() - static_cast(args_size + ret_size), stack->end() - static_cast(ret_size)); +} + +void GradInterpreterPtr::processImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack) { + autogradBasedTransformProcess(op, stack, level(), TransformType::Grad); +} + +void GradInterpreterPtr::sendToNextInterpreterImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + bool grad_special_case) { + autogradBasedTransformSendToNext( + op, stack, *base_, + TransformType::Grad, + prevGradMode(), + std::nullopt, + grad_special_case); +} + +void JvpInterpreterPtr::processImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack) { + autogradBasedTransformProcess(op, stack, level(), TransformType::Jvp); +} + +void JvpInterpreterPtr::sendToNextInterpreterImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + bool grad_special_case) { + autogradBasedTransformSendToNext( + op, stack, *base_, + TransformType::Jvp, + std::nullopt, + prevFwdGradMode(), + grad_special_case); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/ADInterpreters.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/ADInterpreters.h new file mode 100644 index 0000000000000000000000000000000000000000..fc151cedd1b05936922a94df29d771f39884e749 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/ADInterpreters.h @@ -0,0 +1,38 @@ +#pragma once +#include + +namespace at::functorch { + +// These are the interpreters for our AD transforms +// (grad, vjp and jvp). +// See NOTE: [functorch interpreter stack] for more details. + +struct TORCH_API GradInterpreterPtr { + explicit GradInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Grad); } + TransformType key() const { return base_->key(); } + int64_t level() const { return base_->level(); } + void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack); + void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case); + bool prevGradMode() const { + return std::get(base_->meta()).prevGradMode_; + } + Tensor lift(const Tensor& tensor) const; + private: + const Interpreter* base_; +}; + +struct TORCH_API JvpInterpreterPtr { + explicit JvpInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Jvp); } + TransformType key() const { return base_->key(); } + int64_t level() const { return base_->level(); } + void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack); + void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case); + bool prevFwdGradMode() const { + return std::get(base_->meta()).prevFwdGradMode_; + } + Tensor lift(const Tensor& tensor) const; + private: + const Interpreter* base_; +}; + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesActivation.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesActivation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f76cf9176bd5477573fcda4f0bbc054662f3b341 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesActivation.cpp @@ -0,0 +1,54 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include + +// NB: most activation functions fit pointwise unary or binary rules. +// These are only the ones that have special batch rules to help with organization +namespace at::functorch { +static std::tuple> +glu_batch_rule(const Tensor& self, std::optional self_bdim, int64_t dim) { + // repeated error message from glu because 0D -> 1D when batched + // this can't pass anyway because a 0-dimensional tensor has "size" 1, which + // can't be evenly halved, but give a nicer error message here. + TORCH_CHECK(self.dim() > 1, "glu does not support 0-dimensional tensors"); + + const auto rank = rankWithoutBatchDim(self, self_bdim); + const auto dim_ = maybe_wrap_dim(dim, rank) + 1; + + const auto self_ = moveBatchDimToFront(self, self_bdim); + + auto res = at::glu(self_, dim_); + return std::make_tuple(std::move(res), 0); +} + +static std::tuple> glu_backward_batch_rule( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& self, std::optional self_bdim, int64_t dim) { + if (self_bdim) { + // repeated error message from glu because 0D -> 1D when batched + // this can't pass anyway because a 0-dimensional tensor has "size" 1, which + // can't be evenly halved, but give a nicer error message here. + TORCH_CHECK(self.dim() > 1, "glu does not support 0-dimensional tensors"); + } + + const auto rank = rankWithoutBatchDim(self, self_bdim); + const auto dim_ = maybe_wrap_dim(dim, rank) + 1; + + const auto batch_size = get_bdim_size2(grad_output, grad_output_bdim, self, self_bdim); + const auto grad_output_ = ensure_has_bdim(moveBatchDimToFront(grad_output, grad_output_bdim), grad_output_bdim.has_value(), batch_size); + const auto self_ = ensure_has_bdim(moveBatchDimToFront(self, self_bdim), self_bdim.has_value(), batch_size); + + auto res = at::glu_backward(grad_output_, self_, dim_); + return std::make_tuple(std::move(res), 0); +} + + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT(glu_backward, glu_backward_batch_rule); + VMAP_SUPPORT(glu, glu_batch_rule); +} +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesBinaryOps.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesBinaryOps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..424869dd2b96dde92d37dfecc6c1c7157144bc8b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesBinaryOps.cpp @@ -0,0 +1,553 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +#include + +namespace at::functorch { + +template +static Tensor _binary_pointwise_batch_rule( + const Tensor& tensor, std::optional tensor_batch_dim, + const Tensor& other, std::optional other_batch_dim, + ExtraArgs... extra_args) { + + auto [tensor_, other_]= _binary_pointwise_helper( + tensor, tensor_batch_dim, other, other_batch_dim); + + return Func(tensor_, std::move(other_), std::forward(extra_args)...); +} + +template +struct BinaryPointwiseBatchRuleHelper; + +template +struct BinaryPointwiseBatchRuleHelper> { + static std::tuple> apply( + const Tensor& tensor, std::optional tensor_batch_dim, + const Tensor& other, std::optional other_batch_dim, + T... extra_args) { + return std::tuple(_binary_pointwise_batch_rule( + tensor, tensor_batch_dim, other, other_batch_dim, + std::forward(extra_args)...), 0); + } +}; + +#define BINARY_POINTWISE_BATCH_RULE(fn) SINGLE_ARG(\ + BinaryPointwiseBatchRuleHelper<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + +template +struct BinaryRandomPointwiseBatchRuleHelper; + +template +struct BinaryRandomPointwiseBatchRuleHelper> { + static Tensor apply(const Tensor& tensor, const Tensor& other, T... extra_args) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_layer.has_value()) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto cur_level = maybe_layer->layerId(); + RandomnessType randomness = maybe_layer->randomness(); + + auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(tensor, cur_level); + + auto [other_value, other_bdim] = unwrapTensorAtLevel(other, cur_level); + + check_randomness(randomness, (tensor_bdim || other_bdim)); + if (randomness == RandomnessType::Different && !tensor_bdim && !other_bdim) { + auto shape = tensor_value.sizes(); + VmapSymDimVector shapeVec(1, maybe_layer->batchSize()); + shapeVec.reserve(shape.size() + 1); + shapeVec.insert(shapeVec.end(), shape.begin(), shape.end()); + + // not taken care of with binary batch rule, which assumes at least one input is batched + tensor_value = tensor_value.expand_symint(shapeVec); + tensor_bdim = 0; + } else if (randomness == RandomnessType::Same && !tensor_bdim && !other_bdim) { + + // avoids unnecessary checks and batch rule assuming output is batched + return Func(tensor_value, other_value, std::forward(extra_args)...); + } + auto res = _binary_pointwise_batch_rule( + tensor_value, tensor_bdim, other_value, other_bdim, + std::forward(extra_args)...); + return makeBatched(std::move(res), 0, cur_level); + } +}; + +#define BINARY_RANDOM_POINTWISE_BATCH_RULE(fn) SINGLE_ARG(\ + BinaryRandomPointwiseBatchRuleHelper<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + +template +static void binary_pointwise_inplace_batch_rule( + Tensor& tensor, std::optional tensor_batch_dim, + const Tensor& other, std::optional other_batch_dim, + ExtraArgs... extra_args) { + if (!tensor_batch_dim && other_batch_dim) { + vmapIncompatibleInplaceError("inplace arithmetic"); + } + + // compute max logical rank + auto tensor_logical_rank = rankWithoutBatchDim(tensor, tensor_batch_dim); + auto other_logical_rank = rankWithoutBatchDim(other, other_batch_dim); + auto max_logical_rank = std::max(tensor_logical_rank, other_logical_rank); + + auto tensor_ = moveBatchDimToFront(tensor, tensor_batch_dim); + auto other_ = moveBatchDimToFront(other, other_batch_dim); + + // If the dimensions aren't aligned, we need to line them up. + // Tensor[B, 3] + Tensor[2, 5, 3] -> Tensor[B, 1, 1, 3] + Tensor[2, 5, 3] + // Note that only tensors that have a batch dim need to be modified. + // Tensor[B, 2, 3, 5] + Tensor[5] -> no changes needed + tensor_ = maybePadToLogicalRank(tensor_, tensor_batch_dim, max_logical_rank); + other_ = maybePadToLogicalRank(other_, other_batch_dim, max_logical_rank); + + (tensor_.*Meth)(other_, std::forward(extra_args)...); +} + +template +static std::tuple> comparison_pointwise_batch_rule( + const Tensor& tensor, std::optional tensor_batch_dim, + const Tensor& other, std::optional other_batch_dim) { + // compute max logical rank + auto tensor_logical_rank = rankWithoutBatchDim(tensor, tensor_batch_dim); + auto other_logical_rank = rankWithoutBatchDim(other, other_batch_dim); + auto max_logical_rank = std::max(tensor_logical_rank, other_logical_rank); + + auto tensor_ = moveBatchDimToFront(tensor, tensor_batch_dim); + auto other_ = moveBatchDimToFront(other, other_batch_dim); + + // If the dimensions aren't aligned, we need to line them up. + // Tensor[B, 3] + Tensor[2, 5, 3] -> Tensor[B, 1, 1, 3] + Tensor[2, 5, 3] + // Note that only tensors that have a batch dim need to be modified. + // Tensor[B, 2, 3, 5] + Tensor[5] -> no changes needed + tensor_ = maybePadToLogicalRank(tensor_, tensor_batch_dim, max_logical_rank); + other_ = maybePadToLogicalRank(other_, other_batch_dim, max_logical_rank); + + auto result = Func(tensor_, other_); + return std::make_tuple( std::move(result), 0 ); +} + +static std::tuple> where_self_batch_rule( + const Tensor& condition, std::optional condition_bdim, + const Tensor& self, std::optional self_bdim, const Tensor& other, std::optional other_bdim) { + auto condition_logical_rank = rankWithoutBatchDim(condition, condition_bdim); + auto tensor_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto other_logical_rank = rankWithoutBatchDim(other, other_bdim); + auto max_logical_rank = std::max({tensor_logical_rank, other_logical_rank, condition_logical_rank}); + + auto condition_ = moveBatchDimToFront(condition, condition_bdim); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto other_ = moveBatchDimToFront(other, other_bdim); + + condition_ = maybePadToLogicalRank(condition_, condition_bdim, max_logical_rank); + self_ = maybePadToLogicalRank(self_, self_bdim, max_logical_rank); + other_ = maybePadToLogicalRank(other_, other_bdim, max_logical_rank); + return std::make_tuple(at::where(condition_, self_, other_), 0); +} + +static std::tuple> gelu_backward_batch_rule( + const Tensor& grad_out, std::optional grad_out_bdim, const Tensor& input, std::optional input_bdim, + std::string_view approximate) { + + // repeat the preprocessing from _binary_pointwise_batch_rule + auto [grad_out_, input_]= _binary_pointwise_helper(grad_out, grad_out_bdim, input, input_bdim); + + // gelu_backward doesn't broadcast well so we need to insist all inputs have a bdim + const auto batch_size = get_bdim_size2(grad_out, grad_out_bdim, input, input_bdim); + grad_out_ = ensure_has_bdim(grad_out_, grad_out_bdim.has_value(), batch_size); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), batch_size); + + return std::make_tuple(at::gelu_backward(grad_out_, input_, approximate), 0); +} + +static std::tuple> masked_select_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& mask, std::optional mask_bdim) { + TORCH_CHECK(!mask_bdim.has_value(), + "vmap: Attempted to vmap over `mask` in torch.masked_select(self, mask) ", + "We cannot support this because for each batch this would return a ", + "differently shaped Tensor. " + "Please file an issue at https://github.com/pytorch/pytorch/issues if you need this feature."); + auto self_ = moveBatchDimToFront(self, self_bdim); + const auto batch_size = self_.size(0); + const auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + const auto max_logical_rank = std::max(self_logical_rank, mask.dim()); + self_ = maybePadToLogicalRank(self_, 0, max_logical_rank); + + // masked_select returns a 1D tensor, so we have to reshape it into 2D + auto result = at::masked_select(self_, mask).view({ batch_size, -1 }); + return std::make_tuple(std::move(result), 0); +} + +static std::tuple> masked_select_backward_batch_rule( + const Tensor& grad, std::optional grad_bdim, + const Tensor& self, std::optional self_bdim, + const Tensor& mask, std::optional mask_bdim) { + TORCH_CHECK(!mask_bdim.has_value(), + "vmap: Attempted to vmap over `mask` in torch.masked_select_backward(grad, self, mask) ", + "We cannot support this because for each batch this would return a ", + "differently shaped Tensor. " + "Please file an issue at https://github.com/pytorch/pytorch/issues if you need this feature."); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto grad_ = moveBatchDimToFront(grad, grad_bdim); + + const auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + const auto max_logical_rank = std::max(self_logical_rank, mask.dim()); + + self_ = maybePadToLogicalRank(self_, self_bdim, max_logical_rank); + + const auto batch_size = get_bdim_size2(grad, grad_bdim, self, self_bdim); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + grad_ = ensure_has_bdim(grad_, grad_bdim.has_value(), batch_size); + + auto result = at::masked_select_backward(grad_, self_.contiguous(), mask); + return std::make_tuple(std::move(result), 0); +} + +static std::tuple> cdist_backward_batch_rule( + const Tensor& grad, std::optional grad_bdim, + Tensor x1, std::optional x1_bdim, + Tensor x2, std::optional x2_bdim, + const double p, + const Tensor& cdist, std::optional cdist_bdim) { + + if (cdist_bdim && !x1_bdim) { + // We need to make sure that x1 has batch dim if cdist has one + // otherwise, we get + // RuntimeError: Function CdistBackward0 returned an invalid gradient at index 1 - got [5] + // but expected shape compatible with [4, 5] + auto bs = cdist.size(*cdist_bdim); + x1 = ensure_has_bdim(x1, false, bs).contiguous(); + x1_bdim = 0; + } + + // We need to apply the same preprocessing on x1 and x2 as in the forward pass + // _binary_pointwise_batch_rule + std::tie(x1, x2)= _binary_pointwise_helper(x1, x1_bdim, x2, x2_bdim); + + auto grad_ = moveBatchDimToFront(grad, grad_bdim); + if ((x1_bdim || x2_bdim) && !grad_bdim) { + // We need to make sure that grad has batch dim if x1 or x2 have one + // Probably, there is an assumption on the strides. + // Otherwise grad input contains thrash values, e.g. -7.0816e+29, 7.0816e+29 + auto bs = get_bdim_size2(x1, 0, x2, 0); + grad_ = ensure_has_bdim(grad_, grad_bdim.has_value(), bs); + grad_ = grad_.contiguous(); + } + + auto out = at::_cdist_backward(grad_, x1, x2, p, cdist); + + std::optional out_bdim = std::nullopt; + if (x1_bdim || x2_bdim) { + out_bdim = 0; + } + + return std::make_tuple(std::move(out), out_bdim); +} + +static void fill__Tensor_batch_rule( + Tensor& self, + std::optional self_bdim, + const Tensor& other, + std::optional other_bdim) { + if (!other_bdim.has_value()) { + // Optimization: fill_ is faster than the other path which does + // reshaping + copy_ + self.fill_(other); + return; + } + if (!self_bdim) { + vmapIncompatibleInplaceError("fill_"); + } + auto self_and_other = _binary_pointwise_helper( + self, self_bdim, other, other_bdim, /*do_type_promotion*/false); + std::get<0>(self_and_other).copy_(std::get<1>(self_and_other)); +} + +static +std::tuple,Tensor, std::optional> +rrelu_with_noise_batch_rule( + const Tensor& self, + std::optional self_bdim, + Tensor& noise, + std::optional noise_bdim, + const at::Scalar& lower, + const at::Scalar& upper, + bool training, + std::optional generator) { + + auto self_ = moveBatchDimToFront(self, self_bdim); + auto noise_ = moveBatchDimToFront(self, noise_bdim); + + auto ret = at::rrelu_with_noise(self_, noise_, lower, upper, training, std::move(generator)); + + return std::make_tuple(std::move(ret), 0, std::move(noise_), 0); +} + +static Tensor rrelu_with_noise_batch( + const Tensor& self, + Tensor& noise, + const Scalar& lower, + const Scalar& upper, + bool training, + std::optional generator) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "gen_vmap_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + auto [noise_value, noise_bdim] = unwrapTensorAtLevel(noise, cur_level); + TORCH_CHECK(!noise_bdim.has_value(), "vmap: Attempted to vmap over 'noise' in torch.rrelu_with_noise. This is not supported."); + auto res = rrelu_with_noise_batch_rule(self_value, self_bdim, noise_value, noise_bdim, lower, upper, training, std::move(generator)); + return makeBatched(std::move(std::get<0>(res)), std::get<1>(res), cur_level); +} + +static std::tuple> log_sigmoid_backward_batch_rule( + Tensor& grad, std::optional grad_bdim, + Tensor& self, std::optional self_bdim, + Tensor& buffer, std::optional buffer_bdim) { + // NB: This emulates handle_pointwise_ops except we ignore the last argument, buffer + // when any of the inputs are on cuda/xpu. + // We do this because on cuda/xpu, buffer is a dummy tensor always of logical rank 1 and + // it becomes an issue when the rest of the inputs are scalar + int64_t out_logical_rank = std::max(rankWithoutBatchDim(grad, grad_bdim), rankWithoutBatchDim(self, self_bdim)); + bool inputs_on_cuda = grad.is_cuda() || self.is_cuda() || buffer.is_cuda(); + bool inputs_on_xpu = grad.is_xpu() || self.is_xpu() || buffer.is_xpu(); + if (!inputs_on_cuda && !inputs_on_xpu) { + out_logical_rank = std::max(out_logical_rank, rankWithoutBatchDim(buffer, buffer_bdim)); + } + Tensor out_grad = maybePadToLogicalRank(moveBatchDimToFront(grad, grad_bdim), grad_bdim, out_logical_rank); + Tensor out_self = maybePadToLogicalRank(moveBatchDimToFront(self, self_bdim), self_bdim, out_logical_rank); + Tensor out_buffer = maybePadToLogicalRank(moveBatchDimToFront(buffer, buffer_bdim), buffer_bdim, out_logical_rank); + return std::make_tuple(at::log_sigmoid_backward(out_grad, out_self, out_buffer), 0); +} + +static Tensor binomial_wrapper(const Tensor& count, const Tensor& prob, std::optional gen) { + return at::binomial(count, prob.contiguous(), std::move(gen)); // Bug in PyTorch, prob shouldn't need to be contiguous +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchVmapMode, m) { + #define BINARY_RANDOM_POINTWISE(op) \ + m.impl(#op, BINARY_RANDOM_POINTWISE_BATCH_RULE(ATEN_FN(op))); + #define BINARY_RANDOM_POINTWISE2(op, overload) \ + m.impl(#op"."#overload, BINARY_RANDOM_POINTWISE_BATCH_RULE(ATEN_FN2(op, overload))); + + BINARY_RANDOM_POINTWISE2(normal, Tensor_Tensor); + m.impl("binomial", BINARY_RANDOM_POINTWISE_BATCH_RULE(at::functorch::binomial_wrapper)); +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { +#define BINARY_POINTWISE2(op, overload) \ + VMAP_SUPPORT2(op, overload, BINARY_POINTWISE_BATCH_RULE(ATEN_FN2(op, overload))); +#define BINARY_POINTWISE(op) \ + VMAP_SUPPORT(op, BINARY_POINTWISE_BATCH_RULE(ATEN_FN(op))); +#define UNARY_POINTWISE2(op, overload) \ + VMAP_SUPPORT2(op, overload, BASIC_UNARY_BATCH_RULE(ATEN_FN2(op, overload))); +#define UNARY_POINTWISE(op) \ + VMAP_SUPPORT(op, BASIC_UNARY_BATCH_RULE(ATEN_FN(op))); +#define UNARY_SCALAR_POINTWISE2(op, overload) \ + VMAP_SUPPORT(op, overload, SCALAR_UNARY_BATCH_RULE(ATEN_FN2(op, overload))); + +#define BINARY_SCALAR_2(op, tensor_tensor, tensor_scalar) \ + BINARY_POINTWISE2(op, tensor_tensor);\ + UNARY_POINTWISE2(op, tensor_scalar); + +// For all 3 combinations of Tensor x Tensor, Tensor x Scalar, Scalar x Tensor +#define BINARY_SCALAR_3(op, tensor_tensor, tensor_scalar, scalar_tensor) \ + BINARY_POINTWISE2(op, tensor_tensor);\ + UNARY_POINTWISE2(op, tensor_scalar);\ + POINTWISE_BOXED(op.scalar_tensor); + +#define BINARY_SCALAR_3_Tensor(op, tensor_scalar, scalar_tensor) \ + BINARY_POINTWISE(op);\ + UNARY_POINTWISE2(op, tensor_scalar);\ + POINTWISE_BOXED(op.scalar_tensor); + + // Batching rule registrations start + POINTWISE_BOXED(__ilshift__.Tensor); + POINTWISE_BOXED(__ilshift__.Scalar); + POINTWISE_BOXED(__irshift__.Tensor) + POINTWISE_BOXED(__irshift__.Scalar) + BINARY_SCALAR_2(__lshift__, Tensor, Scalar); + BINARY_SCALAR_2(__rshift__, Tensor, Scalar); + + BINARY_SCALAR_2(add, Tensor, Scalar); + POINTWISE_BOXED(addcdiv); + POINTWISE_BOXED(addcmul); + BINARY_POINTWISE(atan2); + BINARY_SCALAR_2(bitwise_and, Tensor, Scalar); + BINARY_POINTWISE2(bitwise_and_, Tensor); + POINTWISE_BOXED(bitwise_and_.Scalar); + POINTWISE_BOXED(bitwise_and.Scalar_Tensor); + BINARY_SCALAR_2(bitwise_or, Tensor, Scalar); + BINARY_POINTWISE2(bitwise_or_, Tensor); + POINTWISE_BOXED(bitwise_or_.Scalar); + POINTWISE_BOXED(bitwise_or.Scalar_Tensor); + BINARY_SCALAR_2(bitwise_xor, Tensor, Scalar); + BINARY_POINTWISE2(bitwise_xor_, Tensor); + POINTWISE_BOXED(bitwise_xor_.Scalar); + POINTWISE_BOXED(bitwise_xor.Scalar_Tensor); + BINARY_SCALAR_3(bitwise_left_shift, Tensor, Tensor_Scalar, Scalar_Tensor); + POINTWISE_BOXED(bitwise_left_shift_.Tensor_Scalar); + POINTWISE_BOXED(bitwise_left_shift_.Tensor); + BINARY_SCALAR_3(bitwise_right_shift, Tensor, Tensor_Scalar, Scalar_Tensor); + POINTWISE_BOXED(bitwise_right_shift_.Tensor_Scalar); + POINTWISE_BOXED(bitwise_right_shift_.Tensor); + + UNARY_POINTWISE(clamp); + POINTWISE_BOXED(clamp.Tensor); + BINARY_POINTWISE2(clamp_min, Tensor); + UNARY_POINTWISE(clamp_min); + POINTWISE_BOXED(clamp_min_); + BINARY_POINTWISE2(clamp_max, Tensor); + UNARY_POINTWISE(clamp_max); + POINTWISE_BOXED(clamp_max_); + BINARY_POINTWISE(complex); + + VARIADIC_BDIMS_BOXED(_euclidean_dist); + // Implementation note: _binary_pointwise_helper performs a dtype promotion if args are scalars, + // but cdist can't work with scalars, at least 2d tensors. + BINARY_POINTWISE(_cdist_forward); + VMAP_SUPPORT(_cdist_backward, cdist_backward_batch_rule); + + BINARY_SCALAR_2(copysign, Tensor, Scalar); + POINTWISE_BOXED(copysign_.Tensor); + POINTWISE_BOXED(copysign_.Scalar); + BINARY_SCALAR_2(div, Tensor, Scalar); + BINARY_SCALAR_2(div, Tensor_mode, Scalar_mode); + + BINARY_POINTWISE(floor_divide); + UNARY_POINTWISE2(floor_divide, Scalar); + + BINARY_POINTWISE(fmax); + BINARY_POINTWISE(fmin); + BINARY_SCALAR_2(fmod, Tensor, Scalar); + POINTWISE_BOXED(frexp.Tensor); + BINARY_POINTWISE(heaviside); + BINARY_POINTWISE(hypot); + BINARY_POINTWISE(gcd); + BINARY_POINTWISE(igamma); + BINARY_POINTWISE(igammac); + BINARY_POINTWISE2(ldexp, Tensor); + BINARY_POINTWISE(logaddexp); + BINARY_POINTWISE(logaddexp2); + POINTWISE_BOXED(lerp.Scalar); + POINTWISE_BOXED(lerp.Tensor); + BINARY_POINTWISE(lcm); + POINTWISE_BOXED(log_sigmoid_forward); + BINARY_POINTWISE(maximum); + BINARY_POINTWISE(minimum); + + BINARY_SCALAR_2(mul, Tensor, Scalar); + BINARY_POINTWISE(nextafter); + BINARY_SCALAR_3(pow, Tensor_Tensor, Tensor_Scalar, Scalar); + POINTWISE_BOXED2(pow_, Scalar); + BINARY_POINTWISE(polar); + POINTWISE_BOXED(polygamma); + BINARY_SCALAR_2(sub, Tensor, Scalar); + BINARY_SCALAR_3(remainder, Tensor, Scalar, Scalar_Tensor); + BINARY_SCALAR_2(rsub, Tensor, Scalar); + + BINARY_SCALAR_3_Tensor(special_xlog1py, other_scalar, self_scalar); + BINARY_SCALAR_3_Tensor(special_zeta, other_scalar, self_scalar); + + VMAP_SUPPORT2(where, self, where_self_batch_rule); + + BINARY_SCALAR_3(xlogy, Tensor, Scalar_Other, Scalar_Self); + + POINTWISE_BOXED(elu_backward); + BINARY_POINTWISE(hardsigmoid_backward); + BINARY_POINTWISE(hardtanh_backward); + BINARY_POINTWISE(hardshrink_backward); + BINARY_POINTWISE(hardswish_backward); + BINARY_POINTWISE(_prelu_kernel); + VARIADIC_BDIMS_BOXED(_prelu_kernel_backward); + BINARY_POINTWISE(leaky_relu_backward); + BINARY_POINTWISE(logit_backward); + VMAP_SUPPORT(log_sigmoid_backward, log_sigmoid_backward_batch_rule); + VMAP_SUPPORT(gelu_backward, gelu_backward_batch_rule); + BINARY_POINTWISE(sigmoid_backward); + POINTWISE_BOXED(softplus_backward); + BINARY_POINTWISE(softshrink_backward); + BINARY_POINTWISE(tanh_backward); + BINARY_POINTWISE(threshold_backward); + BINARY_POINTWISE(silu_backward); + + using TensorScalarInplaceT = Tensor& (Tensor::*)(const Tensor&, const Scalar&) const; + using ScalarScalarInplaceT = Tensor& (Tensor::*)(const Scalar&, const Scalar&) const; + using TensorInplaceT = Tensor& (Tensor::*)(const Tensor&) const; + using TensorInplaceModeT = Tensor& (Tensor::*)(const Tensor&, std::optional) const; + using ScalarInplaceT = Tensor& (Tensor::*)(const Scalar&) const; + using CopyT = Tensor& (Tensor::*)(const Tensor&, bool) const; + + POINTWISE_BOXED(add_.Tensor); // just testing + POINTWISE_BOXED(atan2_); + POINTWISE_BOXED(gcd_); + POINTWISE_BOXED(lcm_); + VMAP_SUPPORT2(add_, Scalar, SINGLE_ARG(unary_inplace_batch_rule)); + VMAP_SUPPORT2(sub_, Tensor, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + VMAP_SUPPORT2(sub_, Scalar, SINGLE_ARG(unary_inplace_batch_rule)); + VMAP_SUPPORT2(mul_, Tensor, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + VMAP_SUPPORT2(mul_, Scalar, SINGLE_ARG(unary_inplace_batch_rule)); + VMAP_SUPPORT2(div_, Tensor, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + VMAP_SUPPORT2(div_, Tensor_mode, SINGLE_ARG(binary_pointwise_inplace_batch_rule>)); + VMAP_SUPPORT2(div_, Scalar, SINGLE_ARG(unary_inplace_batch_rule)); + VMAP_SUPPORT2(clamp_min_, Tensor, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + VMAP_SUPPORT2(clamp_max_, Tensor, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + VMAP_SUPPORT2(masked_fill_, Scalar, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + VMAP_SUPPORT(copy_, SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + +#define COMPARISON_POINTWISE(op) \ + VMAP_SUPPORT2(op, Tensor, \ + SINGLE_ARG(comparison_pointwise_batch_rule)); \ + UNARY_POINTWISE2(op, Scalar) + + COMPARISON_POINTWISE(eq); + COMPARISON_POINTWISE(gt); + COMPARISON_POINTWISE(ge); + COMPARISON_POINTWISE(le); + COMPARISON_POINTWISE(lt); + COMPARISON_POINTWISE(ne); + +#undef COMPARISON_POINTWISE +#undef BINARY_POINTWISE2 +#undef BINARY_POINTWISE +#undef UNARY_POINTWISE2 +#undef UNARY_POINTWISE +#undef UNARY_SCALAR_POINTWISE2 +#undef BINARY_SCALAR_3 + +#define LOGICAL_COMPARISON_POINTWISE(op) \ + VMAP_SUPPORT(op, \ + SINGLE_ARG(comparison_pointwise_batch_rule)); \ + VMAP_SUPPORT(op ## _, \ + SINGLE_ARG(binary_pointwise_inplace_batch_rule)); + + LOGICAL_COMPARISON_POINTWISE(logical_and); + LOGICAL_COMPARISON_POINTWISE(logical_or); + LOGICAL_COMPARISON_POINTWISE(logical_xor); + +#undef SINGLE_ARG +#undef LOGICAL_COMPARISON_POINTWISE + VMAP_SUPPORT(masked_select, masked_select_batch_rule); + VMAP_SUPPORT(masked_select_backward, masked_select_backward_batch_rule); + + VMAP_SUPPORT2(fill_, Tensor, fill__Tensor_batch_rule); + m.impl("rrelu_with_noise", rrelu_with_noise_batch); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesConvolution.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesConvolution.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d6cb7d9eec370008e7d2bbfb0c957784af3b249 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesConvolution.cpp @@ -0,0 +1,461 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +namespace at::functorch { + +// convolution_batch_rule translated from jax with modifications: +// https://github.com/google/jax/blob/master/jax/_src/lax/lax.py#L3143 + +// PyTorch's convolution is different from JAX's conv_general_dilated: +// we do not support batch_group_count (which is needed for convolution backwards). +// Instead, there's a convolution_backward op that needs a batching rule. +static std::tuple> +convolution_batch_rule(const Tensor& lhs, std::optional lhs_bdim, const Tensor& rhs, std::optional rhs_bdim, const std::optional& bias, std::optional bias_bdim, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, c10::SymIntArrayRef output_padding, c10::SymInt groups) { + DimVector lhs_spec(stride.size() + 2); + std::iota(lhs_spec.begin(), lhs_spec.end(), 0); + DimVector rhs_spec = lhs_spec; + DimVector out_spec = lhs_spec; + if (transposed) { + rhs_spec[0] = 1; + rhs_spec[1] = 0; + } + + // If we have a batched bias or weight, we need to perform the computation separately. + std::optional unbatched_bias; + bool separate_bias = false; + if ((rhs_bdim && bias && bias->defined()) || bias_bdim) { + TORCH_INTERNAL_ASSERT(bias.has_value()); + TORCH_INTERNAL_ASSERT(bias->defined()); + unbatched_bias = std::nullopt; + separate_bias = true; + } else { + unbatched_bias = bias; + separate_bias = false; + } + std::tuple> result; + if (lhs_bdim && !rhs_bdim) { + auto new_x = reshape_dim_into(*lhs_bdim, lhs_spec[0], lhs); + auto out = at::convolution_symint(new_x, rhs, unbatched_bias, stride, padding, dilation, transposed, output_padding, groups); + out = reshape_dim_outof_symint(out_spec[0], lhs.sizes()[*lhs_bdim], out); + result = std::make_tuple(out, out_spec[0]); + } else if (!lhs_bdim && rhs_bdim) { + if (groups == 1) { + auto new_w = reshape_dim_into(*rhs_bdim, rhs_spec[0], rhs); + auto out = at::convolution_symint(lhs, new_w, unbatched_bias, stride, padding, dilation, transposed, output_padding, groups); + out = reshape_dim_outof_symint(out_spec[1], rhs.size(*rhs_bdim), out); + result = std::make_tuple(out, out_spec[1]); + } else { + if (transposed) { + // conv_transpose with groups is normally NIHW, IOHW -> N(GO)HW + // With RHS batched, we do the following: + // NIHW, BIOHW -> NIHW, I(BO)HW -> N(GBO)HW -> BN(GO)HW + // NB: the following isn't written using rhs_spec + // (PyTorch convs have a fixed dimension order) + + // BIOHW -> I(BO)HW + auto new_w = reshape_dim_into(*rhs_bdim, 1, rhs); + // NIHW, I(BO)HW -> N(GBO)HW + auto out = at::convolution_symint(lhs, new_w, unbatched_bias, stride, padding, dilation, transposed, output_padding, groups); + // N(GBO)HW -> NG(BO)HW + out = reshape_dim_outof_symint(1, groups, out); + // NG(BO)HW -> NGBOHW + out = reshape_dim_outof_symint(2, rhs.size(*rhs_bdim), out); + // NGBOHW -> NB(GO)HW + out = reshape_dim_into(1, 2, out); + result = std::make_tuple(out, 1); + } else { + // conv with groups is normally N(GI)HW, (GO)IHW -> N(GO)HW + // With RHS batched, we do the following: + // N(GI)HW, B(GO)IHW -> N(GI)HW, (GBO)IHW -> N(GBO)HW -> BN(GO)HW + // NB: the following isn't written using rhs_spec + // (PyTorch convs have a fixed dimension order) + + // B(GO)IHW -> BGOIHW + auto new_w = reshape_dim_outof_symint(0 + (*rhs_bdim == 0), groups, rhs); + // BGOIHW -> G(BO)IHW + new_w = reshape_dim_into(*rhs_bdim + (*rhs_bdim > 0), 1, new_w); + // G(BO)IHW -> (GBO)IHW + new_w = reshape_dim_into(0, 0, new_w); + // N(GI)HW, (GBO)IHW -> N(GBO)HW + auto out = at::convolution_symint(lhs, new_w, unbatched_bias, stride, padding, dilation, transposed, output_padding, groups); + // N(GBO)HW -> NG(BO)HW + out = reshape_dim_outof_symint(1, groups, out); + // NG(BO)HW -> NGBOHW + out = reshape_dim_outof_symint(2, rhs.size(*rhs_bdim), out); + // NGBOHW -> NB(GO)HW + out = reshape_dim_into(1, 2, out); + result = std::make_tuple(out, 1); + } + } + } else if (lhs_bdim && rhs_bdim) { + auto new_x = reshape_dim_into(*lhs_bdim, lhs_spec[1], lhs); + groups *= lhs.sizes()[*lhs_bdim]; + auto dim_with_groups = transposed ? 1 : 0; + auto new_w = reshape_dim_into(*rhs_bdim, rhs_spec[dim_with_groups], rhs); + auto out = at::convolution_symint(new_x, new_w, unbatched_bias, stride, padding, dilation, transposed, output_padding, groups); + out = reshape_dim_outof_symint(out_spec[1], lhs.sizes()[*lhs_bdim], out); + result = std::make_tuple(out, out_spec[1]); + } else { + result = std::make_tuple(at::convolution_symint(lhs, rhs, unbatched_bias, stride, padding, dilation, transposed, output_padding, groups), std::nullopt); + } + if (separate_bias) { + auto& [A, A_batch_dim] = result; + auto B = *bias; + auto B_batch_dim = bias_bdim; + A = moveBatchDimToFront(A, A_batch_dim); + B = moveBatchDimToFront(B, B_batch_dim); + for (size_t i = 0; i < out_spec.size() - 2; i++) { + B = B.unsqueeze(-1); + } + B = maybePadToLogicalRank(B, B_batch_dim, rankWithoutBatchDim(A, A_batch_dim)); + + return std::make_tuple(at::add(A, B), 0); + } else { + return result; + } +} + +static Tensor _convolution_decomp( + const Tensor& input_r, const Tensor& weight_r, const std::optional& bias_r_opt, + IntArrayRef stride_, IntArrayRef padding_, IntArrayRef dilation_, + bool transposed_, IntArrayRef output_padding_, int64_t groups_, + bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) { + // Ignore everything. If the user called this in the normal way, + // then they should be fine. + (void) benchmark; + (void) deterministic; + (void) cudnn_enabled; + (void) allow_tf32; + return at::convolution( + input_r, weight_r, bias_r_opt, stride_, padding_, dilation_, transposed_, output_padding_, groups_); +} + +static Tensor compute_grad_bias( + const Tensor& grad_output_, std::array output_mask) { + if (!output_mask[2]) { + return Tensor(); + } + DimVector reduce_dims; + reduce_dims.resize(grad_output_.dim() - 1); + reduce_dims[0] = 0; + std::iota(reduce_dims.begin() + 1, reduce_dims.end(), 2); + return grad_output_.sum(reduce_dims); +} + +// reshapes the batch_size into dim +static Tensor make_dummy( + const Tensor& tensor, std::optional tensor_bdim, + int64_t dim, int64_t batch_size) { + auto tensor_ = tensor_bdim ? tensor.select(*tensor_bdim, 0) : tensor; + auto orig_size = tensor_.size(dim); + tensor_ = tensor_.slice(dim, 0, 1); + + DimVector expand_shape(tensor_.sizes().begin(), tensor_.sizes().end()); + expand_shape[dim] = batch_size * orig_size; + + return tensor_.new_empty({}).expand(expand_shape); +} + +static std::tuple> +convolution_backward_input_batch_rule( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& input, std::optional input_bdim, + const Tensor& weight, std::optional weight_bdim, + c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, + c10::SymIntArrayRef output_padding, const c10::SymInt& groups) { + const std::array mask = {true, false, false}; + if (grad_output_bdim && weight_bdim) { + // regular: BNO, BOI -> N(BO), (BO)I -> N(BI) + // transposed: BNO, BIO -> N(BO), (BI)O -> N(BI) + const auto batch_size = weight.size(*weight_bdim); + const auto grad_output_ = reshape_dim_into(*grad_output_bdim, 1, grad_output); + const auto weight_ = reshape_dim_into(*weight_bdim, 0, weight); + auto dummy_input = make_dummy(input, input_bdim, 1, batch_size); + const auto result = at::convolution_backward_symint( + grad_output_, dummy_input, weight_, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups * batch_size, mask); + auto grad_input = reshape_dim_outof(1, batch_size, std::get<0>(result)); + return std::make_tuple(std::move(grad_input), 1); + } else if (grad_output_bdim && !weight_bdim) { + // BNO, OI -> (BN)O, OI -> (BN)I + // transposed is the same. + const auto batch_size = grad_output.size(*grad_output_bdim); + const auto grad_output_ = reshape_dim_into(*grad_output_bdim, 0, grad_output); + auto dummy_input = make_dummy(input, input_bdim, 0, batch_size); + const auto result = at::convolution_backward_symint( + grad_output_, dummy_input, weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto grad_input = reshape_dim_outof(0, batch_size, std::get<0>(result)); + return std::make_tuple(std::move(grad_input), 0); + } else if (!grad_output_bdim && weight_bdim) { + const auto batch_size = weight.size(*weight_bdim); + if (groups == 1) { + // regular: NO, BOI -> NO, O(BI) -> N(BI) + // transposed: NO, BIO -> NO, (BI)O -> N(BI) + const auto in_ch_dim = transposed ? 0 : 1; + const auto weight_ = reshape_dim_into(*weight_bdim, in_ch_dim, weight); + auto dummy_input = make_dummy(input, input_bdim, 1, batch_size); + const auto result = at::convolution_backward_symint( + grad_output, dummy_input, weight_, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto grad_input = reshape_dim_outof(1, batch_size, std::get<0>(result)); + return std::make_tuple(std::move(grad_input), 1); + } + Tensor grad_input; + if (!transposed) { + // N(GO), B(GO)I -> N(GO), (GO)(BI) -> N(GBI) + const auto weight_ = reshape_dim_into(*weight_bdim, 1, weight); + auto dummy_input = make_dummy(input, input_bdim, 1, batch_size); + grad_input = std::get<0>(at::convolution_backward_symint( + grad_output, dummy_input, weight_, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask)); // N(GBI) + } else { + // N(GO), B(GI)O -> N(GO), (GBI)O -> N(GBI) + auto weight_ = moveBatchDimToFront(weight, weight_bdim); // B(GI)O + weight_ = reshape_dim_outof_symint(1, groups, weight_); // BGIO + weight_ = weight_.transpose(0, 1); // GBIO + weight_ = weight_.flatten(0, 2); // (GBI)O + const auto dummy_input = make_dummy(input, input_bdim, 1, batch_size); + grad_input = std::get<0>(at::convolution_backward_symint( + grad_output, dummy_input, weight_, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask)); // N(GBI) + } + // N(GBI) -> NG(BI) -> NGBI -> NBGI -> NB(GI) + grad_input = reshape_dim_outof_symint(1, groups, grad_input); + grad_input = reshape_dim_outof_symint(2, batch_size, grad_input); + grad_input = grad_input.transpose(1, 2); + grad_input = reshape_dim_into(2, 2, grad_input); + return std::make_tuple(std::move(grad_input), 1); + } else { + TORCH_INTERNAL_ASSERT(input_bdim); + const auto dummy_input = make_dummy(input, input_bdim, 0, 1); + auto result = at::convolution_backward_symint( + grad_output, dummy_input, weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + return std::make_tuple(std::move(std::get<0>(result)), std::nullopt); + } +} +static std::tuple> +convolution_backward_weight_batch_rule( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& input, std::optional input_bdim, + const Tensor& weight, std::optional weight_bdim, + c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, + c10::SymIntArrayRef output_padding, const c10::SymInt& groups) { + const std::array mask = {false, true, false}; + if (grad_output_bdim && input_bdim) { + // BNO, BNI -> N(BO), N(BI) -> (BO)I (regular) (BI)O (transposed) + const auto batch_size = input.size(*input_bdim); + const auto grad_output_ = reshape_dim_into(*grad_output_bdim, 1, grad_output); + const auto input_ = reshape_dim_into(*input_bdim, 1, input); + const auto dummy_weight = make_dummy(weight, weight_bdim, 0, batch_size); + auto result = at::convolution_backward_symint( + grad_output_, input_, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups * batch_size, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = reshape_dim_outof_symint(0, batch_size, grad_weight); + return std::make_tuple(std::move(grad_weight), 0); + } else if (grad_output_bdim && !input_bdim) { + const auto batch_size = grad_output.size(*grad_output_bdim); + if (groups == 1) { + // regular: BNO, NI -> N(BO), NI -> (BO)I + // transposed: BNO, NI -> N(BO), NI -> I(BO) + const auto grad_output_ = reshape_dim_into(*grad_output_bdim, 1, grad_output); + const auto out_ch_dim = transposed ? 1 : 0; + const auto dummy_weight = make_dummy(weight, weight_bdim, out_ch_dim, batch_size); + auto result = at::convolution_backward_symint( + grad_output_, input, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = reshape_dim_outof_symint(out_ch_dim, batch_size, grad_weight); + return std::make_tuple(std::move(grad_weight), out_ch_dim); + } else { + auto grad_output_ = moveBatchDimToFront(grad_output, grad_output_bdim); // BN(GO) + grad_output_ = reshape_dim_outof_symint(2, groups, grad_output_); // BNGO + grad_output_ = grad_output_.movedim(0, 2); // NGBO + grad_output_ = grad_output_.flatten(1, 3); // N(GBO) + if (!transposed) { + // BN(GO), N(GI) -> N(GBO), N(GI) -> (GBO)I + const auto dummy_weight = make_dummy(weight, weight_bdim, 0, batch_size); + auto result = at::convolution_backward_symint( + grad_output_, input, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = grad_weight.unflatten_symint(0, { groups, batch_size, -1 }); // GBOI + grad_weight = grad_weight.transpose(0, 1); // BGOI + grad_weight = grad_weight.flatten(1, 2); // B(GO)I + return std::make_tuple(std::move(grad_weight), 0); + } else { + // BN(GO), N(GI) -> N(GBO), N(GI) -> (GI)(BO) + const auto dummy_weight = make_dummy(weight, weight_bdim, 1, batch_size); + auto result = at::convolution_backward_symint( + grad_output_, input, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = reshape_dim_outof_symint(1, batch_size, grad_weight); + return std::make_tuple(std::move(grad_weight), 1); + } + } + } else if (!grad_output_bdim && input_bdim) { + const auto batch_size = input.size(*input_bdim); + if (groups == 1) { + // regular: NO, BNI -> NO, N(BI) -> O(BI) + // transposed: NO, BNI -> NO, N(BI) -> (BI)O + const auto input_ = reshape_dim_into(*input_bdim, 1, input); + const auto in_ch_dim = transposed ? 0 : 1; + const auto dummy_weight = make_dummy(weight, weight_bdim, in_ch_dim, batch_size); + auto result = at::convolution_backward_symint( + grad_output, input_, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = reshape_dim_outof_symint(in_ch_dim, batch_size, grad_weight); + return std::make_tuple(std::move(grad_weight), in_ch_dim); + } else { + auto input_ = moveBatchDimToFront(input, input_bdim); // BN(GI) + input_ = reshape_dim_outof_symint(2, groups, input_); // BNGI + input_ = input_.movedim(0, 2); // NGBI + input_ = input_.flatten(1, 3); // N(GBI) + if (!transposed) { + // regular: N(GO), BN(GI) -> N(GO), N(GBI) -> (GO)(BI) + const auto dummy_weight = make_dummy(weight, weight_bdim, 1, batch_size); + auto result = at::convolution_backward_symint( + grad_output, input_, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = reshape_dim_outof_symint(1, batch_size, grad_weight); + return std::make_tuple(std::move(grad_weight), 1); + } else { + // transposed: N(GO), BN(GI) -> N(GO), N(GBI) -> (GBI)O + const auto dummy_weight = make_dummy(weight, weight_bdim, 0, batch_size); + auto result = at::convolution_backward_symint( + grad_output, input_, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + auto& grad_weight = std::get<1>(result); + grad_weight = grad_weight.unflatten_symint(0, { groups, batch_size, -1 }); // GBIO + grad_weight = grad_weight.transpose(0, 1); // BGIO + grad_weight = grad_weight.flatten(1, 2); // B(GI)O + return std::make_tuple(std::move(grad_weight), 0); + } + } + } else { + TORCH_INTERNAL_ASSERT(weight_bdim); + const auto dummy_weight = make_dummy(weight, weight_bdim, 0, 1); + auto result = at::convolution_backward_symint( + grad_output, input, dummy_weight, std::nullopt, stride, padding, + dilation, transposed, output_padding, groups, mask); + return std::make_tuple(std::move(std::get<1>(result)), std::nullopt); + + } +} + +static std::tuple convolution_backward_plumbing( + const Tensor& grad_output_, const Tensor& input_, const Tensor& weight_, + const c10::OptionalArrayRef bias_sizes_opt, + c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, bool transposed, + c10::SymIntArrayRef output_padding, c10::SymInt groups, std::array output_mask) { + const auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "convolution_backward_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({grad_output_, input_, weight_}, cur_level)){ + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::convolution_backward_symint( + grad_output_, input_, weight_, bias_sizes_opt, stride, padding, + dilation, transposed, output_padding, std::move(groups), output_mask); + } + + auto [grad_output, grad_output_bdim] = unwrapTensorAtLevel(grad_output_, cur_level); + auto [input, input_bdim] = unwrapTensorAtLevel(input_, cur_level); + auto [weight, weight_bdim] = unwrapTensorAtLevel(weight_, cur_level); + + auto grad_bias = compute_grad_bias(grad_output_, output_mask); + output_mask[2] = false; + + // TODO: A little bird says that unfold + matmul is actually faster than + // group convolution in many cases. We should benchmark some of + // the common cases and replace things with unfold + matmul as necessary. + + // Notation: + // B - a batch dimension + // G - groups (sometimes omitted because it doesn't matter) + // NO - grad_output + // NI - input + // OI - weight + // "(BO)I" - we don't actually care about the values of this Tensor, + // we just need to create a tensor on the same device with the + // correct shape and pray that the implementation is smart enough + // to not do anything with it. + + // BNO, BNI, BOI + // AKA one of the model ensembling case + if (grad_output_bdim && input_bdim && weight_bdim) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + grad_output = reshape_dim_into(*grad_output_bdim, 1, grad_output); + + // BNO, BNI, BOI -> N(BO), N(BI), (BO)I + const auto batch_size = weight.size(*weight_bdim); + input = reshape_dim_into(*input_bdim, 1, input); + weight = reshape_dim_into(*weight_bdim, 0, weight); + const auto result = at::convolution_backward_symint( + grad_output, input, weight, std::nullopt, stride, padding, dilation, + transposed, output_padding, batch_size * groups, output_mask); + // N(BI), (BO)I -> NBI, BOI + auto grad_input = output_mask[0] ? + reshape_dim_outof(1, batch_size, std::get<0>(result)) : Tensor(); + auto grad_weight = output_mask[1] ? + reshape_dim_outof(0, batch_size, std::get<1>(result)) : Tensor(); + return std::make_tuple( + output_mask[0] ? makeBatched(std::move(grad_input), 1, cur_level) : std::move(grad_input), + output_mask[1] ? makeBatched(std::move(grad_weight), 0, cur_level) : std::move(grad_weight), + std::move(grad_bias)); + } + + Tensor grad_input; + if (output_mask[0]) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto [tensor, bdim] = convolution_backward_input_batch_rule( + grad_output, grad_output_bdim, + input, input_bdim, + weight, weight_bdim, + stride, padding, dilation, transposed, output_padding, groups); + grad_input = makeBatched(std::move(tensor), bdim, cur_level); + } + + Tensor grad_weight; + if (output_mask[1]) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto [tensor, bdim] = convolution_backward_weight_batch_rule( + grad_output, grad_output_bdim, + input, input_bdim, + weight, weight_bdim, + stride, padding, dilation, transposed, output_padding, groups); + grad_weight = makeBatched(std::move(tensor), bdim, cur_level); + } + return std::make_tuple(std::move(grad_input), std::move(grad_weight), std::move(grad_bias)); + + // Someone's definitely going to find a problem with this batching rule so + // I'm leaving the following fallback if we need it back. + // static auto op = c10::Dispatcher::singleton() + // .findSchemaOrThrow("aten::convolution_backward", ""); + // auto result = slow_fallback(op, { + // grad_output_, input_, weight_, bias_sizes_opt, + // stride, padding, dilation, transposed, output_padding, groups, output_mask + // }); + // return std::make_tuple(grad_input, std::get<1>(result), grad_bias); +} + + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT(convolution, convolution_batch_rule); + m.impl("_convolution", _convolution_decomp); + m.impl("convolution_backward", convolution_backward_plumbing); +} + +} // namespace at;:functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesDecompositions.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesDecompositions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7daeebf60f9f0daefa4d898a1669d48f3a2f5b6f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesDecompositions.cpp @@ -0,0 +1,398 @@ + +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include +#include +#include + +namespace at::functorch { + +#define OP_DECOMPOSE(op) m.impl(#op, static_cast(native::op)); +#define OP_DECOMPOSE2(op, overload) m.impl(#op"."#overload, static_cast(native::op)); + +TORCH_LIBRARY_IMPL(aten, FuncTorchVmapMode, m) { + OP_DECOMPOSE(alpha_dropout_); + OP_DECOMPOSE(dropout_); + OP_DECOMPOSE(feature_alpha_dropout_); + OP_DECOMPOSE(feature_dropout_); + OP_DECOMPOSE(dropout); + OP_DECOMPOSE(_scaled_dot_product_attention_math); + OP_DECOMPOSE(scaled_dot_product_attention); +} + +static void unsupportedData(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, "mutating directly with `.data` under vmap transform is not allowed."); +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatchedDecomposition, m) { + OP_DECOMPOSE2(__and__, Scalar); + OP_DECOMPOSE2(__and__, Tensor); + OP_DECOMPOSE2(__iand__, Tensor); + OP_DECOMPOSE2(__iand__, Scalar); + OP_DECOMPOSE2(__ior__, Tensor); + OP_DECOMPOSE2(__ior__, Scalar); + OP_DECOMPOSE2(__ixor__, Tensor); + OP_DECOMPOSE2(__ixor__, Scalar); + OP_DECOMPOSE2(__or__, Tensor); + OP_DECOMPOSE2(__or__, Scalar); + OP_DECOMPOSE2(__xor__, Tensor); + OP_DECOMPOSE2(__xor__, Scalar); + OP_DECOMPOSE(_batch_norm_impl_index); + OP_DECOMPOSE(absolute); + OP_DECOMPOSE(absolute_); + OP_DECOMPOSE(arctan2); + OP_DECOMPOSE(arctan2_); + OP_DECOMPOSE(argsort); + OP_DECOMPOSE2(argsort, stable); + OP_DECOMPOSE(avg_pool1d); + OP_DECOMPOSE(adaptive_max_pool1d); + OP_DECOMPOSE(adaptive_avg_pool1d); + m.impl("adaptive_avg_pool2d", native::adaptive_avg_pool2d_symint); + m.impl("adaptive_avg_pool3d", native::adaptive_avg_pool3d_symint); + OP_DECOMPOSE(adjoint); + OP_DECOMPOSE(arccos); + OP_DECOMPOSE(arccos_); + OP_DECOMPOSE(arccosh); + OP_DECOMPOSE(arccosh_); + OP_DECOMPOSE(arcsin); + OP_DECOMPOSE(arcsin_); + OP_DECOMPOSE(arcsinh); + OP_DECOMPOSE(arcsinh_); + OP_DECOMPOSE(arctan); + OP_DECOMPOSE(arctan_); + OP_DECOMPOSE(arctanh); + OP_DECOMPOSE(arctanh_); + OP_DECOMPOSE(atleast_1d); + OP_DECOMPOSE2(atleast_1d, Sequence); + OP_DECOMPOSE(atleast_2d); + OP_DECOMPOSE2(atleast_2d, Sequence); + OP_DECOMPOSE(atleast_3d); + OP_DECOMPOSE2(atleast_3d, Sequence); + OP_DECOMPOSE(batch_norm); + OP_DECOMPOSE(broadcast_tensors); + m.impl("broadcast_to", native::broadcast_to_symint); + OP_DECOMPOSE(cartesian_prod); + OP_DECOMPOSE(cdist); + OP_DECOMPOSE(chunk); + OP_DECOMPOSE(clip); + OP_DECOMPOSE2(clip, Tensor ); + OP_DECOMPOSE(concat); + OP_DECOMPOSE(conj_physical); + OP_DECOMPOSE(contiguous); + OP_DECOMPOSE(combinations); + OP_DECOMPOSE(corrcoef); + OP_DECOMPOSE(cosine_embedding_loss); + OP_DECOMPOSE(cosine_similarity); + OP_DECOMPOSE(cov); + OP_DECOMPOSE(cross); + m.impl("cross_entropy_loss", native::cross_entropy_loss_symint); + OP_DECOMPOSE2(cumulative_trapezoid, x); + OP_DECOMPOSE2(cumulative_trapezoid, dx); + OP_DECOMPOSE2(dsplit, int); + OP_DECOMPOSE2(dsplit, array); + OP_DECOMPOSE(det); + OP_DECOMPOSE(diff); + OP_DECOMPOSE(diag); + OP_DECOMPOSE(dstack); + OP_DECOMPOSE(einsum); + m.impl("embedding_backward", native::embedding_backward_symint); + OP_DECOMPOSE(expand_as); + m.impl("fft_fft", native::fft_fft_symint); + OP_DECOMPOSE(fft_fftshift); + m.impl("fft_fft2", native::fft_fft2_symint); + m.impl("fft_fftn", native::fft_fftn_symint); + m.impl("fft_hfft", native::fft_hfft_symint); + m.impl("fft_hfft2", native::fft_hfft2_symint); + m.impl("fft_hfftn", native::fft_hfftn_symint); + m.impl("fft_ifft", native::fft_ifft_symint); + OP_DECOMPOSE(fft_ifftshift); + m.impl("fft_ifft2", native::fft_ifft2_symint); + m.impl("fft_ifftn", native::fft_ifftn_symint); + m.impl("fft_ihfft", native::fft_ihfft_symint); + m.impl("fft_irfft", native::fft_irfft_symint); + m.impl("fft_irfft2", native::fft_irfft2_symint); + m.impl("fft_irfftn", native::fft_irfftn_symint); + m.impl("fft_rfft", native::fft_rfft_symint); + m.impl("fft_rfft2", native::fft_rfft2_symint); + m.impl("fft_rfftn", native::fft_rfftn_symint); + OP_DECOMPOSE(fix); + OP_DECOMPOSE(fliplr); + OP_DECOMPOSE(flipud); + OP_DECOMPOSE2(flatten, using_ints); + OP_DECOMPOSE2(float_power, Tensor_Tensor); + OP_DECOMPOSE2(float_power, Tensor_Scalar); + OP_DECOMPOSE2(float_power, Scalar); + OP_DECOMPOSE(gather_backward); + OP_DECOMPOSE(ger); + OP_DECOMPOSE2(gradient, scalarint); + OP_DECOMPOSE2(gradient, scalararray); + OP_DECOMPOSE2(gradient, array); + OP_DECOMPOSE2(gradient, scalarrayint); + OP_DECOMPOSE2(gradient, scalarrayarray); + OP_DECOMPOSE2(gradient, tensorarrayint); + OP_DECOMPOSE2(gradient, tensorarray); + OP_DECOMPOSE2(greater_equal, Tensor ); + OP_DECOMPOSE2(greater_equal, Scalar ); + OP_DECOMPOSE2(greater, Tensor ); + OP_DECOMPOSE(grid_sampler); + OP_DECOMPOSE(group_norm); + OP_DECOMPOSE(hinge_embedding_loss); + OP_DECOMPOSE2(hsplit, int); + OP_DECOMPOSE2(hsplit, array); + OP_DECOMPOSE(hstack); + m.impl("index_select_backward", native::index_select_backward_symint); + OP_DECOMPOSE(inner); + OP_DECOMPOSE(inverse); + OP_DECOMPOSE(isfinite); + OP_DECOMPOSE(isreal); + OP_DECOMPOSE(concatenate); + OP_DECOMPOSE(instance_norm); + OP_DECOMPOSE(kron); + OP_DECOMPOSE(l1_loss); + m.impl("layer_norm", native::layer_norm_symint); + m.impl("_fused_rms_norm", native::rms_norm_composite); + OP_DECOMPOSE2(less_equal, Tensor ); + OP_DECOMPOSE2(less, Tensor ); + OP_DECOMPOSE(linear); + OP_DECOMPOSE(linalg_cond); + OP_DECOMPOSE(linalg_cholesky); + OP_DECOMPOSE(linalg_det); + OP_DECOMPOSE(linalg_eigvalsh); + OP_DECOMPOSE(linalg_eigvals); + OP_DECOMPOSE(linalg_inv); + OP_DECOMPOSE(linalg_lu_factor); + OP_DECOMPOSE(linalg_matmul); + OP_DECOMPOSE(linalg_matrix_norm); + OP_DECOMPOSE2(linalg_matrix_norm, str_ord); + OP_DECOMPOSE(linalg_multi_dot); + OP_DECOMPOSE(linalg_norm); + OP_DECOMPOSE2(linalg_norm, ord_str); + OP_DECOMPOSE(linalg_eigh); + OP_DECOMPOSE(linalg_solve); + OP_DECOMPOSE(linalg_solve_ex); + OP_DECOMPOSE(linalg_svd); + OP_DECOMPOSE(linalg_svdvals); + OP_DECOMPOSE(linalg_pinv); + OP_DECOMPOSE(linalg_tensorinv); + OP_DECOMPOSE2(linalg_pinv, atol_rtol_float); + m.impl("linalg_vander", native::linalg_vander_symint); + OP_DECOMPOSE(cumprod_backward); + OP_DECOMPOSE(linalg_matrix_power); + OP_DECOMPOSE(linalg_vecdot); + OP_DECOMPOSE(log_sigmoid); + OP_DECOMPOSE(logdet); + OP_DECOMPOSE2(log_softmax, int); + OP_DECOMPOSE(_lu_with_info); + OP_DECOMPOSE(matmul); + OP_DECOMPOSE(matrix_H); + OP_DECOMPOSE(matrix_exp); + OP_DECOMPOSE(matrix_power); + OP_DECOMPOSE2(max, other ); + OP_DECOMPOSE(max_pool1d); + OP_DECOMPOSE(max_pool1d_with_indices); + OP_DECOMPOSE(max_pool2d); + OP_DECOMPOSE(max_pool3d); + OP_DECOMPOSE(meshgrid); + OP_DECOMPOSE2(meshgrid, indexing); + OP_DECOMPOSE(mH); + OP_DECOMPOSE2(min, other ); + OP_DECOMPOSE2(moveaxis, intlist); + OP_DECOMPOSE2(movedim, int); + OP_DECOMPOSE2(movedim, intlist); + OP_DECOMPOSE(msort); + OP_DECOMPOSE(mT); + OP_DECOMPOSE(nanmean); + m.impl("narrow", native::narrow_symint); + OP_DECOMPOSE(negative); + OP_DECOMPOSE2(frobenius_norm, dim); + OP_DECOMPOSE2(nuclear_norm, dim); + OP_DECOMPOSE(nuclear_norm); + m.impl("nll_loss_nd", native::nll_loss_nd_symint); + m.impl("nll_loss", native::nll_loss_symint); + m.impl("nll_loss2d", native::nll_loss2d_symint); + OP_DECOMPOSE2(not_equal, Tensor ); + OP_DECOMPOSE(outer); + OP_DECOMPOSE(pairwise_distance); + OP_DECOMPOSE(pinverse); + OP_DECOMPOSE(poisson_nll_loss); + OP_DECOMPOSE(positive); + OP_DECOMPOSE(qr); + OP_DECOMPOSE(ravel); + m.impl("repeat_interleave.self_int", static_cast(native::repeat_interleave_symint)); + m.impl("repeat_interleave.self_Tensor", static_cast(native::repeat_interleave_symint)); + m.impl("reshape", native::reshape_symint); + OP_DECOMPOSE(resolve_conj); + OP_DECOMPOSE(resolve_neg); + m.impl("rms_norm", native::rms_norm_symint); + OP_DECOMPOSE(row_stack); + OP_DECOMPOSE(rrelu); + OP_DECOMPOSE(rrelu_); + OP_DECOMPOSE(relu6); + OP_DECOMPOSE(relu6_); + OP_DECOMPOSE(prelu); + OP_DECOMPOSE2(softmax, int); + OP_DECOMPOSE(special_gammainc); + OP_DECOMPOSE(special_gammaincc); + OP_DECOMPOSE(special_logit); + OP_DECOMPOSE(special_log_softmax); + OP_DECOMPOSE(special_logsumexp); + OP_DECOMPOSE(special_multigammaln); + OP_DECOMPOSE(special_polygamma); + OP_DECOMPOSE(special_softmax); + OP_DECOMPOSE(special_digamma); + OP_DECOMPOSE(special_erf); + OP_DECOMPOSE(special_erfc); + OP_DECOMPOSE(special_erfinv); + OP_DECOMPOSE(special_exp2); + OP_DECOMPOSE(special_expm1); + OP_DECOMPOSE(special_expit); + OP_DECOMPOSE(special_gammaln); + OP_DECOMPOSE(special_i0); + OP_DECOMPOSE(special_log1p); + OP_DECOMPOSE(special_ndtr); + OP_DECOMPOSE(special_psi); + OP_DECOMPOSE(special_round); + OP_DECOMPOSE(special_sinc); + OP_DECOMPOSE(special_xlogy); + OP_DECOMPOSE2(special_xlogy, other_scalar); + OP_DECOMPOSE2(special_xlogy, self_scalar); + + + m.impl("split.sizes", native::split_symint); + OP_DECOMPOSE(square); + OP_DECOMPOSE(numpy_T); + OP_DECOMPOSE(reshape_as); + OP_DECOMPOSE(slogdet); + OP_DECOMPOSE2(result_type, Tensor); + OP_DECOMPOSE2(result_type, Scalar); + OP_DECOMPOSE2(result_type, Scalar_Tensor); + OP_DECOMPOSE2(result_type, Scalar_Scalar); + OP_DECOMPOSE(is_same_size); + OP_DECOMPOSE(view_as); + OP_DECOMPOSE2(size, int); + OP_DECOMPOSE(is_complex); + OP_DECOMPOSE(std); + OP_DECOMPOSE(selu); + OP_DECOMPOSE(selu_); + OP_DECOMPOSE2(std, dim); + OP_DECOMPOSE(std_mean); + OP_DECOMPOSE2(std_mean, dim); + OP_DECOMPOSE(swapaxes); + OP_DECOMPOSE2(subtract, Tensor); + m.impl("sum_to_size", native::sum_to_size_symint); + OP_DECOMPOSE(svd); + OP_DECOMPOSE(swapdims); + OP_DECOMPOSE(take_along_dim); + OP_DECOMPOSE(tensordot); + m.impl("tensor_split.indices", native::tensor_split_indices_symint); + m.impl("tensor_split.sections", native::tensor_split_sections_symint); + OP_DECOMPOSE(_test_check_tensor); + m.impl("tile", native::tile_symint); + OP_DECOMPOSE2(trapezoid, x); + OP_DECOMPOSE2(trapezoid, dx); + OP_DECOMPOSE2(trapz, x); + OP_DECOMPOSE2(trapz, dx); + OP_DECOMPOSE(unsafe_chunk); + m.impl("value_selecting_reduction_backward", native::value_selecting_reduction_backward_symint); + OP_DECOMPOSE(var); + OP_DECOMPOSE2(var, dim); + OP_DECOMPOSE(var_mean); + OP_DECOMPOSE2(var_mean, dim); + OP_DECOMPOSE2(vsplit, int); + OP_DECOMPOSE2(vsplit, array); + OP_DECOMPOSE(vstack); + OP_DECOMPOSE2(where, ScalarOther); + OP_DECOMPOSE2(where, ScalarSelf); + OP_DECOMPOSE2(where, Scalar); + OP_DECOMPOSE(orgqr); + m.impl("unflatten.int", native::unflatten_symint); + m.impl("_convolution_double_backward", native::_convolution_double_backward); + m.impl("conv_transpose1d", native::conv_transpose1d_symint); + m.impl("conv_transpose2d.input", native::conv_transpose2d_symint); + m.impl("conv_transpose3d.input", native::conv_transpose3d_symint); + m.impl("conv1d", native::conv1d_symint); + m.impl("conv2d", native::conv2d_symint); + m.impl("conv3d", native::conv3d_symint); + m.impl("conv1d.padding", native::conv1d_padding_symint); + m.impl("conv2d.padding", native::conv2d_padding_symint); + m.impl("conv3d.padding", native::conv3d_padding_symint); + m.impl("_convolution_mode", native::_convolution_mode_symint); + OP_DECOMPOSE(type_as); + OP_DECOMPOSE(linalg_diagonal); + OP_DECOMPOSE(diagonal_copy); + OP_DECOMPOSE(alias_copy); + m.impl("as_strided_copy", native::as_strided_copy_symint); + m.impl("pad", native::pad_symint); + m.impl("_pad_circular", native::_pad_circular_symint); + OP_DECOMPOSE(swapdims_); + OP_DECOMPOSE(swapaxes_); + OP_DECOMPOSE(unfold_copy); + // Easy way to decompose upsample*.vec overloads instead of introducing *_symint methods + // if used OP_DECOMPOSE2. + m.impl("upsample_bilinear2d.vec", native::upsample_bilinear2d); + m.impl("upsample_bicubic2d.vec", native::upsample_bicubic2d); + m.impl("_upsample_bilinear2d_aa.vec", native::_upsample_bilinear2d_aa); + m.impl("_upsample_bicubic2d_aa.vec", native::_upsample_bicubic2d_aa); + m.impl("upsample_linear1d.vec", native::upsample_linear1d); + m.impl("upsample_nearest1d.vec", native::upsample_nearest1d); + m.impl("upsample_nearest2d.vec", native::upsample_nearest2d); + m.impl("upsample_nearest3d.vec", native::upsample_nearest3d); + m.impl("upsample_trilinear3d.vec", native::upsample_trilinear3d); + + // views on complex tensor + OP_DECOMPOSE(imag); + OP_DECOMPOSE(real); + + // divide, alias for div + OP_DECOMPOSE2(divide, Tensor); + OP_DECOMPOSE2(divide_, Tensor); + OP_DECOMPOSE2(divide, Scalar); + OP_DECOMPOSE2(divide, Tensor_mode); + OP_DECOMPOSE2(divide_, Tensor_mode); + OP_DECOMPOSE2(divide, Scalar_mode); + OP_DECOMPOSE2(divide_, Scalar_mode); + + // divide, alias for div + OP_DECOMPOSE2(true_divide, Tensor); + OP_DECOMPOSE2(true_divide_, Tensor); + OP_DECOMPOSE2(true_divide, Scalar); + OP_DECOMPOSE2(true_divide_, Scalar); + + // multiply, alias for mul + OP_DECOMPOSE2(multiply, Tensor) + OP_DECOMPOSE2(multiply_, Tensor) + OP_DECOMPOSE2(multiply, Scalar) + OP_DECOMPOSE2(multiply_, Scalar) + + OP_DECOMPOSE2(linalg_matrix_rank, atol_rtol_tensor); + OP_DECOMPOSE2(linalg_matrix_rank, atol_rtol_float); + OP_DECOMPOSE(linalg_ldl_factor); + + // comparison ops + OP_DECOMPOSE2(greater, Scalar); + OP_DECOMPOSE2(less_equal, Scalar); + OP_DECOMPOSE2(less, Scalar); + OP_DECOMPOSE2(not_equal, Scalar); + m.impl("_has_compatible_shallow_copy_type", torch::CppFunction::makeFromBoxedFunction<&unsupportedData>()); + + // to.* + OP_DECOMPOSE2(to, device); + OP_DECOMPOSE2(to, dtype); + OP_DECOMPOSE2(to, dtype_layout); + OP_DECOMPOSE2(to, other); + + // Random ops that are also registered here + OP_DECOMPOSE(dropout); + OP_DECOMPOSE(_scaled_dot_product_attention_math); + OP_DECOMPOSE(scaled_dot_product_attention); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesDynamic.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesDynamic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8360757767b956629d5d35c63cecbebf4b66c064 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesDynamic.cpp @@ -0,0 +1,79 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include + +// This file contains batching rules for operations that return Tensors of +// dynamic shape. We generally don't support those with vmap so we raise +// errors for them. + + +namespace at::functorch { + +namespace { +void unsupportedDynamicOp(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, "vmap: We do not support batching operators that can output dynamic shape. ", + "Attempted to vmap over ", op.schema().operator_name(), ". ", + "Please file an issue at https://github.com/pytorch/pytorch/issues ", + "if you need this feature."); +} +#define UNSUPPORTED_DYNAMIC(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction<&unsupportedDynamicOp>()); + +// NB: item and is_nonzero can decompose to this... +void unsupportedLocalScalarDense(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, + "vmap: It looks like you're either (1) calling .item() on a Tensor or ", + "(2) attempting to use a Tensor in some data-dependent control flow or ", + "(3) encountering this error in PyTorch internals. ", + "For (1): we don't support vmap over calling .item() on a Tensor, please try to ", + "rewrite what you're doing with other operations. ", + "For (2): we don't support data-dependent control flow in vmap yet, ", + "please file an issue at https://github.com/pytorch/pytorch/issues . ", + "For (3): please file an issue."); +} + +void unsupportedItem(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, + "vmap: It looks like you're calling .item() on a Tensor. ", + "We don't support vmap over calling .item() on a Tensor, please try to ", + "rewrite what you're doing with other operations. If error is occurring ", + "somewhere inside PyTorch internals, please file a bug report."); +} + +void unsupportedIsNonzero(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, + "vmap: It looks like you're attempting to use a Tensor in some ", + "data-dependent control flow. ", + "We don't support that yet, please file an issue at ", + "https://github.com/pytorch/pytorch/issues ."); +} + +void unsupportedAllclose(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, + "vmap over torch.allclose isn't supported yet. Please file an issue ", + "at https://github.com/pytorch/pytorch/issues if you need this feature."); +} +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + UNSUPPORTED_DYNAMIC(nonzero); + UNSUPPORTED_DYNAMIC(where); + UNSUPPORTED_DYNAMIC(unique_dim); + UNSUPPORTED_DYNAMIC(unique_consecutive); + UNSUPPORTED_DYNAMIC(unique_dim_consecutive); + UNSUPPORTED_DYNAMIC(_unique2); + m.impl("_local_scalar_dense", torch::CppFunction::makeFromBoxedFunction<&unsupportedLocalScalarDense>()); + m.impl("item", torch::CppFunction::makeFromBoxedFunction<&unsupportedItem>()); + m.impl("is_nonzero", torch::CppFunction::makeFromBoxedFunction<&unsupportedIsNonzero>()); + m.impl("allclose", torch::CppFunction::makeFromBoxedFunction<&unsupportedAllclose>()); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesFactory.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ba8c59d001adaaea070bc439fa4fd9d004d304a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesFactory.cpp @@ -0,0 +1,247 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +namespace at::functorch { + +template +struct NewBlahBatchRuleHelperSymInt; + +template +struct NewBlahBatchRuleHelperSymInt> { + static std::tuple> apply( + const Tensor& tensor, + std::optional batch_dim, + SymIntArrayRef shape, + T... extra_args) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + const auto bdim_size = tensor.sym_size(batch_dim.value()); + c10::SmallVector new_shape; + new_shape.reserve(shape.size() + 1); + new_shape.emplace_back(bdim_size); + new_shape.insert(new_shape.end(), shape.begin(), shape.end()); + return std::make_tuple(Func(tensor, new_shape, std::forward(extra_args)...), 0); + } +}; + +template +struct NewBlahBatchRuleHelper; + +template +struct NewBlahBatchRuleHelper> { + static std::tuple> apply( + const Tensor& tensor, + std::optional batch_dim, + IntArrayRef shape, + T... extra_args) { + const auto bdim_size = tensor.size(batch_dim.value()); + VmapDimVector new_shape; + new_shape.reserve(shape.size() + 1); + new_shape.emplace_back(bdim_size); + new_shape.insert(new_shape.end(), shape.begin(), shape.end()); + return std::make_tuple(Func(tensor, new_shape, std::forward(extra_args)...), 0); + } +}; + +// USAGE: NEW_BLAH_BATCH_RULE(at::new_zeros) +// INCORRECT USAGE: NEW_BLAH_BATCH_RULE(&at::new_zeros) +// It is important that this macro is not passed a function pointer!! +#define NEW_BLAH_BATCH_RULE(fn) SINGLE_ARG(\ + NewBlahBatchRuleHelper<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + +#define NEW_BLAH_BATCH_RULE_SYMINT(fn) SINGLE_ARG(\ + NewBlahBatchRuleHelperSymInt<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + +static std::tuple> _new_zeros_with_same_feature_meta_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& other, std::optional other_bdim, + int64_t self_num_batch_dims) { + // The "self, other" naming is too confusing + // What this function really says is "create a new tangent for this base". + const auto& base = other; + const auto& base_bdim = other_bdim; + const auto& tangent = self; + const auto& tangent_bdim = self_bdim; + + // Three case: + // Case 1 Case 2 Case 3 + // base [6] [B, 6] [B, 6] + // tangent [B, 5] [5] [B, 5] + // result [B, 6] [B, 6] [B, 6] + + // Case 2 & 3 + if (base_bdim) { + auto base_ = moveBatchDimToFront(base, base_bdim); + Tensor tangent_ = tangent; + if (tangent_bdim.has_value()) { + // tangent [B, K0, K1, 5] + // base_ [B, 6] + // We want to move B to after the Ks, so that self_num_batch_dims + // (which really means tangent_num_batch_dims) isn't interfered with. + // [B, K0, K1, 6] -> [K0, K1, B, 6] + // + // [K0, K1, B, 6], [B, 5], 2 -> [K0, K1, B, 5] + tangent_ = tangent.movedim(*tangent_bdim, self_num_batch_dims); + } + auto result = at::_new_zeros_with_same_feature_meta(tangent_, base_, self_num_batch_dims); + return std::make_tuple(std::move(result), self_num_batch_dims); + } + + // Case 1: + auto tangent_ = moveBatchDimToFront(tangent, tangent_bdim); + auto result = at::_new_zeros_with_same_feature_meta(tangent_, base, self_num_batch_dims + 1); + return std::make_tuple(std::move(result), 0); +} + +static std::tuple> linspace_logspace_batch_rule_helper( + const at::Tensor& start, std::optional start_bdim, + const at::Tensor& end, std::optional end_bdim, + int64_t steps, + std::optional base, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory) +{ + auto batch_size = get_bdim_size2(start, start_bdim, end, end_bdim); + auto start_ = ensure_has_bdim(start, start_bdim.has_value(), batch_size); + auto end_ = ensure_has_bdim(end, end_bdim.has_value(), batch_size); + start_ = moveBatchDimToFront(start_, start_bdim); + end_ = moveBatchDimToFront(end_, end_bdim); + + auto tensor_options = at::TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory); + + Tensor result; + if (steps == 0){ + result = at::full({batch_size, 0}, 0, tensor_options); + } else if (steps == 1){ + result = start_.new_empty({batch_size}, tensor_options).copy_(start_).unsqueeze(1); + } else { + result = (start_ + at::arange(0, steps, tensor_options).unsqueeze_(1) * (end_ - start_) / (steps - 1)).transpose(0, 1); + } + + if (base){ + result = at::pow(*base, result); + } + + if (dtype && result.scalar_type() != *dtype){ + result = result.to(*dtype); + } + + return std::make_tuple(std::move(result), 0); +} + +static std::tuple> linspace_Tensor_Tensor_batch_rule( + const at::Tensor& start, std::optional start_bdim, + const at::Tensor& end, std::optional end_bdim, + int64_t steps, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory){ + return linspace_logspace_batch_rule_helper(start, start_bdim, end, end_bdim, steps, std::nullopt, dtype, layout, device, pin_memory); +} + +static std::tuple> linspace_Tensor_Scalar_batch_rule( + const at::Tensor& start, std::optional start_bdim, + const at::Scalar& end, + int64_t steps, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory){ + + auto end_t = at::native::wrapped_scalar_tensor(end, start.device()); + return linspace_logspace_batch_rule_helper(start, start_bdim, end_t, std::nullopt, steps, std::nullopt, dtype, layout, device, pin_memory); +} + +static std::tuple> linspace_Scalar_Tensor_batch_rule( + const at::Scalar& start, + const at::Tensor& end, std::optional end_bdim, + int64_t steps, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory){ + + auto start_t = at::native::wrapped_scalar_tensor(start, end.device()); + return linspace_logspace_batch_rule_helper(start_t, std::nullopt, end, end_bdim, steps, std::nullopt, dtype, layout, device, pin_memory); +} + +static std::tuple> logspace_Tensor_Tensor_batch_rule( + const at::Tensor& start, std::optional start_bdim, + const at::Tensor& end, std::optional end_bdim, + int64_t steps, + double base, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory){ + return linspace_logspace_batch_rule_helper(start, start_bdim, end, end_bdim, steps, base, dtype, layout, device, pin_memory); +} + +static std::tuple> logspace_Tensor_Scalar_batch_rule( + const at::Tensor& start, std::optional start_bdim, + const at::Scalar& end, + int64_t steps, + double base, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory){ + + auto end_t = at::native::wrapped_scalar_tensor(end, start.device()); + return linspace_logspace_batch_rule_helper(start, start_bdim, end_t, std::nullopt, steps, base, dtype, layout, device, pin_memory); +} + +static std::tuple> logspace_Scalar_Tensor_batch_rule( + const at::Scalar& start, + const at::Tensor& end, std::optional end_bdim, + int64_t steps, + double base, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory){ + + auto start_t = at::native::wrapped_scalar_tensor(start, end.device()); + return linspace_logspace_batch_rule_helper(start_t, std::nullopt, end, end_bdim, steps, base, dtype, layout, device, pin_memory); +} + +static bool _has_same_storage_numel_batch_rule(const Tensor& a, const Tensor& b) { + return true; +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + m.impl("_has_same_storage_numel", _has_same_storage_numel_batch_rule); + VMAP_SUPPORT(ones_like, BASIC_UNARY_BATCH_RULE(ATEN_FN(ones_like))); + VMAP_SUPPORT(zeros_like, BASIC_UNARY_BATCH_RULE(ATEN_FN(zeros_like))); + VMAP_SUPPORT(empty_like, BASIC_UNARY_BATCH_RULE(ATEN_FN(empty_like))); + VMAP_SUPPORT(randn_like, BASIC_UNARY_BATCH_RULE(ATEN_FN(randn_like))); + VMAP_SUPPORT(rand_like, BASIC_UNARY_BATCH_RULE(ATEN_FN(rand_like))); + VMAP_SUPPORT(full_like, BASIC_UNARY_BATCH_RULE(ATEN_FN(full_like))); + VMAP_SUPPORT(new_empty, NEW_BLAH_BATCH_RULE_SYMINT(ATEN_FN(new_empty))); + VMAP_SUPPORT(new_zeros, NEW_BLAH_BATCH_RULE_SYMINT(ATEN_FN(new_zeros))); + VMAP_SUPPORT(new_ones, NEW_BLAH_BATCH_RULE_SYMINT(ATEN_FN(new_ones))); + VMAP_SUPPORT(new_full, NEW_BLAH_BATCH_RULE_SYMINT(ATEN_FN(new_full))); + VMAP_SUPPORT2(linspace, Tensor_Tensor, linspace_Tensor_Tensor_batch_rule); + VMAP_SUPPORT2(linspace, Tensor_Scalar, linspace_Tensor_Scalar_batch_rule); + VMAP_SUPPORT2(linspace, Scalar_Tensor, linspace_Scalar_Tensor_batch_rule); + VMAP_SUPPORT2(logspace, Tensor_Tensor, logspace_Tensor_Tensor_batch_rule); + VMAP_SUPPORT2(logspace, Tensor_Scalar, logspace_Tensor_Scalar_batch_rule); + VMAP_SUPPORT2(logspace, Scalar_Tensor, logspace_Scalar_Tensor_batch_rule); + VMAP_SUPPORT(_new_zeros_with_same_feature_meta, _new_zeros_with_same_feature_meta_batch_rule); + // Not sure how to add the ones with irregular args to the mix cleanly (i.e. randint takes an extra int parameter) +} +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesHelper.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1fb5c1e1250614d84ff8e2feb92c1ad6bae61da --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesHelper.cpp @@ -0,0 +1,205 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +namespace at::functorch { + +Tensor moveBatchDimToFront(Tensor tensor, std::optional maybe_batch_dim) { + if (!maybe_batch_dim.has_value()) { + return tensor; + } + if (maybe_batch_dim.value() == 0) { + return tensor; + } + return tensor.movedim(maybe_batch_dim.value(), 0); +} + +int64_t rankWithoutBatchDim(const Tensor& tensor, std::optional maybe_batch_dim) { + int64_t result = tensor.dim(); + if (maybe_batch_dim.has_value()) { + result -= 1; + } + return result; +} + +int64_t numelWithoutBatchDim(const Tensor& tensor, std::optional maybe_batch_dim) { + if (!maybe_batch_dim) { + return tensor.numel(); + } + return tensor.numel() / tensor.size(*maybe_batch_dim); +} + +std::optional valIfNonempty(std::optional maybe_empty, int64_t new_val) { + if (maybe_empty.has_value()) { + return new_val; + } + return std::nullopt; +} + +int64_t getPhysicalDim(const Tensor& tensor, bool has_batch_dim, int64_t logical_dim) { + // NB: assumes the batch dim is at the front of the tensor + std::optional bdim = has_batch_dim ? std::optional(0) : std::nullopt; + auto rank = rankWithoutBatchDim(tensor, bdim); + auto wrapped_dim = maybe_wrap_dim(logical_dim, rank); + if (has_batch_dim) { + return wrapped_dim + 1; + } + return wrapped_dim; +} + +VmapDimVector getPhysicalDims(const Tensor& tensor, bool has_batch_dim, IntArrayRef logical_dims) { + // NB: assumes the batch dim is at the front of the tensor + std::optional bdim = has_batch_dim ? std::optional(0) : std::nullopt; + auto rank = rankWithoutBatchDim(tensor, bdim); + VmapDimVector result; + result.reserve(logical_dims.size()); + for (auto d : logical_dims){ + if (has_batch_dim) { + result.push_back(maybe_wrap_dim(d, rank)+1); + } else { + result.push_back(maybe_wrap_dim(d, rank)); + } + } + return result; +} + +Tensor maybePadToLogicalRank(const Tensor& tensor, std::optional has_bdim, int64_t logical_rank) { + if (!has_bdim) { + return tensor; + } + auto tensor_logical_rank = rankWithoutBatchDim(tensor, has_bdim); + if (tensor_logical_rank >= logical_rank) { + return tensor; + } + VmapSymDimVector new_sizes(tensor.sym_sizes().begin(), tensor.sym_sizes().end()); + for (int64_t i = 0; i < logical_rank - tensor_logical_rank; i++) { + new_sizes.insert(new_sizes.begin() + 1, 1); + } + return tensor.view_symint(SymIntArrayRef{new_sizes.begin(), new_sizes.end()}); +} + +void check_randomness(RandomnessType randomness, bool any_tensor_batched) { + TORCH_CHECK( + randomness != RandomnessType::Error, + "vmap: called random operation while in randomness error mode. Please either use the " + "'same' or 'different' randomness flags on vmap or perform the randomness operation out of vmap" + ); + + TORCH_CHECK( + !(randomness == RandomnessType::Same && any_tensor_batched), + "Vmap does not currently support same randomness with a batched tensor input. ", + "Please file an issue with functorch" + ) +} + +void check_randomness(RandomnessType randomness) { + check_randomness(randomness, false); // for ops that don't take in any tensors, don't hit same error +} + +Tensor reshape_dim_into(int64_t src, int64_t dst, const Tensor& x) { + auto x_dim = x.dim(); + src = maybe_wrap_dim(src, x_dim); + dst = maybe_wrap_dim(dst, x_dim - 1); // Returned Tensor has one fewer dim + VmapDimVector new_shape(x.sizes().begin(), x.sizes().end()); + new_shape.erase(new_shape.begin() + src); + new_shape[dst] *= x.sizes()[src]; + return at::reshape(x.movedim(src, dst), new_shape); +} + +Tensor reshape_dim_outof(int64_t src, int64_t size1, const Tensor& x) { + src = maybe_wrap_dim(src, x.dim()); + VmapDimVector shape(x.sizes().begin(), x.sizes().end()); + if (shape[src] != 0) { + // NOTE: 0 % 0 leads to FPE + TORCH_INTERNAL_ASSERT(shape[src] % size1 == 0); + } + // split any size out of `0`-sized dim + int64_t size2 = 0; + if (shape[src] != 0) { + size2 = shape[src] / size1; + } + shape[src] = size1; + shape.insert(shape.begin() + src + 1, size2); + return at::reshape(x, shape); +} + +Tensor reshape_dim_outof_symint(int64_t src, const c10::SymInt& size1, const Tensor& x) { + src = maybe_wrap_dim(src, x.dim()); + c10::SymDimVector shape(x.sym_sizes().begin(), x.sym_sizes().end()); + if (shape[src] != 0) { + // NOTE: 0 % 0 leads to FPE + TORCH_INTERNAL_ASSERT(shape[src] % size1 == 0); + } + c10::SymInt size2; + // split any size out of `0`-sized dim + if (shape[src] == 0) { + size2 = 0; + } else { + size2 = shape[src] / size1; + } + shape[src] = size1; + shape.insert(shape.begin() + src + 1, size2); + return at::reshape_symint(x, shape); +} + +void vmapIncompatibleInplaceError(const char* schema_name) { + TORCH_CHECK(false, + "vmap: ", schema_name, "(self, *extra_args) is not possible because ", + "there exists a Tensor `other` in extra_args that has more elements ", + "than `self`. This happened due to `other` being vmapped over but ", + "`self` not being vmapped over in a vmap. ", + "Please try to use out-of-place operators instead of ", schema_name, ". ", + "If said operator is being called inside the PyTorch framework, ", + "please file a bug report instead."); +} + +static void handleScalarTypePromotion(Tensor& logical_scalar_tensor, Tensor& second) { + auto result_type = at::native::result_type(logical_scalar_tensor[0], second); + if (logical_scalar_tensor.scalar_type() != result_type) { + logical_scalar_tensor = logical_scalar_tensor.to(result_type); + } + if (second.scalar_type() != result_type) { + second = second.to(result_type); + } +} + +std::tuple _binary_pointwise_helper( + const Tensor& tensor, std::optional tensor_batch_dim, + const Tensor& other, std::optional other_batch_dim, + bool do_type_promotion) { + // compute max logical rank + auto tensor_logical_rank = rankWithoutBatchDim(tensor, tensor_batch_dim); + auto other_logical_rank = rankWithoutBatchDim(other, other_batch_dim); + auto max_logical_rank = std::max(tensor_logical_rank, other_logical_rank); + + auto tensor_ = moveBatchDimToFront(tensor, tensor_batch_dim); + auto other_ = moveBatchDimToFront(other, other_batch_dim); + + // In the (0D, ND) case, type promotion semantics are different :/ + if (do_type_promotion) { + auto tensor_is_logical_scalar = (tensor_logical_rank == 0 && tensor_batch_dim.has_value()); + auto other_is_logical_scalar = (other_logical_rank == 0 && other_batch_dim.has_value()); + if (tensor_is_logical_scalar && !other_is_logical_scalar) { + handleScalarTypePromotion(tensor_, other_); + } + if (other_is_logical_scalar && !tensor_is_logical_scalar) { + handleScalarTypePromotion(other_, tensor_); + } + } + + // If the dimensions aren't aligned, we need to line them up. + // Tensor[B, 3] + Tensor[2, 5, 3] -> Tensor[B, 1, 1, 3] + Tensor[2, 5, 3] + // Note that only tensors that have a batch dim need to be modified. + // Tensor[B, 2, 3, 5] + Tensor[5] -> no changes needed + tensor_ = maybePadToLogicalRank(tensor_, tensor_batch_dim, max_logical_rank); + other_ = maybePadToLogicalRank(other_, other_batch_dim, max_logical_rank); + + return std::make_tuple(std::move(tensor_), std::move(other_)); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesHelper.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..01730cc24f5a640f6c50df144ae190316f7e0af6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesHelper.h @@ -0,0 +1,483 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. +#pragma once + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// This file contains helper functions for batching rules. + +namespace at::functorch { + +TORCH_API Tensor reshape_dim_into(int64_t src, int64_t dst, const Tensor& x); +TORCH_API Tensor reshape_dim_outof(int64_t src, int64_t size1, const Tensor& x); + +TORCH_API Tensor reshape_dim_outof_symint(int64_t src, const c10::SymInt& size1, const Tensor& x); + +Tensor moveBatchDimToFront(Tensor tensor, std::optional maybe_batch_dim); +int64_t rankWithoutBatchDim(const Tensor& tensor, std::optional maybe_batch_dim); +int64_t numelWithoutBatchDim(const Tensor& tensor, std::optional maybe_batch_dim); +std::optional valIfNonempty(std::optional maybe_empty, int64_t new_val); +int64_t getPhysicalDim(const Tensor& tensor, bool has_batch_dim, int64_t logical_dim); +VmapDimVector getPhysicalDims(const Tensor& tensor, bool has_batch_dim, IntArrayRef logical_dims); + +void vmapIncompatibleInplaceError(const char* schema_name); + +Tensor maybePadToLogicalRank(const Tensor& tensor, std::optional has_bdim, int64_t logical_rank); + +void check_randomness(RandomnessType randomness); +void check_randomness(RandomnessType randomness, bool any_tensor_bdim); + +inline Tensor ensure_has_bdim(const Tensor& tensor, bool has_bdim, c10::SymInt batch_size) { + if (has_bdim) { + return tensor; + } + const auto sizes = tensor.sym_sizes(); + SymDimVector expanded_shape; + expanded_shape.reserve(sizes.size()); + expanded_shape.emplace_back(std::move(batch_size)); + expanded_shape.insert(expanded_shape.end(), sizes.begin(), sizes.end()); + return tensor.expand_symint(expanded_shape); +} + +#define VMAP_SUPPORT(op, batch_rule) \ + m.impl(#op, op ## _generated_plumbing); + +#define VMAP_SUPPORT2(op, overload, batch_rule) \ + m.impl(#op "." #overload, op ## _ ## overload ## _generated_plumbing); + +#define OP_DECOMPOSE(op) m.impl(#op, static_cast(native::op)); +#define OP_DECOMPOSE2(op, overload) m.impl(#op"."#overload, static_cast(native::op)); + +// DO NOT USE ME DIRECTLY! Use BASIC_UNARY_BATCH_RULE to save yourself some pain +template +struct BasicUnaryBatchRuleHelper; + +template +struct BasicUnaryBatchRuleHelper> { + static std::tuple> apply( + const Tensor& tensor, + std::optional batch_dim, + T... extra_args) { + return std::make_tuple(Func(tensor, std::forward(extra_args)...), batch_dim); + } +}; + +// USAGE: BASIC_UNARY_BATCH_RULE(at::sin) +// INCORRECT USAGE: BASIC_UNARY_BATCH_RULE(&at::sin) +// It is important that this macro is not passed a function pointer!! +#define BASIC_UNARY_BATCH_RULE(fn) SINGLE_ARG(\ + BasicUnaryBatchRuleHelper<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + +#define UNARY_POINTWISE(op) \ + VMAP_SUPPORT(op, BASIC_UNARY_BATCH_RULE(ATEN_FN(op))); + +template +struct VariadicBdimsBatchRuleHelper; + +template +struct VariadicBdimsBatchRuleHelper> { + static std::tuple> apply( + const Tensor& tensor, + std::optional batch_dim, + T... extra_args) { + auto tensor_ = moveBatchDimToFront(tensor, batch_dim); + return std::make_tuple(Func(tensor_, std::forward(extra_args)...), 0); + } +}; + +// USAGE: VARIADIC_BDIMS_BATCH_RULE(at::cholesky_inverse) +// INCORRECT USAGE: VARIADIC_BDIMS_BATCH_RULE(&at::cholesky_inverse) +// It is important that this macro is not passed a function pointer!! +#define VARIADIC_BDIMS_BATCH_RULE(fn) SINGLE_ARG(\ + VariadicBdimsBatchRuleHelper<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + +#define VARIADIC_BDIMS(op) \ + VMAP_SUPPORT(op, VARIADIC_BDIMS_BATCH_RULE(ATEN_FN(op))); + +#define VARIADIC_BDIMS2(op, overload) \ + VMAP_SUPPORT2(op, overload, VARIADIC_BDIMS_BATCH_RULE(ATEN_FN2(op, overload))); + +template +void boxed_tensor_inputs_batch_rule(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + const auto num_arguments = schema.arguments().size(); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "boxed_tensor_inputs_batch_rule"); + + int64_t cur_level = maybe_layer->layerId(); + + auto orig_arguments = torch::jit::last(*stack, num_arguments); + if (std::none_of(orig_arguments.begin(), orig_arguments.end(), ivalueParticipatesInCurrentLevel)) { + op.callBoxed(stack); + return; + } + + auto arguments = torch::jit::pop(*stack, num_arguments); + std::vector>> tensor_inputs; + std::vector tensor_pos; + tensor_inputs.reserve(num_arguments); + tensor_pos.reserve(num_arguments); + for (const auto idx : c10::irange(0, num_arguments)) { + const auto& ivalue = arguments[idx]; + if (ivalue.isTensor()) { + auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(ivalue.toTensor(), cur_level); + tensor_inputs.emplace_back(std::move(tensor_value), tensor_bdim); + tensor_pos.push_back(static_cast(idx)); + } + } + Func(tensor_inputs); + + size_t tensor_idx = 0; + TORCH_INTERNAL_ASSERT(!tensor_pos.empty()); + for (const auto arg_idx : c10::irange(0, num_arguments)) { + if (tensor_idx >= tensor_pos.size() || (int64_t)arg_idx != tensor_pos[tensor_idx]) { + torch::jit::push(stack, arguments[arg_idx]); + } else { + TORCH_INTERNAL_ASSERT(tensor_idx < tensor_inputs.size()); + torch::jit::push(stack, tensor_inputs[tensor_idx].first); + tensor_idx++; + } + } + + op.callBoxed(stack); + const auto returns = torch::jit::pop(*stack, num_returns); + for (const auto& ret : returns) { + if (ret.isTensor()) { + torch::jit::push(stack, makeBatched(ret.toTensor(), 0, cur_level)); + } else { + TORCH_INTERNAL_ASSERT(false, "This boxed batching rule does not currently support ops that return non-tensor values"); + } + } +} + +inline void handle_pointwise_ops(std::vector>> &tensor_inputs) { + int64_t out_logical_rank = 0; + for (auto& tensor_input : tensor_inputs) { + int64_t cur_logical_rank = rankWithoutBatchDim(tensor_input.first, tensor_input.second); + out_logical_rank = std::max(out_logical_rank, cur_logical_rank); + } + for (auto& tensor_input: tensor_inputs) { + tensor_input.first = moveBatchDimToFront(tensor_input.first, tensor_input.second); + tensor_input.first = maybePadToLogicalRank(tensor_input.first, tensor_input.second, out_logical_rank); + } +} + +#define POINTWISE_BOXED(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction>()); + +#define POINTWISE_BOXED2(op, overload) \ + m.impl(#op "." #overload, torch::CppFunction::makeFromBoxedFunction>()); + +inline void handle_variadic_bdims(std::vector>> &tensor_inputs) { + for (auto & tensor_input : tensor_inputs) { + tensor_input.first = moveBatchDimToFront(tensor_input.first, tensor_input.second); + } +} + +#define VARIADIC_BDIMS_BOXED(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction>()); + +using UnpackedBatchedTensor = std::tuple>; + +inline void find_and_unpack_tensors( + const torch::jit::Stack* stack, + int64_t num_args, + int64_t cur_level, + SmallVector* tensors, + SmallVector* tensors_pos, + int64_t* batch_size) { + + int64_t computed_batch_size = -1; + int64_t args_begin = static_cast(stack->size()) - num_args; + + for (const auto idx : c10::irange(0, num_args)) { + const auto& ivalue = (*stack)[args_begin + idx]; + if (!ivalue.isTensor()) { + continue; + } + auto unpacked = unwrapTensorAtLevel(ivalue.toTensor(), cur_level); + const auto& [tensor_value, tensor_bdim] = unpacked; + if (tensor_bdim.has_value()) { + auto candidate_batch_size = tensor_value.size(*tensor_bdim); + if (computed_batch_size == -1) { + computed_batch_size = candidate_batch_size; + } + TORCH_INTERNAL_ASSERT(candidate_batch_size == computed_batch_size); + } + + tensors->push_back(std::move(unpacked)); + tensors_pos->push_back(idx); + } + TORCH_INTERNAL_ASSERT(computed_batch_size > -1); + *batch_size = computed_batch_size; +} + +inline void boxed_existing_bdim_all_batch_rule( + const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + const auto num_arguments = static_cast(schema.arguments().size()); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + const auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "boxed_existing_bdim_all_batch_rule"); + + const auto arguments = torch::jit::last(stack, num_arguments); + if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) { + op.callBoxed(stack); + return; + } + + int64_t args_begin = static_cast(stack->size()) - num_arguments; + SmallVector tensor_inputs; + SmallVector tensor_pos; + int64_t batch_size = 0; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + find_and_unpack_tensors( + stack, num_arguments, cur_level, + &tensor_inputs, &tensor_pos, &batch_size); + + // for each tensor, ensure it has a bdim and reshape it. + for (const auto tensor_idx : c10::irange(0, tensor_inputs.size())) { + const auto& [value, bdim] = tensor_inputs[tensor_idx]; + auto value_ = ensure_has_bdim(value, bdim.has_value(), batch_size); + (*stack)[args_begin + tensor_pos[tensor_idx]] = reshape_dim_into(bdim.value_or(0), 0, value_); + } + + op.callBoxed(stack); + + for (const auto idx : c10::irange(args_begin, args_begin + num_returns)) { + const auto& ret = (*stack)[idx]; + TORCH_INTERNAL_ASSERT(ret.isTensor(), + "This boxed batching rule does not currently support ops that return non-tensor values"); + (*stack)[idx] = makeBatched(reshape_dim_outof(0, batch_size, ret.toTensor()), 0, cur_level); + } +} + +// Use when all tensors arguments accept one (normal) batch dim. +// This batching rule expands the batch dim on all Tensors, reshapes it into +// dim 0, calls the op, and then reshapes the batch dim out of dim 0. +// This is not the most efficient thing; if there are alternatives, please try +// to use them. Use this only as a last resort. +#define EXISTING_BDIM_ALL_BOXED(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction()); + +template +inline void boxed_all_tensors_have_optional_bdim( + const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + const auto num_arguments = schema.arguments().size(); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "boxed_all_tensors_have_optional_bdim"); + int64_t cur_level = maybe_layer->layerId(); + + const auto arguments = torch::jit::last(stack, num_arguments); + if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) { + op.callBoxed(stack); + return; + } + + int64_t args_begin = static_cast(stack->size() - num_arguments); + SmallVector tensor_inputs; + SmallVector tensor_pos; + int64_t batch_size = 0; + + find_and_unpack_tensors( + stack, static_cast(num_arguments), cur_level, + &tensor_inputs, &tensor_pos, &batch_size); + + std::optional is_no_batch_dim_case; + + for (const auto tensor_idx : c10::irange(0, tensor_inputs.size())) { + const auto& value = std::get<0>(tensor_inputs[tensor_idx]); + auto bdim = std::get<1>(tensor_inputs[tensor_idx]); + const auto logical_rank = rankWithoutBatchDim(value, bdim); + + if (!is_no_batch_dim_case.has_value()) { + is_no_batch_dim_case = (logical_rank == feature_rank); + } + auto value_ = ensure_has_bdim(value, bdim.has_value(), batch_size); + if (!bdim.has_value()) { + bdim = 0; + } + if (*is_no_batch_dim_case) { + TORCH_INTERNAL_ASSERT(logical_rank == feature_rank); + value_ = moveBatchDimToFront(value_, bdim); + if (tensor_idx == contig_tensor_index) { + value_ = value_.contiguous(); + } + (*stack)[args_begin + tensor_pos[tensor_idx]] = std::move(value_); + continue; + } + TORCH_INTERNAL_ASSERT(logical_rank == feature_rank + 1); + value_ = reshape_dim_into(*bdim, 0, value_); + if (tensor_idx == contig_tensor_index) { + value_ = value_.contiguous(); + } + (*stack)[args_begin + tensor_pos[tensor_idx]] = std::move(value_); + } + + op.callBoxed(stack); + + for (const auto idx : c10::irange(args_begin, args_begin + num_returns)) { + const auto& ret = (*stack)[idx]; + TORCH_INTERNAL_ASSERT(ret.isTensor(), + "This boxed batching rule does not currently support ops that return non-tensor values"); + if (*is_no_batch_dim_case) { + (*stack)[idx] = makeBatched(ret.toTensor(), 0, cur_level); + } else { + (*stack)[idx] = makeBatched(reshape_dim_outof(0, batch_size, ret.toTensor()), 0, cur_level); + } + } +} + +// Useful for many NN operators. +// The operator must satisfy the following: +// - All arguments must accept an optional batch dim. +// - All arguments must be the same rank +#define ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED(feature_rank, op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction>()); + +#define ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(feature_rank, op, contig_tensor_index) \ + m.impl(#op, \ + torch::CppFunction::makeFromBoxedFunction<\ + boxed_all_tensors_have_optional_bdim<\ + feature_rank, \ + contig_tensor_index>\ + >()); + +template +struct ExistingBdimBatchRuleHelper; + +template +struct ExistingBdimBatchRuleHelper> { + static std::tuple> apply( + const Tensor& self, + std::optional self_bdim, + T... extra_args) { + auto self_ = reshape_dim_into(*self_bdim, 0, self); + auto out = Func(self_, std::forward(extra_args)...); + return std::make_tuple(reshape_dim_outof_symint(0, self.sym_sizes()[*self_bdim], out), 0); + } +}; + +// USAGE: EXISTING_BDIM_BATCH_RULE(at::cholesky_inverse) +// INCORRECT USAGE: EXISTING_BDIM_BATCH_RULE(&at::cholesky_inverse) +// It is important that this macro is not passed a function pointer!! +#define EXISTING_BDIM_BATCH_RULE(fn) SINGLE_ARG(\ + ExistingBdimBatchRuleHelper<\ + decltype(&fn),\ + &fn,\ + c10::guts::function_traits::parameter_types>::apply) + + +#define EXISTING_BDIM(op) \ + VMAP_SUPPORT(op, EXISTING_BDIM_BATCH_RULE(ATEN_FN(op))); + +#define EXISTING_BDIM2(op, overload) \ + VMAP_SUPPORT2(op, overload, EXISTING_BDIM_BATCH_RULE(ATEN_FN2(op, overload))); + +#define INVOKE(object,ptrToMember) ((object).*(ptrToMember)) + + +template +Tensor& unary_inplace_batch_rule(Tensor& self, std::optional /*unused*/, ExtraArgs... extra_args) { + INVOKE(self, Method)(std::forward(extra_args)...); + return self; +} + +inline int64_t get_bdim_size4( + const Tensor& a_value, std::optional a_bdim, + const Tensor& b_value, std::optional b_bdim, + const Tensor& c_value, std::optional c_bdim, + const Tensor& d_value, std::optional d_bdim) { + if (a_bdim) + return a_value.size(*a_bdim); + if (b_bdim) + return b_value.size(*b_bdim); + if (c_bdim) + return c_value.size(*c_bdim); + if (d_bdim) + return d_value.size(*d_bdim); + TORCH_INTERNAL_ASSERT(false); +} + +inline int64_t get_bdim_size3( + const Tensor& a_value, std::optional a_bdim, + const Tensor& b_value, std::optional b_bdim, + const Tensor& c_value, std::optional c_bdim) { + if (a_bdim) + return a_value.size(*a_bdim); + if (b_bdim) + return b_value.size(*b_bdim); + if (c_bdim) + return c_value.size(*c_bdim); + TORCH_INTERNAL_ASSERT(false); +} + +inline int64_t get_bdim_size2( + const Tensor& a_value, std::optional a_bdim, + const Tensor& b_value, std::optional b_bdim) { + if (a_bdim) + return a_value.size(*a_bdim); + if (b_bdim) + return b_value.size(*b_bdim); + TORCH_INTERNAL_ASSERT(false); +} + +inline c10::SymInt get_bdim_size2_symint( + const Tensor& a_value, std::optional a_bdim, + const Tensor& b_value, std::optional b_bdim) { + if (a_bdim) + return a_value.sym_size(*a_bdim); + if (b_bdim) + return b_value.sym_size(*b_bdim); + TORCH_INTERNAL_ASSERT(false); +} + +// [start, start + 1, ..., stop - 1] +inline VmapDimVector range(int64_t start, int64_t stop) { + TORCH_INTERNAL_ASSERT(stop >= start); + VmapDimVector dims; + dims.reserve(stop - start); + for (int64_t i = start; i < stop; i++) { + dims.emplace_back(i); + } + return dims; +} +std::tuple _binary_pointwise_helper( + const Tensor& tensor, std::optional tensor_batch_dim, const Tensor& other, std::optional other_batch_dim, + bool do_type_promotion=true); + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesIndexing.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesIndexing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9199ce2912920566122a8c3cea2fc292a279f62b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesIndexing.cpp @@ -0,0 +1,23 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +namespace at::functorch { + +#define OP_DECOMPOSE(op) m.impl(#op, static_cast(native::op)); +#define OP_DECOMPOSE2(op, overload) m.impl(#op"."#overload, static_cast(native::op)); + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + OP_DECOMPOSE2(_unsafe_index, Tensor); + OP_DECOMPOSE(_unsafe_masked_index); + OP_DECOMPOSE(_unsafe_index_put); + OP_DECOMPOSE(_unsafe_masked_index_put_accumulate); +} + +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesLinearAlgebra.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesLinearAlgebra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..680adb8db27f339ba341fee0396d763d3f5e47eb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesLinearAlgebra.cpp @@ -0,0 +1,869 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include + +#include + +namespace at::functorch { + +typedef std::tuple> oneOutput; +typedef std::tuple, Tensor, std::optional> twoOutputs; +typedef std::tuple, Tensor, std::optional, Tensor, std::optional> threeOutputs; +typedef std::tuple, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional> fourOutputs; + +namespace { + +// Note [Batching rules for matmul-like operators] +// at::matmul doesn't "de-expand" arguments to get better performance (maybe +// it should). In the batching rules for matmul-like operators (dot, mv, mm), +// we should be careful not to expand any unnecessary dimensions. i.e., if +// only one of the two arguments is a BatchedTensor, then we should try +// not to expand batch dimensions onto the other arg. + +std::tuple> dot_batch_rule(const Tensor& A, std::optional A_bdim, const Tensor& B, std::optional B_bdim) { + TORCH_CHECK(A.dim() - A_bdim.has_value() == 1 && B.dim() - B_bdim.has_value() == 1, "Got wrong shapes for dot"); + auto A_ = moveBatchDimToFront(A, A_bdim); + auto B_ = moveBatchDimToFront(B, B_bdim); + if (A_bdim && B_bdim) { + return std::make_tuple(at::matmul(A_.unsqueeze(-2), B_.unsqueeze(-1)).squeeze(-1).squeeze(-1), 0); + } else { + return std::make_tuple(at::matmul(A_, B_.t()), 0); + } +} +Tensor vdot_decomp(const Tensor& A, const Tensor& B) { + return at::dot(A.is_complex() ? A.conj() : A, B); +} + +// NB: I wrote this like this because we *might* want its for a future matmul +// batch rule that isn't decomposed... +// "tv" = tensor @ vector +std::tuple> tv_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& other, std::optional other_bdim) { + if (self_bdim && other_bdim) { + // See Note [Batching rules for matmul-like operators] + // B...OI, BI -> ...BOI, BI1 -> ...BO1 -> ...BO + auto self_ = at::movedim(self, *self_bdim, -3); + auto other_ = moveBatchDimToFront(other, other_bdim); + other_ = other_.unsqueeze(-1); + auto result = at::matmul(self_, other_).squeeze(-1); + auto result_bdim = result.dim() - 2; + return std::make_tuple( std::move(result), result_bdim ); + } + else if (self_bdim && !other_bdim) { + // B...OI, I -> B...O + auto self_ = moveBatchDimToFront(self, self_bdim); + return std::make_tuple( at::matmul(self_, other), 0 ); + } + else if (!self_bdim && other_bdim) { + // ...OI, BI -> ...OI, IB -> OB + auto other_ = at::movedim(other, *other_bdim, -1); + auto result = at::matmul(self, other_); + return std::make_tuple( std::move(result), 1 ); + } + TORCH_INTERNAL_ASSERT(false, "can't get here"); +} + +std::tuple> mv_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& other, std::optional other_bdim) { + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto other_logical_rank = rankWithoutBatchDim(other, other_bdim); + TORCH_CHECK(self_logical_rank == 2 && other_logical_rank == 1, + "Shape mismatch: ", + "Got incorrect dims for mv(a, b). a has dim ", self_logical_rank, + "and b has dim ", other_logical_rank, + "but expected them to have dim 2 and dim 1"); + return tv_batch_rule(self, self_bdim, other, other_bdim); +} + +std::tuple> mm_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& other, std::optional other_bdim) { + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto other_logical_rank = rankWithoutBatchDim(other, other_bdim); + TORCH_CHECK(self_logical_rank == 2 && other_logical_rank == 2, + "Shape mismatch: Got incorrect dims for mm(a, b). " + "a has dim ", self_logical_rank, + "and b has dim ", other_logical_rank, + "but expected them to have dim 2 and dim 2"); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto other_ = moveBatchDimToFront(other, other_bdim); + return std::make_tuple( at::matmul(self_, other_), 0 ); +} + +std::tuple> bmm_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& other, std::optional other_bdim) { + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto other_logical_rank = rankWithoutBatchDim(other, other_bdim); + TORCH_CHECK(self_logical_rank == 3 && other_logical_rank == 3, + "Shape mismatch: Got incorrect dims for bmm(a, b). " + "a has dim ", self_logical_rank, + "and b has dim ", other_logical_rank, + "but expected them to have dim 3 and dim 3"); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto other_ = moveBatchDimToFront(other, other_bdim); + return std::make_tuple( at::matmul(self_, other_), 0 ); +} + +// AFAICT, nothing here can be batched. So we decompose :) +Tensor addmv_decomp( + const Tensor& input, const Tensor& mat, const Tensor& vec, const Scalar& beta, const Scalar& alpha) { + Tensor out = at::mv(mat, vec); + if (!alpha.equal(1)) { + out = alpha * out; + } + if (!beta.equal(0)) { + out = beta * input + out; + } + return out; +} + +Tensor addbmm_decomp( + const Tensor& input, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha) { + Tensor out = at::bmm(batch1, batch2).sum(0); + if (!alpha.equal(1)) { + out = alpha * out; + } + if (!beta.equal(0)) { + out = beta * input + out; + } + return out; +} + +Tensor baddbmm_decomp( + const Tensor& input, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha) { + Tensor out = at::bmm(batch1, batch2); + if (!alpha.equal(1)) { + out = alpha * out; + } + if (!beta.equal(0)) { + out = beta * input + out; + } + return out; +} + +Tensor addmm_decomp(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha) { + // Decomposition that is probably not very fast... + return at::add(self * beta, at::mm(mat1, mat2), alpha); +} + +void _linalg_check_errors_batch_rule(const Tensor& info, std::optional info_bdim, std::string_view api_name, bool is_matrix) { + auto info_ = moveBatchDimToFront(info, info_bdim); + // Not a matrix means this is a batch of matrices + at::_linalg_check_errors(info_, api_name, false); +} + +std::tuple> +householder_product_batch_rule(const Tensor &input, std::optional input_bdim, + const Tensor &tau, std::optional tau_bdim) +{ + auto input_ = moveBatchDimToFront(input, input_bdim); + auto tau_ = moveBatchDimToFront(tau, tau_bdim); + + auto batch_size = get_bdim_size2(input, input_bdim, tau, tau_bdim); + + input_ = ensure_has_bdim(input_, input_bdim.has_value(), batch_size); + tau_ = ensure_has_bdim(tau_, tau_bdim.has_value(), batch_size); + return std::make_tuple(at::linalg_householder_product(input_, tau_), 0); +} + +template +struct LinalgCheckMatrixUnaryRuleHelper; + +template +struct LinalgCheckMatrixUnaryRuleHelper> { + static Tensor check_and_reshape_input(const Tensor& tensor, std::optional batch_dim) { + TORCH_CHECK(rankWithoutBatchDim(tensor, batch_dim) >= 2, op_name, ": The input tensor A must have at least 2 dimensions."); + return moveBatchDimToFront(tensor, batch_dim); + } + + static oneOutput apply_one( + const Tensor& tensor, + std::optional batch_dim, + T... extra_args) { + auto tensor_ = check_and_reshape_input(tensor, batch_dim); + return std::make_tuple(Func(std::move(tensor_), std::forward(extra_args)...), 0); + } + + static twoOutputs apply_two( + const Tensor& tensor, + std::optional batch_dim, + T... extra_args) { + auto tensor_ = check_and_reshape_input(tensor, batch_dim); + auto res = Func(std::move(tensor_), std::forward(extra_args)...); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0); + } + + static threeOutputs apply_three( + const Tensor& tensor, + std::optional batch_dim, + T... extra_args) { + auto tensor_ = check_and_reshape_input(tensor, batch_dim); + auto res = Func(std::move(tensor_), std::forward(extra_args)...); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0, std::move(std::get<2>(res)), 0); + } + + static fourOutputs apply_four( + const Tensor& tensor, + std::optional batch_dim, + T... extra_args) { + auto tensor_ = check_and_reshape_input(tensor, batch_dim); + auto res = Func(std::move(tensor_), std::forward(extra_args)...); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0, std::move(std::get<2>(res)), 0, std::get<3>(res), 0); + } +}; + +template +struct LinalgCheckMatrixBinaryRuleHelper; + +template +struct LinalgCheckMatrixBinaryRuleHelper> { + static std::tuple check_inputs_and_reshape_inputs( + const Tensor& first, std::optional first_bdim, + const Tensor& second, std::optional second_bdim) { + TORCH_CHECK(rankWithoutBatchDim(first, first_bdim) >= 2, + op_name, ": The input tensor A must have at least 2 dimensions."); + TORCH_CHECK(rankWithoutBatchDim(second, second_bdim) >= 2, + op_name, ": The input tensor B must have at least 2 dimensions."); + return _binary_pointwise_helper(first, first_bdim, second, second_bdim, false); + } + + static oneOutput apply_one( + const Tensor& first, std::optional first_bdim, + const Tensor& second, std::optional second_bdim, + T... extra_args) { + auto [tensor_, other_]= check_inputs_and_reshape_inputs(first, first_bdim, second, second_bdim); + return std::make_tuple(Func(std::move(tensor_), std::move(other_), std::forward(extra_args)...), 0); + } + + static twoOutputs apply_two( + const Tensor& first, std::optional first_bdim, + const Tensor& second, std::optional second_bdim, + T... extra_args) { + auto [tensor_, other_]= check_inputs_and_reshape_inputs(first, first_bdim, second, second_bdim); + auto res = Func(std::move(tensor_), std::move(other_), std::forward(extra_args)...); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0); + } +}; + +void expect_at_least_rank( + const Tensor& tensor, + std::optional tensor_bdim, + int64_t expected_rank, + const char* name) { + auto rank = rankWithoutBatchDim(tensor, tensor_bdim); + TORCH_CHECK(rank >= expected_rank, + name, " should have at least ", expected_rank, " dimensions, but has ", + rank, " dimensions instead."); +} + +threeOutputs linalg_lu_unpack_batch_rule( + const Tensor& LU, std::optional LU_bdim, + const Tensor& pivots, std::optional pivots_bdim, + bool unpack_data, bool unpack_pivots) { + auto LU_ = moveBatchDimToFront(LU, LU_bdim); + auto pivots_ = moveBatchDimToFront(pivots, pivots_bdim); + + // LU and pivots's first {N-2} (for LU), {N-1} (for pivots) dimensions must + // match So if only one of them is being vmapped over, we must expand out that + // dimension. + if (LU_bdim.has_value() != pivots_bdim.has_value()) { + auto bdim_size = get_bdim_size2(LU, LU_bdim, pivots, pivots_bdim); + LU_ = ensure_has_bdim(LU_, LU_bdim.has_value(), bdim_size); + pivots_ = ensure_has_bdim(pivots_, pivots_bdim.has_value(), bdim_size); + pivots_bdim = 0; + LU_bdim = 0; + } + + auto res = at::lu_unpack(LU_, pivots_, unpack_data, unpack_pivots); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0, std::move(std::get<2>(res)), 0); +} + +oneOutput linalg_lu_solve_batch_rule( + const Tensor& LU, std::optional LU_bdim, + const Tensor& pivots, std::optional pivots_bdim, + const Tensor& B, std::optional B_bdim, + bool left, bool adjoint) { + const auto LU_min_rank = 2; + const auto pivots_min_rank = 1; + const auto B_min_rank = 2; + + expect_at_least_rank(LU, LU_bdim, LU_min_rank, "LU"); + expect_at_least_rank(pivots, pivots_bdim, pivots_min_rank, "pivots"); + expect_at_least_rank(B, B_bdim, B_min_rank, "B"); + + auto LU_ = moveBatchDimToFront(LU, LU_bdim); + auto pivots_ = moveBatchDimToFront(pivots, pivots_bdim); + auto B_ = moveBatchDimToFront(B, B_bdim); + + // LU and pivots's first {N-2} (for LU), {N-1} (for pivots) dimensions must match + // So if only one of them is being vmapped over, we must expand out that dimension. + if (LU_bdim.has_value() ^ pivots_bdim.has_value()) { + auto bdim_size = get_bdim_size2(LU, LU_bdim, pivots, pivots_bdim); + LU_ = ensure_has_bdim(LU_, LU_bdim.has_value(), bdim_size); + pivots_ = ensure_has_bdim(pivots_, pivots_bdim.has_value(), bdim_size); + pivots_bdim = 0; + LU_bdim = 0; + } + + // Now, {LU, pivots} and B's first dimensions are allowed to broadcast. + // The rest of the logic handles that. + const auto LU_num_batch_dims = rankWithoutBatchDim(LU_, LU_bdim) - LU_min_rank; + const auto pivots_num_batch_dims = rankWithoutBatchDim(pivots_, pivots_bdim) - pivots_min_rank; + const auto B_num_batch_dims = rankWithoutBatchDim(B_, B_bdim) - B_min_rank; + const auto max_num_batch_dims = std::max({LU_num_batch_dims, pivots_num_batch_dims, B_num_batch_dims}); + + LU_ = maybePadToLogicalRank(LU_, LU_bdim, max_num_batch_dims + LU_min_rank); + pivots_ = maybePadToLogicalRank(pivots_, pivots_bdim, max_num_batch_dims + pivots_min_rank); + B_ = maybePadToLogicalRank(B_, B_bdim, max_num_batch_dims + B_min_rank); + + auto result = at::linalg_lu_solve(LU_, pivots_, B_, left, adjoint); + return std::make_tuple(std::move(result), 0); +} + +oneOutput cholesky_solve_batch_rule( + const Tensor& self, std::optional self_bdim, + const Tensor& A, std::optional A_bdim, + bool upper) { + TORCH_CHECK(rankWithoutBatchDim(self, self_bdim) >= 2, + "b should have at least 2 dimensions, but has ", self.dim(), " dimensions instead"); + TORCH_CHECK(rankWithoutBatchDim(A, A_bdim) >= 2, + "u should have at least 2 dimensions, but has ", A.dim(), " dimensions instead"); + + auto [tensor_, other_]= _binary_pointwise_helper(self, self_bdim, A, A_bdim, /*do_type_promotion=*/false); + return std::make_tuple(at::cholesky_solve(tensor_, other_, upper), 0); +} + +threeOutputs linalg_lu_factor_ex_batch_rule( + const Tensor& A, std::optional A_bdim, bool pivot, bool check_errors) { + TORCH_CHECK(rankWithoutBatchDim(A, A_bdim) >= 2, "torch.lu_factor_ex: Expected tensor with 2 or more dimensions. Got size: ", A.sizes(), " instead"); + const auto A_ = moveBatchDimToFront(A, A_bdim); + auto res = at::linalg_lu_factor_ex(A_, pivot, check_errors); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0, std::move(std::get<2>(res)), 0); +} + +oneOutput matrix_exp_batch_rule(const Tensor& self, std::optional self_bdim) { + TORCH_CHECK(rankWithoutBatchDim(self, self_bdim) >= 2, "torch.matrix_exp: The input tensor A must have at least 2 dimensions."); + const auto self_ = moveBatchDimToFront(self, self_bdim).contiguous(); // seems to be a bug + return std::make_tuple(at::matrix_exp(self_), 0); +} + +oneOutput matrix_sqrth_batch_rule(const Tensor& self, std::optional self_bdim) { + TORCH_CHECK(rankWithoutBatchDim(self, self_bdim) >= 2, "linalg.matrix_sqrth: The input tensor A must have at least 2 dimensions."); + const auto self_ = moveBatchDimToFront(self, self_bdim).contiguous(); + return std::make_tuple(at::linalg_matrix_sqrth(self_), 0); +} + +fourOutputs solve_ex_batch_rule( + const Tensor& A, std::optional A_bdim, + const Tensor& B, std::optional B_bdim, + bool left, bool check_errors) { + auto batch_size = get_bdim_size2(A, A_bdim, B, B_bdim); + const auto A_logical_rank = rankWithoutBatchDim(A, A_bdim); + const auto B_logical_rank = rankWithoutBatchDim(B, B_bdim); + const auto max_logical_rank = std::max(A_logical_rank, B_logical_rank); + + TORCH_CHECK(A_logical_rank >= 2, + "linalg.solve: The input tensor A must have at least 2 dimensions."); + + auto b_logical_rank = max_logical_rank; + if (A_logical_rank > B_logical_rank) { // vector case: B was a vector or batched vector + // not accurate but matches linalg error message + TORCH_CHECK(B_logical_rank >= 1, "linalg.solve: The input tensor B must have at least 2 dimensions."); + b_logical_rank = max_logical_rank - 1; + } else { // matrix case: A and B are both matrices or batches of matrices + TORCH_CHECK(B_logical_rank >= 2, "linalg.solve: The input tensor B must have at least 2 dimensions."); + } + + // basically binary pointwise helper but if B was a vector incoming, we must pad it to be 1 dim smaller than A + auto A_ = moveBatchDimToFront(A, A_bdim); + auto B_ = moveBatchDimToFront(B, B_bdim); + A_ = maybePadToLogicalRank(A_, A_bdim, max_logical_rank); + B_ = maybePadToLogicalRank(B_, B_bdim, b_logical_rank); + + A_ = ensure_has_bdim(A_, A_bdim.has_value(), batch_size); + B_ = ensure_has_bdim(B_, B_bdim.has_value(), batch_size); + + auto res = _linalg_solve_ex(A_, B_, left, check_errors); + return std::make_tuple(std::move(std::get<0>(res)), 0, std::move(std::get<1>(res)), 0, std::move(std::get<2>(res)), 0, std::move(std::get<3>(res)), 0); +} + +oneOutput cross_batch_rule(const Tensor& self, std::optional self_bdim, + const Tensor& other, std::optional other_bdim, const int64_t dim) { + // match cross dimension checks + TORCH_CHECK(rankWithoutBatchDim(self, self_bdim) == rankWithoutBatchDim(other, other_bdim), + "linalg.cross: inputs must have the same number of dimensions." + ); + + const auto batch_size = get_bdim_size2(self, self_bdim, other, other_bdim); + auto [self_, other_]= _binary_pointwise_helper(self, self_bdim, other, other_bdim, false); + + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + other_ = ensure_has_bdim(other_, other_bdim.has_value(), batch_size); + + const auto dim_ = getPhysicalDim(self_, true, dim); + + return std::make_tuple(linalg_cross(self_, other_, dim_), 0); +} + +std::optional batch_dim_if_not_empty(const Tensor& t) { + if (t.dim() == 1 && t.size(0) == 0) { + return std::optional(); + } + return std::optional(0); +} + +fourOutputs linalg_lstsq_batch_rule( + const Tensor& self, std::optional self_bdim, const Tensor& b, std::optional b_bdim, + std::optional rcond, std::optional driver) { + TORCH_CHECK(rankWithoutBatchDim(self, self_bdim) >= 2, "torch.linalg.lstsq: input must have at least 2 dimensions."); + TORCH_CHECK(rankWithoutBatchDim(b, b_bdim) >= 1, "torch.linalg.lstsq: other must have at least 1 dimension."); + + const auto batch_size = get_bdim_size2(self, self_bdim, b, b_bdim); + auto [self_, other] = _binary_pointwise_helper(self, self_bdim, b, b_bdim, /*do_type_promotion=*/false); + + // because of ambiguity with vector case, lstsq can broadcast [1, 2] -> [batch_size, 2] but not [2] -> [batch_size, 2] + // so could unsqueeze if there's no bdim or just ensure_has_bdim + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + other = ensure_has_bdim(other, b_bdim.has_value(), batch_size); + + auto [res, res_1, res_2, res_3] = at::linalg_lstsq(self_, other, rcond, driver); + + // everything but the 0th output are only sometimes computed. When they aren't, they're empty tensors without a bdim + const auto res_1_bdim = batch_dim_if_not_empty(res_1); + const auto res_2_bdim = batch_dim_if_not_empty(res_2); + const auto res_3_bdim = batch_dim_if_not_empty(res_3); + return std::make_tuple(std::move(res), 0, std::move(res_1), res_1_bdim, std::move(res_2), res_2_bdim, std::move(res_3), res_3_bdim); +} + +template +std::tuple> +atol_rtol_tensor_batch_rule( + F Func, const Tensor& input, std::optional input_bdim, + const std::optional& atol, const std::optional atol_bdim, + const std::optional& rtol, const std::optional rtol_bdim, bool hermitian, char const *op_name) { + auto input_logical_rank = rankWithoutBatchDim(input, input_bdim); + + TORCH_CHECK(input_logical_rank >= 2, + op_name, ": The input tensor input must have at least 2 dimensions."); + + // atol and rtol's dims must be broadcastable to the number of batch dims of input + // which is input's dim - 2 (input represents a batch of matrices, so 2 is for the matrix dimensions) + const auto input_logical_num_bdims = input_logical_rank - 2; + const int64_t atol_logical_num_bdims = atol.has_value() ? rankWithoutBatchDim(*atol, atol_bdim) : 0; + const int64_t rtol_logical_num_bdims = rtol.has_value() ? rankWithoutBatchDim(*rtol, rtol_bdim) : 0; + const auto max_logical_bdims = std::max({input_logical_num_bdims, atol_logical_num_bdims, rtol_logical_num_bdims}); + + auto input_ = moveBatchDimToFront(input, input_bdim); + auto atol_ = atol.has_value() ? moveBatchDimToFront(*atol, atol_bdim) : atol; + auto rtol_ = rtol.has_value() ? moveBatchDimToFront(*rtol, rtol_bdim) : rtol; + + // pad all inputs to have the same number of (non-vmap) batch dimensions + input_ = maybePadToLogicalRank(input_, input_bdim, max_logical_bdims + 2); + atol_ = atol_.has_value() ? maybePadToLogicalRank(*atol_, atol_bdim, max_logical_bdims) : atol_; + rtol_ = rtol_.has_value() ? maybePadToLogicalRank(*rtol_, rtol_bdim, max_logical_bdims) : rtol_; + + return std::make_tuple(Func(input_, atol_, rtol_, hermitian), 0); +} + +std::tuple> +pinv_batch_rule( + const Tensor& input, std::optional input_bdim, const std::optional& atol, + const std::optional atol_bdim, const std::optional& rtol, + const std::optional rtol_bdim, bool hermitian) { + return atol_rtol_tensor_batch_rule(ATEN_FN2(linalg_pinv, atol_rtol_tensor), input, input_bdim, atol, atol_bdim, rtol, rtol_bdim, hermitian, "linalg.pinv"); +} + +Tensor flatten_sdpa_attn_bias_for_vmap( + const Tensor& attn_bias, + std::optional attn_bias_bdim, + const c10::SymInt& batch_size) { + auto attn_bias_ = moveBatchDimToFront(attn_bias, attn_bias_bdim); + attn_bias_ = ensure_has_bdim(attn_bias_, attn_bias_bdim.has_value(), batch_size); + return attn_bias_.flatten(0, 1); +} + + +std::tuple, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional, SymInt, SymInt, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional> +_scaled_dot_product_flash_attention_batch_rule( + const Tensor& query, std::optional query_bdim, + const Tensor& key, std::optional key_bdim, + const Tensor& value, std::optional value_bdim, + double dropout_p, + bool is_causal, + bool return_debug_mask, + std::optional scale +) { + if (dropout_p > 0) { + auto maybe_layer = maybeCurrentDynamicLayer(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness, query_bdim.has_value() || key_bdim.has_value() || value_bdim.has_value()); + } + auto batch_size = get_bdim_size3(query, query_bdim, key, key_bdim, value, value_bdim); + auto query_ = moveBatchDimToFront(query, query_bdim); + auto key_ = moveBatchDimToFront(key, key_bdim); + auto value_ = moveBatchDimToFront(value, value_bdim); + query_ = ensure_has_bdim(query_, query_bdim.has_value(), batch_size); + key_ = ensure_has_bdim(key_, key_bdim.has_value(), batch_size); + value_ = ensure_has_bdim(value_, value_bdim.has_value(), batch_size); + query_ = query_.flatten(0, 1); + key_ = key_.flatten(0, 1); + value_ = value_.flatten(0, 1); + + auto [res0, res1, res2, res3, res4, res5, res6, res7, res8] = at::_scaled_dot_product_flash_attention( + query_, key_, value_, dropout_p, is_causal, return_debug_mask, scale); + + res0 = reshape_dim_outof(0, batch_size, res0); + res1 = reshape_dim_outof(0, batch_size, res1); + // res2 and res3 (cum_seq_q and cum_seq_k) are always [0] for dense tensors + // res4 and res5 (max_q and max_k) are SymInts, so they don't need reshaping + // res6 and res7 (philox seed and offset) are always non-batched + if (return_debug_mask) { + res8 = reshape_dim_outof(0, batch_size, res8); + } + + return std::make_tuple( + std::move(res0), 0, + std::move(res1), 0, + std::move(res2), std::nullopt, + std::move(res3), std::nullopt, + std::move(res4), + std::move(res5), + std::move(res6), std::nullopt, + std::move(res7), std::nullopt, + std::move(res8), return_debug_mask ? std::optional(0) : std::nullopt + ); +} + +std::tuple, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional, SymInt, SymInt, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional> +_scaled_dot_product_flash_attention_quantized_batch_rule( + const Tensor& query, std::optional query_bdim, + const Tensor& key, std::optional key_bdim, + const Tensor& value, std::optional value_bdim, + const std::optional& q_descale, std::optional q_descale_bdim, + const std::optional& k_descale, std::optional k_descale_bdim, + const std::optional& v_descale, std::optional v_descale_bdim, + double dropout_p, + bool is_causal, + bool return_debug_mask, + std::optional scale +) { + if (dropout_p > 0) { + auto maybe_layer = maybeCurrentDynamicLayer(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness, query_bdim.has_value() || key_bdim.has_value() || value_bdim.has_value()); + } + auto batch_size = get_bdim_size3(query, query_bdim, key, key_bdim, value, value_bdim); + auto query_ = moveBatchDimToFront(query, query_bdim); + auto key_ = moveBatchDimToFront(key, key_bdim); + auto value_ = moveBatchDimToFront(value, value_bdim); + query_ = ensure_has_bdim(query_, query_bdim.has_value(), batch_size); + key_ = ensure_has_bdim(key_, key_bdim.has_value(), batch_size); + value_ = ensure_has_bdim(value_, value_bdim.has_value(), batch_size); + query_ = query_.flatten(0, 1); + key_ = key_.flatten(0, 1); + value_ = value_.flatten(0, 1); + + // Handle descale tensors (shape: batch x num_heads_kv) + std::optional q_descale_, k_descale_, v_descale_; + if (q_descale.has_value() && q_descale->defined()) { + auto tmp = moveBatchDimToFront(*q_descale, q_descale_bdim); + tmp = ensure_has_bdim(tmp, q_descale_bdim.has_value(), batch_size); + q_descale_ = tmp.flatten(0, 1); + } + if (k_descale.has_value() && k_descale->defined()) { + auto tmp = moveBatchDimToFront(*k_descale, k_descale_bdim); + tmp = ensure_has_bdim(tmp, k_descale_bdim.has_value(), batch_size); + k_descale_ = tmp.flatten(0, 1); + } + if (v_descale.has_value() && v_descale->defined()) { + auto tmp = moveBatchDimToFront(*v_descale, v_descale_bdim); + tmp = ensure_has_bdim(tmp, v_descale_bdim.has_value(), batch_size); + v_descale_ = tmp.flatten(0, 1); + } + + auto [res0, res1, res2, res3, res4, res5, res6, res7, res8] = at::_scaled_dot_product_flash_attention( + query_, key_, value_, q_descale_, k_descale_, v_descale_, dropout_p, is_causal, return_debug_mask, scale); + + res0 = reshape_dim_outof(0, batch_size, res0); + res1 = reshape_dim_outof(0, batch_size, res1); + // res2 and res3 (cum_seq_q and cum_seq_k) are always [0] for dense tensors + // res4 and res5 (max_q and max_k) are SymInts, so they don't need reshaping + // res6 and res7 (philox seed and offset) are always non-batched + if (return_debug_mask) { + res8 = reshape_dim_outof(0, batch_size, res8); + } + + return std::make_tuple( + std::move(res0), 0, + std::move(res1), 0, + std::move(res2), std::nullopt, + std::move(res3), std::nullopt, + std::move(res4), + std::move(res5), + std::move(res6), std::nullopt, + std::move(res7), std::nullopt, + std::move(res8), return_debug_mask ? std::optional(0) : std::nullopt + ); +} + +fourOutputs _scaled_dot_product_efficient_attention_batch_rule( + const Tensor& query, std::optional query_bdim, + const Tensor& key, std::optional key_bdim, + const Tensor& value, std::optional value_bdim, + const std::optional& attn_bias, std::optional attn_bias_bdim, + bool compute_log_sumexp, + double dropout_p, + bool is_causal, + std::optional scale +) { + if (dropout_p > 0) { + auto maybe_layer = maybeCurrentDynamicLayer(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + RandomnessType randomness = maybe_layer->randomness(); + auto any_tensor_batched = query_bdim.has_value() || key_bdim.has_value() || + value_bdim.has_value() || attn_bias_bdim.has_value(); + check_randomness(randomness, any_tensor_batched); + } + auto batch_size = attn_bias.has_value() && attn_bias->defined() + ? get_bdim_size4(query, query_bdim, key, key_bdim, value, value_bdim, *attn_bias, attn_bias_bdim) + : get_bdim_size3(query, query_bdim, key, key_bdim, value, value_bdim); + auto query_ = moveBatchDimToFront(query, query_bdim); + auto key_ = moveBatchDimToFront(key, key_bdim); + auto value_ = moveBatchDimToFront(value, value_bdim); + query_ = ensure_has_bdim(query_, query_bdim.has_value(), batch_size); + key_ = ensure_has_bdim(key_, key_bdim.has_value(), batch_size); + value_ = ensure_has_bdim(value_, value_bdim.has_value(), batch_size); + + query_ = query_.flatten(0, 1); + key_ = key_.flatten(0, 1); + value_ = value_.flatten(0, 1); + + std::optional attn_bias_; + if (attn_bias.has_value() && attn_bias->defined()) { + attn_bias_ = flatten_sdpa_attn_bias_for_vmap(*attn_bias, attn_bias_bdim, batch_size); + } + auto [res0, res1, res2, res3] = at::_scaled_dot_product_efficient_attention( + query_, key_, value_, attn_bias_, compute_log_sumexp, dropout_p, is_causal, scale); + res0 = reshape_dim_outof(0, batch_size, res0); + res1 = reshape_dim_outof(0, batch_size, res1); + // philox seed is always non-batched + return std::make_tuple(std::move(res0), 0, std::move(res1), 0, std::move(res2), std::nullopt, std::move(res3), std::nullopt); +} + +// Please unify SDPA APIs!!! +std::tuple, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional, SymInt, SymInt, Tensor, std::optional, Tensor, std::optional, Tensor, std::optional> +_scaled_dot_product_cudnn_attention_batch_rule( + const Tensor& query, std::optional query_bdim, + const Tensor& key, std::optional key_bdim, + const Tensor& value, std::optional value_bdim, + const std::optional& attn_bias, std::optional attn_bias_bdim, + bool compute_log_sumexp, + double dropout_p, + bool is_causal, + bool return_debug_mask, + std::optional scale +) { + if (dropout_p > 0) { + auto maybe_layer = maybeCurrentDynamicLayer(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + RandomnessType randomness = maybe_layer->randomness(); + auto any_tensor_batched = query_bdim.has_value() || key_bdim.has_value() || + value_bdim.has_value() || attn_bias_bdim.has_value(); + check_randomness(randomness, any_tensor_batched); + } + auto batch_size = attn_bias.has_value() && attn_bias->defined() + ? get_bdim_size4(query, query_bdim, key, key_bdim, value, value_bdim, *attn_bias, attn_bias_bdim) + : get_bdim_size3(query, query_bdim, key, key_bdim, value, value_bdim); + auto query_ = moveBatchDimToFront(query, query_bdim); + auto key_ = moveBatchDimToFront(key, key_bdim); + auto value_ = moveBatchDimToFront(value, value_bdim); + query_ = ensure_has_bdim(query_, query_bdim.has_value(), batch_size); + key_ = ensure_has_bdim(key_, key_bdim.has_value(), batch_size); + value_ = ensure_has_bdim(value_, value_bdim.has_value(), batch_size); + query_ = query_.flatten(0, 1); + key_ = key_.flatten(0, 1); + value_ = value_.flatten(0, 1); + + std::optional attn_bias_; + if (attn_bias.has_value() && attn_bias->defined()) { + attn_bias_ = flatten_sdpa_attn_bias_for_vmap(*attn_bias, attn_bias_bdim, batch_size); + } + + auto [res0, res1, res2, res3, res4, res5, res6, res7, res8] = at::_scaled_dot_product_cudnn_attention( + query_, key_, value_, attn_bias_, compute_log_sumexp, dropout_p, is_causal, return_debug_mask, scale); + + res0 = reshape_dim_outof(0, batch_size, res0); + std::optional res1_bdim; + if (compute_log_sumexp) { + res1 = reshape_dim_outof(0, batch_size, res1); + res1_bdim = 0; + } else { + res1_bdim = std::nullopt; + } + // res2 and res3 (cum_seq_q and cum_seq_k) are always [0] for dense tensors + // res4 and res5 (max_q and max_k) are SymInts, so they don't need reshaping + // res6 and res7 (philox seed and offset) are always non-batched + if (return_debug_mask) { + res8 = reshape_dim_outof(0, batch_size, res8); + } + + return std::make_tuple( + std::move(res0), 0, + std::move(res1), res1_bdim, + std::move(res2), std::nullopt, + std::move(res3), std::nullopt, + std::move(res4), + std::move(res5), + std::move(res6), std::nullopt, + std::move(res7), std::nullopt, + std::move(res8), return_debug_mask ? std::optional(0) : std::nullopt + ); +} + +} + +#define LINALG_CHECK_MATRIX_UNARY_BATCH_RULE(fn, num_out) SINGLE_ARG(\ + LinalgCheckMatrixUnaryRuleHelper<\ + func_string_##fn,\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn),\ + c10::guts::function_traits::parameter_types>::apply_##num_out) + +#define LINALG_CHECK_MATRIX_UNARY_BATCH_RULE2(fn, overload, num_out) SINGLE_ARG(\ + LinalgCheckMatrixUnaryRuleHelper<\ + func_string_##fn_##overload,\ + decltype(&ATEN_FN2(fn, overload)),\ + &ATEN_FN2(fn, overload),\ + c10::guts::function_traits::parameter_types>::apply_##num_out) + +#define LINALG_CHECK_MATRIX_BINARY_BATCH_RULE(fn, num_out) SINGLE_ARG(\ + LinalgCheckMatrixBinaryRuleHelper<\ + func_string_##fn,\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn),\ + c10::guts::function_traits::parameter_types>::apply_##num_out) + + +// Define string constants with the function names. These will be used as template parameters +// C++ doesn't let us use string literals as template parameters, so we have to declare them as consts first +// What is going on with these macros? +// - clang-5 seems to require the constexpr +// - windows compiles with or without the constexpr, but the constexpr causes test problems +// - as a result we have some macro guards. +#if defined(_MSC_VER) +#define LINALG_STRING_CONST(fn, op_name) \ + const char func_string_##fn[] = #op_name;\ + +#define LINALG_STRING_CONST2(fn, overload, op_name) \ + const char func_string_##fn_##overload[] = #op_name;\ + +#else +#define LINALG_STRING_CONST(fn, op_name) \ + constexpr const char func_string_##fn[] = #op_name;\ + +#define LINALG_STRING_CONST2(fn, overload, op_name) \ + constexpr const char func_string_##fn_##overload[] = #op_name;\ + +#endif + +#define LINALG_CHECK_MATRIX_UNARY_ONE_OUT(fn, op_name) \ + LINALG_STRING_CONST(fn, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT(fn, LINALG_CHECK_MATRIX_UNARY_BATCH_RULE(fn, one));\ + } + +#define LINALG_CHECK_MATRIX_UNARY_ONE_OUT2(fn, overload, op_name) \ + LINALG_STRING_CONST2(fn, overload, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT2(fn, overload, LINALG_CHECK_MATRIX_UNARY_BATCH_RULE2(fn, overload, one));\ + } + +#define LINALG_CHECK_MATRIX_UNARY_TWO_OUT(fn, op_name) \ + LINALG_STRING_CONST(fn, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT(fn, LINALG_CHECK_MATRIX_UNARY_BATCH_RULE(fn, two));\ + } + +#define LINALG_CHECK_MATRIX_UNARY_THREE_OUT(fn, op_name) \ + LINALG_STRING_CONST(fn, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT(fn, LINALG_CHECK_MATRIX_UNARY_BATCH_RULE(fn, three));\ + } + +#define LINALG_CHECK_MATRIX_UNARY_FOUR_OUT(fn, op_name) \ + LINALG_STRING_CONST(fn, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT(fn, LINALG_CHECK_MATRIX_UNARY_BATCH_RULE(fn, four));\ + } + +#define LINALG_CHECK_MATRIX_BINARY_ONE_OUT(fn, op_name) \ + LINALG_STRING_CONST(fn, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT(fn, LINALG_CHECK_MATRIX_BINARY_BATCH_RULE(fn, one));\ + } + +#define LINALG_CHECK_MATRIX_BINARY_TWO_OUT(fn, op_name) \ + LINALG_STRING_CONST(fn, op_name)\ + TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) {\ + VMAP_SUPPORT(fn, LINALG_CHECK_MATRIX_BINARY_BATCH_RULE(fn, two));\ + } + +// These need to be outside. String constant must be declared outside of a macro to be used as template param +// NOLINTBEGIN(*array*) +LINALG_CHECK_MATRIX_UNARY_ONE_OUT(cholesky_inverse, cholesky_inverse) +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(linalg_cholesky_ex, linalg.cholesky) +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(linalg_eig, linalg.eig) +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(linalg_inv_ex, linalg.inv_ex) +LINALG_CHECK_MATRIX_UNARY_THREE_OUT(linalg_ldl_factor_ex, torch.linalg.ldl_factor_ex) +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(linalg_qr, linalg.qr) +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(linalg_slogdet, linalg.slogdet) +LINALG_CHECK_MATRIX_BINARY_ONE_OUT(linalg_solve_triangular, linalg.solve_triangular) + +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(geqrf, geqrf) +LINALG_CHECK_MATRIX_BINARY_TWO_OUT(triangular_solve, triangular_solve) +LINALG_CHECK_MATRIX_UNARY_THREE_OUT(_linalg_det, linalg.det) +LINALG_CHECK_MATRIX_UNARY_TWO_OUT(_linalg_eigh, linalg.eigh) +LINALG_CHECK_MATRIX_UNARY_FOUR_OUT(_linalg_slogdet, linalg.slogdet) +LINALG_CHECK_MATRIX_UNARY_THREE_OUT(_linalg_svd, linalg.svd) +// NOLINTEND(*array*) + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT(bmm, bmm_batch_rule); + m.impl("addmv", addmv_decomp); + m.impl("addmm", addmm_decomp); + m.impl("addbmm", addbmm_decomp); + m.impl("baddbmm", baddbmm_decomp); + VMAP_SUPPORT(dot, dot_batch_rule); + VMAP_SUPPORT(mv, mv_batch_rule); + VMAP_SUPPORT(mm, mm_batch_rule); + VMAP_SUPPORT(lu_unpack, linalg_lu_unpack_batch_rule); + VMAP_SUPPORT(linalg_lu_solve, linalg_lu_solve_batch_rule); + VMAP_SUPPORT(linalg_householder_product, householder_product_batch_rule); + VMAP_SUPPORT(cholesky_solve, cholesky_solve_batch_rule); // custom dim error + VMAP_SUPPORT(linalg_lstsq, linalg_lstsq_batch_rule); // custom errors and sometimes empty return + VMAP_SUPPORT(linalg_lu_factor_ex, linalg_lu_factor_ex_batch_rule); + VMAP_SUPPORT(linalg_matrix_exp, matrix_exp_batch_rule); + VMAP_SUPPORT(linalg_matrix_sqrth, matrix_sqrth_batch_rule); + VMAP_SUPPORT(_linalg_solve_ex, solve_ex_batch_rule); + VMAP_SUPPORT(linalg_cross, cross_batch_rule); + VMAP_SUPPORT2(linalg_pinv, atol_rtol_tensor, pinv_batch_rule); + VMAP_SUPPORT(_scaled_dot_product_efficient_attention, _scaled_dot_product_efficient_attention_batch_rule); + + VMAP_SUPPORT(_scaled_dot_product_flash_attention, _scaled_dot_product_flash_attention_batch_rule); + VMAP_SUPPORT2(_scaled_dot_product_flash_attention, quantized, _scaled_dot_product_flash_attention_quantized_batch_rule); + VMAP_SUPPORT(_scaled_dot_product_cudnn_attention, _scaled_dot_product_cudnn_attention_batch_rule); + + VMAP_SUPPORT(_linalg_check_errors, _linalg_check_errors_batch_rule); + + m.impl("vdot", vdot_decomp); +} +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesLoss.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesLoss.cpp new file mode 100644 index 0000000000000000000000000000000000000000..caf3a9070555d511588cc5c8a75304364d4b4dc7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesLoss.cpp @@ -0,0 +1,183 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +namespace at::functorch { +// Flattens out all dims except the batch dim, and also moves batch dim +// (if it exists) to front. +static at::Tensor flatten_logical(const Tensor& tensor, std::optional bdim) { + if (bdim.has_value()) { + auto result = moveBatchDimToFront(tensor, bdim); + if (result.dim() > 1) { + return result.flatten(1); + } else { + return result; + } + } else { + return tensor.flatten(); + } +} + +// Useful for many loss functions +template +static std::tuple> +loss_batch_rule_helper(const at::Tensor& self, std::optional self_bdim, const at::Tensor& target, + std::optional target_bdim, int64_t reduction, + Func loss_fn) { + auto self_ = flatten_logical(self, self_bdim); + auto target_ = flatten_logical(target, target_bdim); + auto result = loss_fn(self_, target_, Reduction::None); + if (result.dim() == 1) { + return std::make_tuple(result, 0); + } else if (reduction == Reduction::None) { + DimVector end_shape; + const auto batched_elem = self_bdim.has_value() ? + moveBatchDimToFront(self, self_bdim) : moveBatchDimToFront(target, target_bdim); + return std::make_tuple(result.reshape(batched_elem.sizes()), 0); + } else if (reduction == Reduction::Sum) { + return std::make_tuple(result.sum(-1), 0); + } else if (reduction == Reduction::Mean) { + return std::make_tuple(result.mean(-1), 0); + } + TORCH_INTERNAL_ASSERT(false); +} + +static std::tuple> +mse_loss_batch_rule(const at::Tensor& self, std::optional self_bdim, const at::Tensor& target, + std::optional target_bdim, int64_t reduction) { + return loss_batch_rule_helper(self, self_bdim, target, target_bdim, + reduction, [](const at::Tensor& self, const at::Tensor& target, int64_t reduction) { + return at::mse_loss(self, target, reduction); + }); +} + +static std::tuple> +huber_loss_batch_rule(const at::Tensor& self, std::optional self_bdim, const at::Tensor& target, + std::optional target_bdim, int64_t reduction, double delta) { + return loss_batch_rule_helper(self, self_bdim, target, target_bdim, + reduction, [delta](const at::Tensor& self, const at::Tensor& target, int64_t reduction) { + return at::huber_loss(self, target, reduction, delta); + }); +} + +static std::tuple> +smooth_l1_loss_batch_rule(const at::Tensor& self, std::optional self_bdim, const at::Tensor& target, + std::optional target_bdim, int64_t reduction, double beta) { + return loss_batch_rule_helper(self, self_bdim, target, target_bdim, + reduction, [beta](const at::Tensor& self, const at::Tensor& target, int64_t reduction) { + return at::smooth_l1_loss(self, target, reduction, beta); + }); +} + +static Tensor apply_loss_reduction(const at::Tensor& unreduced, int64_t reduction) { + if (reduction == at::Reduction::Mean) { + return unreduced.mean(); + } else if (reduction == at::Reduction::Sum) { + return unreduced.sum(); + } + return unreduced; +} + +static Tensor binary_cross_entropy_plumbing( + const Tensor& self, const Tensor& target, + const std::optional& weight, int64_t reduction) { + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "binary_cross_entropy_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!isBatchedAtLevel(self, cur_level) && !isBatchedAtLevel(target, cur_level) + && !isBatchedAtLevel(weight, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::binary_cross_entropy(self, target, weight, reduction); + } + + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + auto [target_value, target_bdim] = unwrapTensorAtLevel(target, cur_level); + + Tensor result; + if (self_bdim || target_bdim) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + const auto bdim_size = get_bdim_size2(self_value, self_bdim, target_value, target_bdim); + auto self_ = moveBatchDimToFront(self_value, self_bdim); + auto target_ = moveBatchDimToFront(target_value, target_bdim); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), bdim_size); + target_ = ensure_has_bdim(target_, target_bdim.has_value(), bdim_size); + result = at::binary_cross_entropy(self_, target_, std::nullopt, Reduction::None); + result = makeBatched(result, 0, cur_level); + } else { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + result = at::binary_cross_entropy(self_value, target_value, std::nullopt, Reduction::None); + } + if (weight.has_value() && weight->defined()) { + result = result * weight.value(); + } + return apply_loss_reduction(result, reduction); +} + +static Tensor binary_cross_entropy_backward_plumbing( + const Tensor& grad, const Tensor& input, const Tensor& target, + const std::optional& weight_opt, int64_t reduction) { + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "binary_cross_entropy_backward_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({grad, input, target, weight_opt}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::binary_cross_entropy_backward(grad, input, target, weight_opt, reduction); + } + + auto [grad_value, grad_bdim] = unwrapTensorAtLevel( + reduction == Reduction::None ? grad : grad.expand_as(input), cur_level); + auto [input_value, input_bdim] = unwrapTensorAtLevel(input, cur_level); + auto [target_value, target_bdim] = unwrapTensorAtLevel(target, cur_level); + + Tensor grad_input; + if (grad_bdim || input_bdim || target_bdim) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + const auto bdim_size = get_bdim_size3( + grad_value, grad_bdim, input_value, input_bdim, target_value, target_bdim); + + auto grad_ = moveBatchDimToFront(grad_value, grad_bdim); + auto input_ = moveBatchDimToFront(input_value, input_bdim); + auto target_ = moveBatchDimToFront(target_value, target_bdim); + + grad_ = ensure_has_bdim(grad_, grad_bdim.has_value(), bdim_size); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), bdim_size); + target_ = ensure_has_bdim(target_, target_bdim.has_value(), bdim_size); + + grad_input = at::binary_cross_entropy_backward( + grad_, input_, target_, std::nullopt, Reduction::None); + grad_input = makeBatched(grad_input, 0, cur_level); + } else { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + grad_input = at::binary_cross_entropy_backward( + grad_value, input_value, target_value, std::nullopt, Reduction::None); + } + if (weight_opt.has_value() && weight_opt->defined()) { + grad_input = grad_input * weight_opt.value(); + } + if (reduction == Reduction::Mean) { + grad_input.div_(input.numel()); + } + return grad_input; +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT(mse_loss, mse_loss_batch_rule); + // mse_loss_backward uses a decomposition for its batch rule + VMAP_SUPPORT(huber_loss, huber_loss_batch_rule); + // huber_loss_backward uses a decomposition for its batch rule + VMAP_SUPPORT(smooth_l1_loss, smooth_l1_loss_batch_rule); + // smooth_l1_loss_backward uses a decomposition for its batch rule + m.impl("binary_cross_entropy", binary_cross_entropy_plumbing); + m.impl("binary_cross_entropy_backward", binary_cross_entropy_backward_plumbing); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesModules.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesModules.cpp new file mode 100644 index 0000000000000000000000000000000000000000..956f1f2f4c107017a811c65c76779cd1085d5575 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesModules.cpp @@ -0,0 +1,395 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +#include + +namespace at::functorch { + +static Tensor getStepTensor(const Tensor& indices, const c10::SymInt& bdim_size, const c10::SymInt& num_embeddings) { + // [batch_size, 1, 1, 1, ..., 1] + c10::SymDimVector view_shape(indices.dim(), 1); + view_shape[0] = bdim_size; + auto range = at::arange(0, bdim_size * num_embeddings, num_embeddings, indices.options()); + return range.view_symint(view_shape); +} + +static std::tuple> embedding_batch_rule( + const Tensor& weight, std::optional weight_bdim, + const Tensor& indices, std::optional indices_bdim, + c10::SymInt padding_idx, bool scale_grad_by_freq, bool sparse) { + if (!weight_bdim && indices_bdim) { + // B*, ED -> B*D + auto result = at::embedding_symint(weight, indices, std::move(padding_idx), scale_grad_by_freq, sparse); + return std::make_tuple(std::move(result), indices_bdim); + } else if (weight_bdim && !indices_bdim) { + // *, BED -> *, E(BD) -> *(BD) -> *BD + const auto batch_size = weight.size(*weight_bdim); + const auto weight_ = reshape_dim_into(*weight_bdim, /*embedding_dim*/1, weight); + auto result = at::embedding_symint(weight_, indices, std::move(padding_idx), scale_grad_by_freq, sparse); + result = reshape_dim_outof(-1, batch_size, result); + auto result_bdim = result.dim() - 2; + return std::make_tuple(std::move(result), result_bdim); + } + TORCH_INTERNAL_ASSERT(weight_bdim && indices_bdim); + // B*, BED -> B*, (BE)D -> B*D + // We'll need to do something extra: add (0, E, 2*E, ...) to the indices. + const auto batch_size = weight.size(*weight_bdim); + const auto num_embeddings = weight.size((*weight_bdim == 0) ? 1 : 0); + const auto weight_ = reshape_dim_into(*weight_bdim, 0, weight); + auto indices_ = moveBatchDimToFront(indices, indices_bdim); + + { + // getStepTensor returns a regular Tensor. If indices_ is a DTensor + // we want to allow this mixed DTensor-Tensor operation. + at::DTensorAllowImplicitReplication guard; + const auto range = getStepTensor(indices, batch_size, num_embeddings); + indices_ = indices_ + range; + } + auto result = at::embedding_symint(weight_, indices_, std::move(padding_idx), scale_grad_by_freq, sparse); + return std::make_tuple(std::move(result), 0); +} + +static std::tuple> +embedding_dense_backward_batch_rule( + const Tensor& grad_, std::optional grad_bdim, + const Tensor& indices_, std::optional indices_bdim, + c10::SymInt num_weights, c10::SymInt padding_idx, bool scale_grad_by_freq) { + Tensor grad = grad_; + Tensor indices = indices_; + if (!indices_bdim.has_value() && grad_bdim) { + const auto bdim_size = grad.sym_size(*grad_bdim); + grad = reshape_dim_into(*grad_bdim, -1, grad); + auto result = at::embedding_dense_backward_symint( + grad, indices, std::move(num_weights), std::move(padding_idx), scale_grad_by_freq); + result = reshape_dim_outof_symint(1, bdim_size, result); + return std::make_tuple(std::move(result), 1); + } + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + const auto bdim_size = indices.size(indices_bdim.value()); + indices = moveBatchDimToFront(indices, indices_bdim); + grad = moveBatchDimToFront(grad, grad_bdim); + grad = ensure_has_bdim(grad, grad_bdim.has_value(), bdim_size); + const auto range = getStepTensor(indices, bdim_size, num_weights); + auto result = at::embedding_dense_backward_symint( + grad, indices + range, num_weights * bdim_size, -1, scale_grad_by_freq); + result = reshape_dim_outof(0, bdim_size, result); + // Fill in the padding. We can't do it in the embedding_dense_backward call + // because we need to fill in multiple rows! + if (padding_idx >= 0) { + result.select_symint(1, std::move(padding_idx)).fill_(0); + } + return std::make_tuple(std::move(result), 0); +} + +/** + * grid sample batch rule breaks down into 3 cases: + * case 1 (input is batched, grid is not): + * batch input along first dimension, unpack along first dimension + * 2d: + * input: N(BC)H_{in}W_{in}, grid: NH_{out}W_{out}2 + * output: N(BC)H_{out}W_{out} + * 3d: + * input: N(BC)D_{in}H_{in}W_{in}, grid: ND_{out}H_{out}W_{out}3 + * output: N(BC)D_{out}H_{out}W_{out} + * case 2 (input is not batched, grid is batched): + * batch grid along second dimension, unpack along second dimension + * 2d: + * input: NCH_{in}W_{in}, grid: N(BH_{out})W_{out}2 + * output: NC(BH_{out})W_{out} + * 3d: + * input: NCD_{in}H_{in}W_{in}, grid: N(BD_{out})H_{out}W_{out}3 + * output: NC(BD_{out})H_{out}W_{out} + * case 3 (input and grid are both batched): + * batch grid and input along 0th dimension, unpack along 0th dimension + * 2d: + * input: (BN)CH_{in}W_{in}, grid: (BN)H_{out}W_{out}2 + * output: (BN)CH_{out}W_{out} + * 3d: + * input: (BN)CD_{in}H_{in}W_{in}, grid: (BN)D_{out}H_{out}W_{out}3 + * output: (BN)CD_{out}H_{out}W_{out} + */ +template +std::tuple> +static grid_sample_batch_rule(const Tensor& input, std::optional input_bdim, const Tensor& grid, std::optional grid_bdim, ExtraArgs... extra_args) { + std::tuple> result; + if (input_bdim && !grid_bdim) { + auto new_input = reshape_dim_into(*input_bdim, 1, input); + auto out = Func(new_input, grid, std::forward(extra_args)...); + out = reshape_dim_outof(1, input.sizes()[*input_bdim], out); + result = std::make_tuple(std::move(out), 1); + } else if (!input_bdim && grid_bdim) { + // grid of N(BH)W2 -> NC(BH)W or grid of N(BD)HBW3 -> NC(BD)HW + auto new_grid = reshape_dim_into(*grid_bdim, 1, grid); + auto out = Func(input, new_grid, std::forward(extra_args)...); + out = reshape_dim_outof(2, grid.sizes()[*grid_bdim], out); + result = std::make_tuple(std::move(out), 2); + } else if (input_bdim && grid_bdim) { + auto new_input = reshape_dim_into(*input_bdim, 0, input); + auto new_grid = reshape_dim_into(*grid_bdim, 0, grid); + auto out = Func(new_input, new_grid, std::forward(extra_args)...); + out = reshape_dim_outof(0, input.sizes()[*grid_bdim], out); + result = std::make_tuple(std::move(out), 0); + } else { + result = std::make_tuple(Func(input, grid, std::forward(extra_args)...), std::nullopt); + } + return result; +} + +static std::tuple +grid_sample_backward_helper_in( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& input, std::optional input_bdim, + const Tensor& grid, std::optional grid_bdim) { + + auto batch_size = get_bdim_size3( + grad_output, grad_output_bdim, input, input_bdim, grid, grid_bdim); + + auto grad_output_ = moveBatchDimToFront(grad_output, grad_output_bdim); + grad_output_ = ensure_has_bdim(grad_output_, grad_output_bdim.has_value(), batch_size); + grad_output_ = reshape_dim_into(0, 0, grad_output_); + + auto input_ = moveBatchDimToFront(input, input_bdim); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), batch_size); + input_ = reshape_dim_into(0, 0, input_); + + auto grid_ = moveBatchDimToFront(grid, grid_bdim); + grid_ = ensure_has_bdim(grid_, grid_bdim.has_value(), batch_size); + grid_ = reshape_dim_into(0, 0, grid_); + + return std::make_tuple(std::move(grad_output_), std::move(input_), std::move(grid_), batch_size); +} + +static std::tuple, Tensor, std::optional> +grid_sample_backward_helper_out( + // NOLINTNEXTLINE(performance-unnecessary-value-param) + std::tuple bw_out, + int64_t grad_input_bdim, + int64_t grad_grid_bdim, + int64_t bdim_size) { + auto& [grad_input, grad_grid] = bw_out; + std::optional grad_input_bdim_out, grad_grid_bdim_out; + if (grad_input.defined()) { + grad_input = reshape_dim_outof(grad_input_bdim, bdim_size, grad_input); + grad_input_bdim_out = grad_input_bdim; + } + if (grad_grid.defined()) { + grad_grid = reshape_dim_outof(grad_grid_bdim, bdim_size, grad_grid); + grad_grid_bdim_out = grad_grid_bdim; + } + return std::make_tuple(std::move(grad_input), grad_input_bdim_out, std::move(grad_grid), grad_grid_bdim_out); +} + + +template +std::tuple, Tensor, std::optional> +static grid_sample_backward_batch_rule( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& input, std::optional input_bdim, + const Tensor& grid, std::optional grid_bdim, + ExtraArgs... extra_args) { + + auto new_bw_input = grid_sample_backward_helper_in( + grad_output, grad_output_bdim, input, input_bdim, grid, grid_bdim); + + auto [new_grad_output, new_input, new_grid, batch_size] = new_bw_input; + + auto bw_out = Func(std::move(new_grad_output), std::move(new_input), std::move(new_grid), std::forward(extra_args)...); + + return grid_sample_backward_helper_out(std::move(bw_out), 0, 0, batch_size); +} + +template +std::tuple, Tensor, std::optional> +static cudnn_grid_sample_backward_batch_rule( + const Tensor& input, std::optional input_bdim, + const Tensor& grid, std::optional grid_bdim, + const Tensor& grad_output, std::optional grad_output_bdim) { + + auto [new_grad_output,new_input,new_grid,bdim_size]= grid_sample_backward_helper_in( + grad_output, grad_output_bdim, input, input_bdim, grid, grid_bdim); + + auto bw_out = Func(std::move(new_input), std::move(new_grid), std::move(new_grad_output)); + + return grid_sample_backward_helper_out(std::move(bw_out), 0, 0, bdim_size); +} + +// uses functional formulation for one_hot under vmap to be compatible with +// fakeTensor/dynamic shapes and compiled functorch transforms. +// mirrors the meta path in aten/src/ATen/native/Onehot.cpp, +// but requires explicit positive num_classes under vmap to avoid +// data-dependent output shapes. +static Tensor one_hot_decomposition_hack(const Tensor &self, int64_t num_classes) { + TORCH_CHECK(self.dtype() == kLong, "one_hot is only applicable to index tensor."); + + // disallow implicit inference under vmap; this would be data-dependent + // and is intentionally guarded by Dynamo in torch/_dynamo/variables/torch.py. + TORCH_CHECK(num_classes > 0, "When vmap-ing torch.nn.functional.one_hot, please " + "provide an explicit positive num_classes argument."); + + const auto options = self.options(); + at::Tensor index = at::arange(num_classes, options); + return at::eq(self.unsqueeze(-1), index).to(at::kLong); +} + +template +struct UpsampleBackwardBatchRuleHelper; + +template +struct UpsampleBackwardBatchRuleHelper> { + static std::tuple> apply( + const Tensor& grad_output, std::optional grad_output_bdim, + c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, + T... extra_args) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto grad_output_ = reshape_dim_into(grad_output_bdim.value(), 0, grad_output); + TORCH_INTERNAL_ASSERT(!input_size.empty()); + + // input_size is wrong so we correct it + c10::SymDimVector physical_input_size(input_size.begin(), input_size.end()); + physical_input_size[0] = grad_output_.sym_sizes()[0]; + + auto out = Func( + std::move(grad_output_), + output_size, + std::move(physical_input_size), + std::forward(extra_args)...); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return std::make_tuple(reshape_dim_outof_symint(0, grad_output.sym_sizes()[grad_output_bdim.value()], out), 0); + } + +}; + +template +struct GridSampleBatchRuleHelper; + +template +struct GridSampleBatchRuleHelper> { + static std::tuple> apply( + const Tensor& input, std::optional input_batch_dim, + const Tensor& grid, std::optional grid_batch_dim, + T... extra_args) { + return grid_sample_batch_rule( + input, input_batch_dim, grid, grid_batch_dim, std::forward(extra_args)...); + } +}; + +template +struct GridSampleBackwardBatchRuleHelper; + +template +struct GridSampleBackwardBatchRuleHelper> { + static std::tuple, Tensor, std::optional> apply( + const Tensor& grad_output, std::optional grad_output_batch_dim, + const Tensor& input, std::optional input_batch_dim, + const Tensor& grid, std::optional grid_batch_dim, + T... extra_args) { + return grid_sample_backward_batch_rule( + grad_output, grad_output_batch_dim, + input, input_batch_dim, + grid, grid_batch_dim, + std::forward(extra_args)...); + } +}; + +template +struct CudnnGridSampleBackwardBatchRuleHelper { + static std::tuple, Tensor, std::optional> apply( + const Tensor& input, std::optional input_batch_dim, + const Tensor& grid, std::optional grid_batch_dim, + const Tensor& grad_output, std::optional grad_output_batch_dim) { + return cudnn_grid_sample_backward_batch_rule( + input, input_batch_dim, + grid, grid_batch_dim, + grad_output, grad_output_batch_dim + ); + } +}; + +#define GRID_SAMPLE_BATCH_RULE(fn) SINGLE_ARG(\ + GridSampleBatchRuleHelper<\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn),\ + c10::guts::function_traits::parameter_types>::apply) + +#define GRID_SAMPLE_BW_BATCH_RULE(fn) SINGLE_ARG(\ + GridSampleBackwardBatchRuleHelper<\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn),\ + c10::guts::function_traits::parameter_types>::apply) + +#define CUDNN_GRID_SAMPLE_BW_BATCH_RULE(fn)\ + CudnnGridSampleBackwardBatchRuleHelper::apply + +#define UPSAMPLE_BACKWARD(op) VMAP_SUPPORT(op, SINGLE_ARG(\ + UpsampleBackwardBatchRuleHelper<\ + decltype(&ATEN_FN(op)),\ + &ATEN_FN(op),\ + c10::guts::function_traits::parameter_types>::apply)) + + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + EXISTING_BDIM(im2col); + EXISTING_BDIM(col2im); + + VMAP_SUPPORT(embedding, embedding_batch_rule); + VMAP_SUPPORT(embedding_dense_backward, embedding_dense_backward_batch_rule); + + VMAP_SUPPORT(grid_sampler_2d, GRID_SAMPLE_BATCH_RULE(grid_sampler)); + VMAP_SUPPORT(grid_sampler_2d_backward, GRID_SAMPLE_BW_BATCH_RULE(grid_sampler_2d_backward)); + + VMAP_SUPPORT(grid_sampler_3d, GRID_SAMPLE_BATCH_RULE(grid_sampler)); + VMAP_SUPPORT(grid_sampler_3d_backward, GRID_SAMPLE_BW_BATCH_RULE(grid_sampler_3d_backward)); + VMAP_SUPPORT(cudnn_grid_sampler_backward, CUDNN_GRID_SAMPLE_BW_BATCH_RULE(cudnn_grid_sampler_backward)); + + VMAP_SUPPORT(cudnn_grid_sampler, GRID_SAMPLE_BATCH_RULE(cudnn_grid_sampler)); + + EXISTING_BDIM(pixel_shuffle); + EXISTING_BDIM(pixel_unshuffle); + EXISTING_BDIM(channel_shuffle); + + VARIADIC_BDIMS(constant_pad_nd); + EXISTING_BDIM(reflection_pad1d); + EXISTING_BDIM(reflection_pad2d); + EXISTING_BDIM(reflection_pad3d); + EXISTING_BDIM(replication_pad1d); + EXISTING_BDIM(replication_pad2d); + EXISTING_BDIM(replication_pad3d); + + EXISTING_BDIM_ALL_BOXED(replication_pad1d_backward); + EXISTING_BDIM_ALL_BOXED(replication_pad2d_backward); + EXISTING_BDIM_ALL_BOXED(replication_pad3d_backward); + + EXISTING_BDIM_ALL_BOXED(reflection_pad1d_backward); + EXISTING_BDIM_ALL_BOXED(reflection_pad2d_backward); + EXISTING_BDIM_ALL_BOXED(reflection_pad3d_backward); + + EXISTING_BDIM(upsample_bicubic2d); + EXISTING_BDIM(upsample_bilinear2d); + EXISTING_BDIM(upsample_linear1d); + EXISTING_BDIM(upsample_nearest1d); + EXISTING_BDIM(upsample_nearest2d); + EXISTING_BDIM(upsample_nearest3d); + EXISTING_BDIM(upsample_trilinear3d); + EXISTING_BDIM(_upsample_bilinear2d_aa); + EXISTING_BDIM(_upsample_bicubic2d_aa); + + UPSAMPLE_BACKWARD(upsample_bicubic2d_backward); + UPSAMPLE_BACKWARD(upsample_bilinear2d_backward); + UPSAMPLE_BACKWARD(upsample_linear1d_backward); + UPSAMPLE_BACKWARD(upsample_nearest1d_backward); + UPSAMPLE_BACKWARD(upsample_nearest2d_backward); + UPSAMPLE_BACKWARD(upsample_nearest3d_backward); + UPSAMPLE_BACKWARD(upsample_trilinear3d_backward); + UPSAMPLE_BACKWARD(_upsample_bilinear2d_aa_backward); + UPSAMPLE_BACKWARD(_upsample_bicubic2d_aa_backward); + + m.impl("one_hot", one_hot_decomposition_hack); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesNorm.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesNorm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bcf20e514a0ca4ef74a7061b4a200d3a1914aad1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesNorm.cpp @@ -0,0 +1,880 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +namespace at::functorch { + +static bool is_empty_tensor(const Tensor& tensor) { + const auto shape = tensor.sizes(); + return shape.size() == 1 && shape[0] == 0; +} + +static std::optional compute_stat_bdim( + std::optional input_bdim, + const Tensor& stat) { + // There's a weird case where mean, rstd can both have shape (0,). + // It's possible that this is a bug on the PyTorch side. + // When that happens we don't want to return a BatchedTensor. + if (input_bdim.has_value() && !is_empty_tensor(stat)) { + return 0; + } + return std::nullopt; +} + +static Tensor padRight(const Tensor& tensor, std::optional has_bdim, int64_t logical_rank) { + // NB: Batch dim, if it exists, is assumed to be the first dim + auto tensor_logical_rank = rankWithoutBatchDim(tensor, has_bdim); + if (tensor_logical_rank >= logical_rank) { + return tensor; + } + VmapDimVector new_sizes(tensor.sizes().begin(), tensor.sizes().end()); + for (int64_t i = 0; i < logical_rank - tensor_logical_rank; i++) { + new_sizes.push_back(1); + } + return tensor.view(new_sizes); +} + +template +static +std::tuple,Tensor, std::optional,Tensor, std::optional> +batch_norm_batch_rule( + const Tensor& input, std::optional input_bdim, + const std::optional& weight_opt, std::optional weight_bdim, + const std::optional& bias_opt, std::optional bias_bdim, + const std::optional& running_mean_opt, std::optional running_mean_bdim, + const std::optional& running_var_opt, std::optional running_var_bdim, + bool training, double momentum, double eps) { + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + c10::MaybeOwned running_mean_maybe_owned = at::borrow_from_optional_tensor(running_mean_opt); + const auto& running_mean = *running_mean_maybe_owned; + c10::MaybeOwned running_var_maybe_owned = at::borrow_from_optional_tensor(running_var_opt); + const auto& running_var = *running_var_maybe_owned; + TORCH_CHECK(!training || (!input_bdim || ((!running_mean.defined() || running_mean_bdim) && (!running_var.defined() || running_var_bdim))), + "Batch norm got a batched tensor as input while the running_mean or running_var, which will be updated in place, ", + "were not batched.\nIf you are using a module and do not need eval mode, please set `track_running_stats` to be False.", + "If you are using a prebuilt module and do not need eval mode, please see the functorch website for resources on ", + "how to patch your module to work with vmap"); + std::optional bdim_size; + Tensor result0; + Tensor mean; + Tensor rstd; + if (!input_bdim && !running_mean_bdim && !running_var_bdim) { + const auto dummy_weight = at::ones(input.size(1), input.options()); // cudnn and miopen require a weight + const auto dummy_bias = at::zeros(input.size(1), input.options()); // without this, get "strides() called on undefined Tensor" on cuda + auto result = Func(input, dummy_weight, dummy_bias, running_mean_opt, running_var_opt, training, momentum, eps); + result0 = std::get<0>(result).transpose(0, 1); // [C, B, *] + mean = std::move(std::get<1>(result)); + rstd = std::move(std::get<2>(result)); + } else { + bdim_size = get_bdim_size3(input, input_bdim, running_mean, running_mean_bdim, running_var, running_var_bdim); + auto input_ = moveBatchDimToFront(input, input_bdim); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), bdim_size.value()); + input_ = reshape_dim_into(0, /*channels dim*/1, input_); + + std::optional running_mean_; + std::optional running_var_; + if (running_mean.defined()) { + running_mean_ = moveBatchDimToFront(running_mean, running_mean_bdim); + running_mean_ = ensure_has_bdim(*running_mean_, running_mean_bdim.has_value(), bdim_size.value()); + running_mean_ = reshape_dim_into(0, 0, *running_mean_).contiguous(); + } + if (running_var.defined()) { + running_var_ = moveBatchDimToFront(running_var, running_var_bdim); + running_var_ = ensure_has_bdim(*running_var_, running_var_bdim.has_value(), bdim_size.value()); + running_var_ = reshape_dim_into(0, 0, *running_var_).contiguous(); + } + + const auto dummy_weight = at::ones(input_.size(1), input_.options()); // cudnn and miopen require a weight + const auto dummy_bias = at::zeros(input_.size(1), input_.options()); // without this, get "strides() called on undefined Tensor" on cuda + auto result = Func(input_, dummy_weight, dummy_bias, running_mean_, running_var_, training, momentum, eps); + result0 = std::get<0>(result).transpose(0, 1); // [(B0, C), B, *] + mean = std::move(std::get<1>(result)); + rstd = std::move(std::get<2>(result)); + result0 = reshape_dim_outof(0, bdim_size.value(), result0); // [B0, C, B, *] + mean = reshape_dim_outof(0, bdim_size.value(), mean); // [B0, C] + rstd = reshape_dim_outof(0, bdim_size.value(), rstd); // [B0, C] + } + + const auto stats_bdim = compute_stat_bdim(bdim_size, mean); + if (weight.defined()) { + const auto input_logical_rank = rankWithoutBatchDim(input, input_bdim); + auto weight_ = moveBatchDimToFront(weight, weight_bdim); + weight_ = padRight(weight_, weight_bdim, input_logical_rank); + result0 = result0 * weight_; + } + if (bias.defined()) { + const auto result_logical_rank = rankWithoutBatchDim( + result0, + bdim_size.has_value() || weight_bdim.has_value() ? std::optional(0) : std::optional(std::nullopt)); + auto bias_ = moveBatchDimToFront(bias, bias_bdim); + bias_ = padRight(bias_, bias_bdim, result_logical_rank); + result0 = result0 + bias_; + } + result0 = result0.transpose(1, 2); // [B0, B, C, *], because some arg must have been batched, the output must be batched + return std::make_tuple(std::move(result0), 0, std::move(mean), stats_bdim, std::move(rstd), stats_bdim); +} + +template +static +std::tuple> batch_norm_backward_no_weight_bias_batch_rule( + const at::Tensor & grad_out, std::optional grad_out_bdim, + const at::Tensor & input, std::optional input_bdim, + const std::optional & running_mean_opt, std::optional running_mean_bdim, + const std::optional & running_var_opt, std::optional running_var_bdim, + const at::Tensor & mean, std::optional mean_bdim, + const at::Tensor & rstd, std::optional rstd_bdim, + bool training, double eps) { + c10::MaybeOwned running_mean_maybe_owned = at::borrow_from_optional_tensor(running_mean_opt); + const Tensor& running_mean = *running_mean_maybe_owned; + c10::MaybeOwned running_var_maybe_owned = at::borrow_from_optional_tensor(running_var_opt); + const Tensor& running_var = *running_var_maybe_owned; + + if (!grad_out_bdim.has_value() && !input_bdim.has_value() && !running_mean_bdim.has_value() && !running_var_bdim.has_value()) { + // for either of these to have bdims, the input, running_mean, or running_var must have had a bdim + TORCH_INTERNAL_ASSERT(!mean_bdim); + TORCH_INTERNAL_ASSERT(!rstd_bdim); + const auto dummy_weight = at::ones(input.size(1), input.options()); + auto result =Func( + grad_out, input, dummy_weight, running_mean_opt, running_var_opt, mean, rstd, training, eps, {true, false, false}); + return {std::move(std::get<0>(result)), std::nullopt}; + } + + auto grad_out_ = moveBatchDimToFront(grad_out, grad_out_bdim); + auto input_ = moveBatchDimToFront(input, input_bdim); + auto mean_ = moveBatchDimToFront(mean, mean_bdim); + auto rstd_ = moveBatchDimToFront(rstd, rstd_bdim); + + // ensure all inputs have bdim. + const auto bdim_size = get_bdim_size4(grad_out, grad_out_bdim, input, input_bdim, running_mean, running_mean_bdim, running_var, running_var_bdim); + grad_out_ = ensure_has_bdim(grad_out_, grad_out_bdim.has_value(), bdim_size); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), bdim_size); + mean_ = ensure_has_bdim(mean_, mean_bdim.has_value(), bdim_size); + rstd_ = ensure_has_bdim(rstd_, rstd_bdim.has_value(), bdim_size); + + std::optional running_mean_; + std::optional running_var_; + if (running_mean.defined()) { + running_mean_ = moveBatchDimToFront(running_mean, running_mean_bdim); + running_mean_ = ensure_has_bdim(*running_mean_, running_mean_bdim.has_value(), bdim_size); + running_mean_ = reshape_dim_into(0, 0, *running_mean_).contiguous(); + } + if (running_var.defined()) { + running_var_ = moveBatchDimToFront(running_var, running_var_bdim); + running_var_ = ensure_has_bdim(*running_var_, running_var_bdim.has_value(), bdim_size); + running_var_ = reshape_dim_into(0, 0, *running_var_).contiguous(); + } + + input_ = reshape_dim_into(0, /*channels dim*/1, input_); + TORCH_INTERNAL_ASSERT(mean_.dim() == 2); + TORCH_INTERNAL_ASSERT(rstd_.dim() == 2); + mean_ = reshape_dim_into(0, 0, mean_); + rstd_ = reshape_dim_into(0, 0, rstd_); + grad_out_ = grad_out_.transpose(0, 1).flatten(1, 2); // [B0, B, C, *] -> [B, (B0, C), *] + + const auto dummy_weight = at::ones(input_.size(1), input_.options()); + auto result = at::native_batch_norm_backward( + grad_out_.contiguous(), + input_.contiguous(), + dummy_weight, + running_mean_, // contiguous called if there is a tensor given + running_var_, // contiguous called if there is a tensor given + mean_.contiguous(), + rstd_.contiguous(), + training, eps, {true, false, false}); + auto& result0 = std::get<0>(result); + result0 = reshape_dim_outof(1, bdim_size, result0); // [B, B0, C, *] + result0 = result0.transpose(0, 1); // [B0, B, C, *] + return std::make_tuple(std::move(result0), 0); +} + +template +static +std::tuple batch_norm_backward_plumbing( + const at::Tensor & grad_out, + const at::Tensor & input, + const std::optional & weight_opt, + const std::optional & running_mean_opt, + const std::optional & running_var_opt, + const std::optional & save_mean_opt, + const std::optional & save_rstd_opt, + bool training, + double eps, + std::array output_mask) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + c10::MaybeOwned running_mean_maybe_owned = at::borrow_from_optional_tensor(running_mean_opt); + const Tensor& running_mean = *running_mean_maybe_owned; + c10::MaybeOwned running_var_maybe_owned = at::borrow_from_optional_tensor(running_var_opt); + const Tensor& running_var = *running_var_maybe_owned; + // NB: not sure why these are optional...these are required from the forward + TORCH_INTERNAL_ASSERT(save_mean_opt.has_value()); + TORCH_INTERNAL_ASSERT(save_rstd_opt.has_value()); + const Tensor& save_mean = *save_mean_opt; + const Tensor& save_rstd = *save_rstd_opt; + TORCH_INTERNAL_ASSERT(save_mean.defined()); + TORCH_INTERNAL_ASSERT(save_rstd.defined()); + + // plumbing + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "batch_norm_backward_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + auto [grad_out_value, grad_out_bdim] = unwrapTensorAtLevel(grad_out, cur_level); + auto [input_value, input_bdim] = unwrapTensorAtLevel(input, cur_level); + Tensor mean_value; + std::optional weight_value; + std::optional weight_bdim; + if (weight.defined()) { + std::tie(weight_value, weight_bdim) = unwrapTensorAtLevel(weight, cur_level); + } + std::optional running_mean_value; + std::optional running_mean_bdim; + if (running_mean.defined()) { + std::tie(running_mean_value, running_mean_bdim) = unwrapTensorAtLevel(running_mean, cur_level); + } + std::optional running_var_value; + std::optional running_var_bdim; + if (running_var.defined()) { + std::tie(running_var_value, running_var_bdim) = unwrapTensorAtLevel(running_var, cur_level); + } + auto [save_mean_value, save_mean_bdim] = unwrapTensorAtLevel(save_mean, cur_level); + auto [save_rstd_value, save_rstd_bdim] = unwrapTensorAtLevel(save_rstd, cur_level); + + // results + Tensor grad_bias; + Tensor grad_weight; + Tensor grad_input; + + TORCH_INTERNAL_ASSERT(grad_out_value.dim() > 1); // batch_norm can't operate on 1D tensors so the output will be at least 2D + if (output_mask[2]) { + grad_bias = grad_out.transpose(0, 1).sum(range(1, grad_out.dim())); + } + if (output_mask[1] && weight_value.has_value()) { + // NB: output isn't saved... + auto mean = training ? save_mean : running_mean; + auto var = training ? save_rstd : (1 / at::sqrt(running_var + eps)); + const auto normalized_input = (input.transpose(0, 1) - padRight(mean, std::nullopt, input.dim())) * padRight(var, std::nullopt, input.dim()); + const auto expanded_grad_weight = normalized_input * grad_out.transpose(0, 1); + grad_weight = expanded_grad_weight.sum(range(1, grad_out.dim())); + } + if (output_mask[0]) { + const auto grad_normalized_input = weight.defined() ? + grad_out.transpose(0, 1) * padRight(weight, std::nullopt, grad_out.dim()) : grad_out.transpose(0, 1); // [B0, C, B, *] + auto [grad_normalized_input_value, grad_normalized_input_bdim] = + unwrapTensorAtLevel(grad_normalized_input.transpose(0, 1), cur_level); // [B0, B, C, *] + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto results = batch_norm_backward_no_weight_bias_batch_rule( + grad_normalized_input_value, grad_normalized_input_bdim, + input_value, input_bdim, + running_mean_value, running_mean_bdim, + running_var_value, running_var_bdim, + save_mean_value, save_mean_bdim, + save_rstd_value, save_rstd_bdim, + training, eps); + grad_input = makeBatched(std::move(std::get<0>(results)), std::get<1>(results), cur_level); + } + return std::make_tuple(std::move(grad_input), std::move(grad_weight), std::move(grad_bias)); +} + +static std::tuple native_group_norm_plumbing( + const Tensor & input, const std::optional & weight_opt, + const std::optional & bias_opt, int64_t N, int64_t C, + int64_t HxW, int64_t group, double eps) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "native_group_norm_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({input, weight_opt, bias_opt}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::native_group_norm(input, weight_opt, bias_opt, N, C, HxW, group, eps); + } + + auto [input_value, input_bdim] = unwrapTensorAtLevel(input, cur_level); + + Tensor result0; + Tensor mean; + Tensor rstd; + if (input_bdim) { + const auto input_ = reshape_dim_into(*input_bdim, 0, input_value); + const auto bdim_size = input_value.size(*input_bdim); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + std::tie(result0, mean, rstd) = at::native_group_norm(input_, std::nullopt, std::nullopt, N * bdim_size, C, HxW, group, eps); + result0 = makeBatched(reshape_dim_outof(0, bdim_size, result0), 0, cur_level); + mean = makeBatched(reshape_dim_outof(0, bdim_size, mean), 0, cur_level); + rstd = makeBatched(reshape_dim_outof(0, bdim_size, rstd), 0, cur_level); + } else { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + std::tie(result0, mean, rstd) = at::native_group_norm(input_value, std::nullopt, std::nullopt, N, C, HxW, group, eps); + } + + if (weight.defined()) { + const auto padded_weight = padRight(weight, std::nullopt, result0.dim() - 1); + result0 = result0 * padded_weight; + } + + if (bias.defined()) { + const auto padded_bias = padRight(bias, std::nullopt, result0.dim() - 1); + result0 = result0 + padded_bias; + } + + return std::make_tuple(std::move(result0), std::move(mean), std::move(rstd)); +} + +static at::Tensor group_norm_backward_no_weight_bias_batch_rule( + const at::Tensor & grad_out, std::optional grad_out_bdim, + const at::Tensor & input, std::optional input_bdim, + const at::Tensor & mean, std::optional mean_bdim, + const at::Tensor & rstd, std::optional rstd_bdim, + int64_t N, int64_t C, int64_t HxW, int64_t group) { + auto grad_out_ = moveBatchDimToFront(grad_out, grad_out_bdim); + auto input_ = moveBatchDimToFront(input, input_bdim); + auto mean_ = moveBatchDimToFront(mean, mean_bdim); + auto rstd_ = moveBatchDimToFront(rstd, rstd_bdim); + + const auto bdim_size = get_bdim_size2(grad_out, grad_out_bdim, input, input_bdim); + grad_out_ = ensure_has_bdim(grad_out_, grad_out_bdim.has_value(), bdim_size); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), bdim_size); + mean_ = ensure_has_bdim(mean_, mean_bdim.has_value(), bdim_size); + rstd_ = ensure_has_bdim(rstd_, rstd_bdim.has_value(), bdim_size); + + grad_out_ = reshape_dim_into(0, 0, grad_out_); // [B0 * N, C, *] + input_ = reshape_dim_into(0, 0, input_); // [B0 * N, C, *] + mean_ = reshape_dim_into(0, 0, mean_); // [B0 * N, G] + rstd_ = reshape_dim_into(0, 0, rstd_); // [B0 * N, G] + + auto result0 = std::get<0>(native_group_norm_backward( + grad_out_.contiguous(), + input_.contiguous(), + mean_.contiguous(), + rstd_.contiguous(), + std::nullopt, N * bdim_size, C, HxW, group, {true, false, false})); + return reshape_dim_outof(0, bdim_size, result0); +} + +static std::tuple native_group_norm_backward_plumbing( + const Tensor & grad_out, const Tensor & input, const Tensor & mean, + const Tensor & rstd, const std::optional & weight_opt, + int64_t N, int64_t C, int64_t HxW, int64_t group, std::array output_mask +) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + + // plumbing + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "native_group_norm_backward_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({grad_out, input, mean, rstd, weight_opt}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::native_group_norm_backward(grad_out, input, mean, rstd, weight_opt, N, C, HxW, group, output_mask); + } + + auto [input_value, input_bdim] = unwrapTensorAtLevel(input, cur_level); + Tensor weight_value; + std::optional weight_bdim; + if (weight.defined()){ + std::tie(weight_value, weight_bdim) = unwrapTensorAtLevel(weight, cur_level); + } + auto [mean_value, mean_bdim] = unwrapTensorAtLevel(mean, cur_level); + auto [rstd_value, rstd_bdim] = unwrapTensorAtLevel(rstd, cur_level); + + // results + Tensor grad_input; + Tensor grad_weight; + Tensor grad_bias; + + TORCH_INTERNAL_ASSERT(grad_out.dim() > 1); // group_norm can't operate on 1D tensors so the output will be at least 2D + if (output_mask[2]) { + grad_bias = grad_out.transpose(0, 1).sum(range(1, grad_out.dim())); + } + + if (output_mask[1] && weight.defined()) { + const auto reshaped_input = reshape_dim_outof(1, group, input); + const auto normalized_input = (reshaped_input - padRight(mean, std::nullopt, reshaped_input.dim())) * padRight(rstd, std::nullopt, reshaped_input.dim()); + const auto expanded_grad_weight = reshape_dim_into(1, 1, normalized_input) * grad_out; + grad_weight = expanded_grad_weight.transpose(0, 1).sum(range(1, expanded_grad_weight.dim())); + } + + if (output_mask[0]) { + const auto grad_normalized_input = weight.defined() ? + grad_out * padRight(weight, std::nullopt, grad_out.dim() - 1) : grad_out; + auto [grad_normalized_input_value, grad_normalized_input_bdim] = + unwrapTensorAtLevel(grad_normalized_input, cur_level); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto tensor = group_norm_backward_no_weight_bias_batch_rule( + grad_normalized_input_value, grad_normalized_input_bdim, + input_value, input_bdim, + mean_value, mean_bdim, + rstd_value, rstd_bdim, + N, C, HxW, group + ); + grad_input = makeBatched(std::move(tensor), 0, cur_level); + } + return std::make_tuple(std::move(grad_input), std::move(grad_weight), std::move(grad_bias)); +} + +static bool has_same_shape( + const Tensor& tensor, std::optional tensor_bdim, + c10::SymIntArrayRef normalized_shape) { + if (!tensor.defined()) { + return true; + } + if (rankWithoutBatchDim(tensor, tensor_bdim) != static_cast(normalized_shape.size())) { + return false; + } + const auto tensor_shape = tensor.sizes(); + for (const auto i : c10::irange(normalized_shape.size())) { + auto j = i; + // (0, 1, 2), 1 -> (0, 2, 3) + if (tensor_bdim.has_value() && static_cast(i) >= tensor_bdim.value()) { + j = j + 1; + } + if (normalized_shape[i] != tensor_shape[j]) { + return false; + } + } + return true; +} + +static C10_ALWAYS_INLINE void check_same_shape( + const Tensor& tensor, std::optional tensor_bdim, + c10::SymIntArrayRef normalized_shape, const std::string& name) { + TORCH_CHECK(has_same_shape(tensor, tensor_bdim, normalized_shape), + "Expected ", name, " to be of same shape as normalized_shape, but got ", + name, " of shape ", + tensor.sizes(), + " and normalized_shape = ", + normalized_shape); +} + +// Ugh, hard to deduplicate +static C10_ALWAYS_INLINE void _check_layer_norm_inputs( + SymIntArrayRef normalized_shape, + const Tensor& weight, std::optional weight_bdim, + const Tensor& bias, std::optional bias_bdim) { + + const auto normalized_ndim = normalized_shape.size(); + TORCH_CHECK( + normalized_ndim >= 1, + "Expected normalized_shape to be at least 1-dimensional, i.e., ", + "containing at least one element, but got normalized_shape = ", + normalized_shape); + check_same_shape(weight, weight_bdim, normalized_shape, "weight"); + check_same_shape(bias, bias_bdim, normalized_shape, "weight"); +} + +static std::tuple,Tensor, std::optional,Tensor, std::optional> +native_layer_norm_batch_rule( + const Tensor& input, std::optional input_bdim, + c10::SymIntArrayRef normalized_shape, + const std::optional& weight_opt, std::optional weight_bdim, + const std::optional& bias_opt, std::optional bias_bdim, + double eps) { + auto input_ = moveBatchDimToFront(input, input_bdim); + if (!weight_bdim && !bias_bdim) { + auto [result0, mean, rstd] = at::native_layer_norm_symint(input_, normalized_shape, weight_opt, bias_opt, eps); + const auto stats_bdim = compute_stat_bdim(input_bdim, mean); + return std::make_tuple(std::move(result0), 0, std::move(mean), stats_bdim, std::move(rstd), stats_bdim); + } + + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + _check_layer_norm_inputs(normalized_shape, weight, weight_bdim, bias, bias_bdim); + + const auto input_logical_rank = rankWithoutBatchDim(input, input_bdim); + const auto result = at::native_layer_norm_symint(input_, normalized_shape, std::nullopt, std::nullopt, eps); + auto [result0, mean, rstd] = result; + const auto stats_bdim = compute_stat_bdim(input_bdim, mean); + + if (weight.defined()) { + auto weight_ = moveBatchDimToFront(weight, weight_bdim); + weight_ = maybePadToLogicalRank(weight_, /*has_bdim*/weight_bdim, input_logical_rank); + result0 = result0 * weight_; + } + if (bias.defined()) { + const auto result_logical_rank = rankWithoutBatchDim( + result0, + input_bdim.has_value() || weight_bdim.has_value() ? std::optional(0) : std::optional(std::nullopt)); + auto bias_ = moveBatchDimToFront(bias, bias_bdim); + bias_ = maybePadToLogicalRank(bias_, /*has_bdim*/bias_bdim, result_logical_rank); + result0 = result0 + bias_; + } + return std::make_tuple(std::move(result0), 0, std::move(mean), stats_bdim, std::move(rstd), stats_bdim); +} + +static std::tuple> native_layer_norm_backward_no_weight_bias_batch_rule( + const at::Tensor & grad_out, std::optional grad_out_bdim, + const at::Tensor & input, std::optional input_bdim, + at::IntArrayRef normalized_shape, + const at::Tensor & mean, std::optional mean_bdim, + const at::Tensor & rstd, std::optional rstd_bdim) { + + if (!grad_out_bdim.has_value() && !input_bdim.has_value() && + !mean_bdim.has_value() && !rstd_bdim.has_value()) { + auto result = at::native_layer_norm_backward( + grad_out, input, normalized_shape, mean, rstd, std::nullopt, std::nullopt, {true, false, false}); + return std::make_tuple(std::get<0>(std::move(result)), std::nullopt); + } + + auto grad_out_ = moveBatchDimToFront(grad_out, grad_out_bdim); + auto input_ = moveBatchDimToFront(input, input_bdim); + auto mean_ = moveBatchDimToFront(mean, mean_bdim); + auto rstd_ = moveBatchDimToFront(rstd, rstd_bdim); + + // ensure grad_out / input have bdim. + const auto bdim_size = get_bdim_size2(grad_out, grad_out_bdim, input, input_bdim); + grad_out_ = ensure_has_bdim(grad_out_, grad_out_bdim.has_value(), bdim_size); + input_ = ensure_has_bdim(input_, input_bdim.has_value(), bdim_size); + mean_ = ensure_has_bdim(mean_, mean_bdim.has_value(), bdim_size); + rstd_ = ensure_has_bdim(rstd_, rstd_bdim.has_value(), bdim_size); + + auto result = at::native_layer_norm_backward( + grad_out_.contiguous(), + input_.contiguous(), + normalized_shape, + mean_.contiguous(), + rstd_.contiguous(), + std::nullopt, std::nullopt, {true, false, false}); + + return std::make_tuple(std::get<0>(result), 0); +} + +static std::tuple native_layer_norm_backward_plumbing( + const at::Tensor & grad_out, + const at::Tensor & input, + at::IntArrayRef normalized_shape, + const at::Tensor & mean, + const at::Tensor & rstd, + const std::optional & weight_opt, + const std::optional & bias_opt, + std::array output_mask) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + // plumbing + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "native_layer_norm_backward_plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + if (!areAnyBatchedAtLevel({grad_out, input, mean, rstd, weight_opt, bias_opt}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::native_layer_norm_backward(grad_out, input, normalized_shape, mean, rstd, + weight_opt, bias_opt, output_mask); + } + auto [grad_out_value, grad_out_bdim] = unwrapTensorAtLevel(grad_out, cur_level); + auto [input_value, input_bdim] = unwrapTensorAtLevel(input, cur_level); + auto [mean_value, mean_bdim] = unwrapTensorAtLevel(mean, cur_level); + auto [rstd_value, rstd_bdim] = unwrapTensorAtLevel(rstd, cur_level); + std::optional weight_value; + std::optional weight_bdim; + if (weight.defined()) { + std::tie(weight_value, weight_bdim) = unwrapTensorAtLevel(weight, cur_level); + } + std::optional bias_value; + std::optional bias_bdim; + if (bias.defined()) { + std::tie(bias_value, bias_bdim) = unwrapTensorAtLevel(bias, cur_level); + } + + // results + Tensor grad_bias; + Tensor grad_weight; + Tensor grad_input; + + if (output_mask[2] && bias_value.has_value()) { + const auto num_front_dims_to_reduce = grad_out.dim() - normalized_shape.size(); + if (num_front_dims_to_reduce == 0) { + grad_bias = grad_out; + } else { + grad_bias = grad_out.sum(range(0, static_cast(num_front_dims_to_reduce))); + } + } + if (output_mask[1] && weight_value.has_value()) { + // NB: output isn't saved... + const auto normalized_input = (input - mean) * rstd; + const auto expanded_grad_weight = normalized_input * grad_out; + const auto num_front_dims_to_reduce = + expanded_grad_weight.dim() - normalized_shape.size(); + if (num_front_dims_to_reduce == 0) { + grad_weight = expanded_grad_weight; + } else { + grad_weight = expanded_grad_weight.sum(range(0, static_cast(num_front_dims_to_reduce))); + } + } + if (output_mask[0]) { + const auto grad_normalized_input = weight.defined() ? + grad_out * weight : grad_out; + auto [grad_normalized_input_value, grad_normalized_input_bdim] = + unwrapTensorAtLevel(grad_normalized_input, cur_level); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto results = native_layer_norm_backward_no_weight_bias_batch_rule( + grad_normalized_input_value, grad_normalized_input_bdim, + input_value, input_bdim, + normalized_shape, + mean_value, mean_bdim, + rstd_value, rstd_bdim); + grad_input = makeBatched(std::get<0>(results), std::get<1>(results), cur_level); + } + return std::make_tuple(std::move(grad_input), std::move(grad_weight), std::move(grad_bias)); +} + +template +struct NativeBatchNormBatchRuleHelper { + static std::tuple,Tensor, std::optional,Tensor, std::optional> apply( + const Tensor& input, std::optional input_bdim, + const std::optional& weight_opt, std::optional weight_bdim, + const std::optional& bias_opt, std::optional bias_bdim, + const std::optional& running_mean_opt, std::optional running_mean_bdim, + const std::optional& running_var_opt, std::optional running_var_bdim, + bool training, double momentum, double eps) { + return batch_norm_batch_rule( + input, input_bdim, weight_opt, weight_bdim, bias_opt, bias_bdim, + running_mean_opt, running_mean_bdim, running_var_opt, running_var_bdim, training, momentum, eps); + } +}; + +template +struct CudnnBatchNormBatchRuleHelper { + static std::tuple,Tensor, std::optional,Tensor, std::optional,Tensor, std::optional> apply( + const Tensor& input, std::optional input_bdim, + const Tensor& weight_opt, std::optional weight_bdim, + const std::optional& bias_opt, std::optional bias_bdim, + const std::optional& running_mean_opt, std::optional running_mean_bdim, + const std::optional& running_var_opt, std::optional running_var_bdim, + bool training, double momentum, double eps) { + auto reserve = at::empty({0}, input.options().dtype(kByte)); // in experiments, reserve was never set to anything other than empty by cuda + auto res = batch_norm_batch_rule( + input, input_bdim, weight_opt, weight_bdim, bias_opt, bias_bdim, + running_mean_opt, running_mean_bdim, running_var_opt, running_var_bdim, training, momentum, eps); + return std::tuple_cat(res, std::make_tuple(reserve, std::nullopt)); + } +}; + +template +struct MiopenBatchNormBatchRuleHelper { + static std::tuple,Tensor, std::optional,Tensor, std::optional> apply( + const Tensor& input, std::optional input_bdim, + const Tensor& weight_opt, std::optional weight_bdim, + const std::optional& bias_opt, std::optional bias_bdim, + const std::optional& running_mean_opt, std::optional running_mean_bdim, + const std::optional& running_var_opt, std::optional running_var_bdim, + bool training, double momentum, double eps) { + return batch_norm_batch_rule( + input, input_bdim, weight_opt, weight_bdim, bias_opt, bias_bdim, + running_mean_opt, running_mean_bdim, running_var_opt, running_var_bdim, training, momentum, eps); + } +}; + +#define NATIVE_BATCH_NORM_BATCH_RULE(fn) SINGLE_ARG(\ + NativeBatchNormBatchRuleHelper<\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn)>::apply) + +#define CUDNN_BATCH_NORM_BATCH_RULE(fn) SINGLE_ARG(\ + CudnnBatchNormBatchRuleHelper<\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn)>::apply) + +#define MIOPEN_BATCH_NORM_BATCH_RULE(fn) SINGLE_ARG(\ + MiopenBatchNormBatchRuleHelper<\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn)>::apply) + +template +struct NativeBatchNormBackwardBatchRuleHelper { + static std::tuple apply( + const at::Tensor & grad_out, + const at::Tensor & input, + const std::optional & weight_opt, + const std::optional & running_mean_opt, + const std::optional & running_var_opt, + const std::optional & save_mean_opt, + const std::optional & save_rstd_opt, + bool training, + double eps, + std::array output_mask) { + + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "NativeBatchNormBackwardBatchRuleHelper.apply"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({grad_out, input, weight_opt, running_mean_opt, + running_var_opt, save_mean_opt, save_rstd_opt}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::native_batch_norm_backward(grad_out, input, weight_opt, + running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, + training, eps, output_mask); + } + + return batch_norm_backward_plumbing( + grad_out, input, weight_opt, running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, training, eps, output_mask); + } +}; + +template +struct CudnnBatchNormBackwardBatchRuleHelper { + static std::tuple apply( + const at::Tensor & input, + const at::Tensor & grad_out, + const at::Tensor & weight, + const std::optional & running_mean_opt, + const std::optional & running_var_opt, + const std::optional & save_mean_opt, + const std::optional & save_rstd_opt, + double eps, + const at::Tensor & reserve) { + + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "CudnnBatchNormBackwardBatchRuleHelper.apply"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({input, grad_out, weight, running_mean_opt, + running_var_opt, save_mean_opt, save_rstd_opt, reserve}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::cudnn_batch_norm_backward(input, grad_out, weight, + running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, eps, reserve); + } + + return batch_norm_backward_plumbing( + grad_out, input, weight, running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, true, eps, {true, true, true}); + } +}; + +template +struct MiopenBatchNormBackwardBatchRuleHelper { + static std::tuple apply( + const at::Tensor & input, + const at::Tensor & grad_out, + const at::Tensor & weight, + const std::optional & running_mean_opt, + const std::optional & running_var_opt, + const std::optional & save_mean_opt, + const std::optional & save_rstd_opt, + double eps) { + + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "MiopenBatchNormBackwardBatchRuleHelper.apply"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + + if (!areAnyBatchedAtLevel({input, grad_out, weight, running_mean_opt, + running_var_opt, save_mean_opt, save_rstd_opt}, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::miopen_batch_norm_backward(input, grad_out, weight, + running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, eps); + } + + return batch_norm_backward_plumbing( + grad_out, input, weight, running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, true, eps, {true, true, true}); + } +}; + +#define NATIVE_BATCH_NORM_BACKWARD_BATCH_RULE(fn) SINGLE_ARG(\ + NativeBatchNormBackwardBatchRuleHelper<\ + decltype(&ATEN_FN(fn)),\ + &ATEN_FN(fn)>::apply) + +#define CUDNN_BATCH_NORM_BACKWARD_BATCH_RULE(fn) SINGLE_ARG(\ + CudnnBatchNormBackwardBatchRuleHelper<\ + decltype(&fn),\ + &fn>::apply) + +#define MIOPEN_BATCH_NORM_BACKWARD_BATCH_RULE(fn) SINGLE_ARG(\ + MiopenBatchNormBackwardBatchRuleHelper<\ + decltype(&fn),\ + &fn>::apply) + +static std::tuple cudnn_batch_norm_backward_wrapper( + const at::Tensor & grad_out, + const at::Tensor & input, + const at::Tensor& weight_opt, + const std::optional & running_mean_opt, + const std::optional & running_var_opt, + const std::optional & save_mean_opt, + const std::optional & save_rstd_opt, + bool training, + double eps, + std::array output_mask) { + TORCH_INTERNAL_ASSERT(!training); + auto reserve = at::empty({0}, input.options().dtype(kByte)); + return at::cudnn_batch_norm_backward(input, grad_out, weight_opt, running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, eps, reserve); + } + +static std::tuple miopen_batch_norm_backward_wrapper( + const at::Tensor & grad_out, + const at::Tensor & input, + const at::Tensor& weight_opt, + const std::optional & running_mean_opt, + const std::optional & running_var_opt, + const std::optional & save_mean_opt, + const std::optional & save_rstd_opt, + bool training, + double eps, + std::array output_mask) { + TORCH_INTERNAL_ASSERT(!training); // this should be ensured by batch_norm_impl + return at::miopen_batch_norm_backward(input, grad_out, weight_opt, running_mean_opt, running_var_opt, save_mean_opt, save_rstd_opt, eps); + } + +// NB: This is NOT good. In the ideal world, we do NOT want to convert the new legit op back into native_batch_norm +// as native_batch_norm has a problematic schema--it promises it is functional when it is not. However, vmap doesn't +// work with dynamo anyway so we gain some buffer room to do wrong things here. The (reasonable) hope is that we will +// make native_batch_norm composite implicit within a few weeks and we can fix this before vmap works with dynamo. +static std::tuple _native_batch_norm_legit_batch( + const Tensor& self, const std::optional& weight_opt, const std::optional& bias_opt, + Tensor& running_mean, Tensor& running_var, bool train, double momentum, double eps) { + return at::native_batch_norm(self, weight_opt, bias_opt, running_mean, running_var, train, momentum, eps); +} + +static std::tuple _native_batch_norm_legit_no_stats_batch( + const Tensor& self, const std::optional& weight_opt, const std::optional& bias_opt, + bool train, double momentum, double eps) { + return at::native_batch_norm(self, weight_opt, bias_opt, Tensor(), Tensor(), train, momentum, eps); +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT(native_batch_norm, NATIVE_BATCH_NORM_BATCH_RULE(native_batch_norm)); + VMAP_SUPPORT(cudnn_batch_norm, CUDNN_BATCH_NORM_BATCH_RULE(cudnn_batch_norm)); + VMAP_SUPPORT(miopen_batch_norm, MIOPEN_BATCH_NORM_BATCH_RULE(miopen_batch_norm)); + m.impl("_native_batch_norm_legit", _native_batch_norm_legit_batch); + m.impl("_native_batch_norm_legit.no_stats", _native_batch_norm_legit_no_stats_batch); + m.impl("native_batch_norm_backward", NATIVE_BATCH_NORM_BACKWARD_BATCH_RULE(native_batch_norm_backward)); + m.impl("cudnn_batch_norm_backward", CUDNN_BATCH_NORM_BACKWARD_BATCH_RULE(at::functorch::cudnn_batch_norm_backward_wrapper)); + m.impl("miopen_batch_norm_backward", MIOPEN_BATCH_NORM_BACKWARD_BATCH_RULE(at::functorch::miopen_batch_norm_backward_wrapper)); + m.impl("native_group_norm", native_group_norm_plumbing); + m.impl("native_group_norm_backward", native_group_norm_backward_plumbing); + VMAP_SUPPORT(native_layer_norm, native_layer_norm_batch_rule); + m.impl("native_layer_norm_backward", native_layer_norm_backward_plumbing); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesPooling.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesPooling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58737f74a57338a43816564a74016a6cdb9e0819 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesPooling.cpp @@ -0,0 +1,74 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include + +namespace at::functorch { + +template +static std::tuple,Tensor, std::optional> +max_pool_with_indices_batch_rule_helper( + const Tensor& self, std::optional self_bdim, + IntArrayRef kernel_size, IntArrayRef stride, + IntArrayRef padding, IntArrayRef dilation, bool ceil_mode, int64_t n, Func pooling_fn) { + + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + TORCH_INTERNAL_ASSERT(logical_rank == n + 1 || logical_rank == n + 2); + // Tensor[B, logical_rank...] -> just call max_poolnd + if (logical_rank == n + 1) { + auto self_ = moveBatchDimToFront(self, self_bdim); + auto result = pooling_fn( + self_, kernel_size, stride, padding, dilation, ceil_mode); + return std::make_tuple(std::move(std::get<0>(result)), 0, std::move(std::get<1>(result)), 0); + } + // Tensor[B, N, logical_rank...] -> Tensor[B * N, logical_rank...] + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto bdim_size = self.size(self_bdim.value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto self_ = reshape_dim_into(self_bdim.value(), 0, self); + auto result = pooling_fn( + self_, kernel_size, stride, padding, dilation, ceil_mode); + return std::make_tuple( + reshape_dim_outof(0, bdim_size, std::get<0>(result)), 0, + reshape_dim_outof(0, bdim_size, std::get<1>(result)), 0); +} + +static std::tuple,Tensor, std::optional> +max_pool3d_with_indices_batch_rule( + const Tensor& self, std::optional self_bdim, + IntArrayRef kernel_size, IntArrayRef stride, + IntArrayRef padding, IntArrayRef dilation, bool ceil_mode) { + return max_pool_with_indices_batch_rule_helper(self, self_bdim, kernel_size, stride, padding, dilation, ceil_mode, 3, at::max_pool3d_with_indices); +} + +static std::tuple,Tensor, std::optional> +max_pool2d_with_indices_batch_rule( + const Tensor& self, std::optional self_bdim, + IntArrayRef kernel_size, IntArrayRef stride, + IntArrayRef padding, IntArrayRef dilation, bool ceil_mode) { + return max_pool_with_indices_batch_rule_helper(self, self_bdim, kernel_size, stride, padding, dilation, ceil_mode, 2, at::max_pool2d_with_indices); +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + EXISTING_BDIM(_adaptive_avg_pool2d); + EXISTING_BDIM_ALL_BOXED(_adaptive_avg_pool2d_backward); + EXISTING_BDIM(_adaptive_avg_pool3d); + EXISTING_BDIM_ALL_BOXED(_adaptive_avg_pool3d_backward); + EXISTING_BDIM(avg_pool2d); + EXISTING_BDIM(avg_pool3d); + EXISTING_BDIM_ALL_BOXED(avg_pool2d_backward); + EXISTING_BDIM_ALL_BOXED(avg_pool3d_backward); + EXISTING_BDIM_ALL_BOXED(adaptive_max_pool2d); + EXISTING_BDIM_ALL_BOXED(adaptive_max_pool3d); + ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(3, adaptive_max_pool2d_backward, 2); + ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(4, adaptive_max_pool3d_backward, 2); + VMAP_SUPPORT(max_pool2d_with_indices, max_pool2d_with_indices_batch_rule); + VMAP_SUPPORT(max_pool3d_with_indices, max_pool3d_with_indices_batch_rule); + ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(3, max_pool2d_with_indices_backward, 2); + ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(4, max_pool3d_with_indices_backward, 2); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesRandomness.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesRandomness.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f2a3803a6aa2451660279ec8ea4aa11cfff4844 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesRandomness.cpp @@ -0,0 +1,500 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +#include + +// This file contains batching rules for random operations. These are different +// from our regular batching rules: regular batching rules get registered to the +// FuncTorchBatched key, but batching rules for random operations get +// registered to FuncTorchVmapMode. This is because we need to interpose on +// random operations even if they're not on a BatchedTensor. + +// NOLINTBEGIN(bugprone-unchecked-optional-access) +namespace at::functorch { + +template +static Tensor random_batching_rule(SymIntArrayRef shape, ExtraArgs... extra_args) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_layer.has_value()); + c10::SmallVector shapeVec(1, maybe_layer->batchSize()); + shapeVec.reserve(shape.size() + 1); + shapeVec.insert(shapeVec.end(), shape.begin(), shape.end()); + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness); + if (randomness == RandomnessType::Different) { + return makeBatched(Func(shapeVec, std::forward(extra_args)...), 0, maybe_layer->layerId()); + } else { + return Func(shape, std::forward(extra_args)...); + } +} + +template +static Tensor& random_inplace_batching_rule(Tensor& self, ExtraArgs... extra_args) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_layer.has_value()); + const auto cur_level = maybe_layer->layerId(); + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + self_value = moveBatchDimToFront(std::move(self_value), self_bdim); + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness); + TORCH_CHECK( + !(randomness == RandomnessType::Different && !self_bdim), + "vmap: Cannot ask for different inplace randomness on an unbatched tensor. This will appear like same randomness. ", + "If this is necessary for your usage, please file an issue with functorch."); + if (randomness == RandomnessType::Same && self_bdim) { + auto intermediate = empty(self.sizes(), self.options()); + Func(intermediate, std::forward(extra_args)...); + self.copy_(intermediate); // batching should make this just work out... + return self; + } else { + Func(self_value, std::forward(extra_args)...); + return self; + } +} + +static Tensor& bernoulli_inplace_Tensor_batching_rule(Tensor& self, const Tensor& p_, std::optional gen) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_layer.has_value()); + auto cur_level = maybe_layer->layerId(); + RandomnessType randomness = maybe_layer->randomness(); + + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + + auto [other_value, other_bdim] = unwrapTensorAtLevel(p_, cur_level); + + check_randomness(randomness, other_bdim.has_value()); + + if (!self_bdim && other_bdim) { + vmapIncompatibleInplaceError("inplace bernoulli"); + } + + // compute max logical rank + auto self_logical_rank = rankWithoutBatchDim(self_value, self_bdim); + auto other_logical_rank = rankWithoutBatchDim(other_value, other_bdim); + auto max_logical_rank = std::max(self_logical_rank, other_logical_rank); + + auto self_ = moveBatchDimToFront(self_value, self_bdim); + auto other_ = moveBatchDimToFront(other_value, other_bdim); + + // If the dimensions aren't aligned, we need to line them up. + // Tensor[B, 3] + Tensor[2, 5, 3] -> Tensor[B, 1, 1, 3] + Tensor[2, 5, 3] + // Note that only tensors that have a batch dim need to be modified. + // Tensor[B, 2, 3, 5] + Tensor[5] -> no changes needed + self_ = maybePadToLogicalRank(self_, self_bdim, max_logical_rank); + other_ = maybePadToLogicalRank(other_, other_bdim, max_logical_rank); + TORCH_CHECK( + !(randomness == RandomnessType::Different && !self_bdim), + "vmap: Cannot ask for different inplace randomness on an unbatched tensor. This will appear like same randomness. ", + "If this is necessary for your usage, please file an issue with functorch."); + if (randomness == RandomnessType::Same && self_bdim) { + auto intermediate = empty(self.sizes(), self.options()); + intermediate.bernoulli_(other_, std::move(gen)); + self.copy_(intermediate); // batching should make this just work out... + return self; + } else { + self_.bernoulli_(other_, std::move(gen)); + return self; + } +} + +template +static Tensor randperm_batching_rule(int64_t n, ExtraArgs... extra_args) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + auto const batch_size = maybe_layer->batchSize(); + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness); + if (randomness == RandomnessType::Different) { + std::vector stackedList(batch_size.guard_int(__FILE__, __LINE__)); + for (int64_t idx = 0; idx < batch_size; ++idx) { + // since this is done in a loop, need to pass by reference for generator to update + stackedList[idx] = Func(n, extra_args...); + } + return makeBatched(at::stack(stackedList), 0, maybe_layer->layerId()); + } else { + return Func(n, std::forward(extra_args)...); + } +} + +template +static Tensor unary_pointwise_random_batch_rule(const Tensor& tensor, ExtraArgs... extra_args) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + const auto cur_level = maybe_layer->layerId(); + + auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(tensor, cur_level); + tensor_value = moveBatchDimToFront(tensor_value, tensor_bdim); + + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness, tensor_bdim.has_value()); + auto shape = tensor_value.sizes(); + VmapSymDimVector shapeVec(1, maybe_layer->batchSize()); + shapeVec.reserve(shape.size() + 1); + shapeVec.insert(shapeVec.end(), shape.begin(), shape.end()); + + if (randomness == RandomnessType::Different && !tensor_bdim) { + tensor_value = tensor_value.expand_symint(shapeVec); + } + auto out = Func(tensor_value, std::forward(extra_args)...); + if (randomness == RandomnessType::Same && !tensor_bdim) { + return out; + } + return makeBatched(out, 0, cur_level); +} + +template +static Tensor tensor_like_random_batch_rule(const Tensor& self, ExtraArgs... extra_args) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + const auto cur_level = maybe_layer->layerId(); + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness); + + auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(self, cur_level); + tensor_value = moveBatchDimToFront(tensor_value, tensor_bdim); + + if (randomness == RandomnessType::Same && tensor_bdim) { + tensor_value = tensor_value[0]; + } else if (randomness == RandomnessType::Different && !tensor_bdim) { + auto shape = tensor_value.sizes(); + VmapSymDimVector shapeVec(1, maybe_layer->batchSize()); + shapeVec.reserve(shape.size() + 1); + shapeVec.insert(shapeVec.end(), shape.begin(), shape.end()); + tensor_value = tensor_value.expand_symint(shapeVec); + } + + auto res = Func(tensor_value, std::forward(extra_args)...); + return (randomness == RandomnessType::Same) ? res : makeBatched(res, 0, cur_level); +} + +static std::tuple native_dropout_batching_rule(const Tensor& tensor, double p, std::optional train) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + const auto cur_level = maybe_layer->layerId(); + RandomnessType randomness = maybe_layer->randomness(); + + auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(tensor, cur_level); + tensor_value = moveBatchDimToFront(tensor_value, tensor_bdim); + + if (!train.has_value() || *train) { + check_randomness(randomness); // if we are in eval mode, we don't use about randomness + } + + if ((train.has_value() && !*train) || + randomness == RandomnessType::Different) { + if (!tensor_bdim) { + // if tensor is unbatched, add batch dim before + // calling dropout. + auto shape = tensor_value.sizes(); + VmapSymDimVector shapeVec(1, maybe_layer->batchSize()); + shapeVec.reserve(shape.size() + 1); + shapeVec.insert(shapeVec.end(), shape.begin(), shape.end()); + tensor_value = tensor_value.expand_symint(shapeVec); + } + auto [output, mask] = at::native_dropout(tensor_value, p, train); + return std::make_tuple( + makeBatched(output, 0, cur_level), + makeBatched(mask, 0, cur_level)); + } + + // repeated code from the CPU kernel since the CUDA one doesn't call bernoulli_ explicitly + double p1m = 1. - p; + // Check for probability of zero to avoid divide by zero and NaN results + double scale = p1m == 0 ? 0. : 1. / p1m; + Tensor mask = at::empty_like(tensor, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + mask.bernoulli_(p1m); + auto output = tensor.mul(mask).mul_(scale); + return std::make_tuple(std::move(output), std::move(mask)); +} + +static Tensor native_dropout_backward_batch_rule(const Tensor& grad_out, const Tensor& mask, double scale){ + Tensor result = grad_out * mask * scale; + return result; +} + +static Tensor multinomial_batching_rule(const Tensor& self, const int64_t num_samples, const bool replacement, std::optional generator) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchVmapMode); + auto maybe_layer = maybeCurrentDynamicLayer(); + const auto cur_level = maybe_layer->layerId(); + + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + self_value = moveBatchDimToFront(self_value, self_bdim); + + RandomnessType randomness = maybe_layer->randomness(); + check_randomness(randomness, self_bdim.has_value()); + + if (randomness == RandomnessType::Different) { + // 1D cases: S -> BS -> multinomial(BS) + // BS -> multinomial(BS) + // + // 2D cases: MS -> BMS -> (BM)S -> multinomial((BM)S) -> (BM)S -> BMS + // BMS -> (BM)S -> multinomial((BM)S) -> (BM)S -> BMS + const auto is_2D_case = rankWithoutBatchDim(self_value, self_bdim) == 2; + if (!self_bdim.has_value()) { + self_value = ensure_has_bdim(self_value, self_bdim.has_value(), maybe_layer->batchSize()); + } + if (is_2D_case) { + self_value = reshape_dim_into(0, 0, self_value); + } + auto out = multinomial(self_value, num_samples, replacement, std::move(generator)); + if (is_2D_case) { + out = reshape_dim_outof_symint(0, maybe_layer->batchSize(), out); + } + return makeBatched(out, 0, cur_level);; + } + + TORCH_INTERNAL_ASSERT(randomness == RandomnessType::Same); // check_randomness eliminates error randomness + TORCH_INTERNAL_ASSERT(!self_bdim.has_value()); // check_randomness eliminates same randomness with batched input + // Must be same randomness with unbatched input + // 1D case: S -> multinomial(S) -> S + // 2D case: MS -> multinomial(MS) -> MS + return multinomial(self_value, num_samples, replacement, std::move(generator)); +} + +template +struct RandomBatchRuleHelper; + +template +struct RandomBatchRuleHelper> { + static Tensor apply(SymIntArrayRef shape, T... extra_args) { + return random_batching_rule(shape, std::forward(extra_args)...); + } +}; + +template +static Tensor rand_int_wrapper(SymIntArrayRef shape, c10::SymInt high, T... extra_args) { + return Func(high, shape, std::forward(extra_args)...); +} + +template +struct RandomInplaceBatchRuleHelper; + +template +struct RandomInplaceBatchRuleHelper> { + static Tensor& apply(Tensor& self, T... extra_args) { + return random_inplace_batching_rule(self, std::forward(extra_args)...); + } +}; + +template +struct RandIntBatchRuleHelper; + +template +struct RandIntBatchRuleHelper> { + static Tensor apply(c10::SymInt high, SymIntArrayRef shape, T... extra_args) { + return random_batching_rule), + &rand_int_wrapper, + c10::SymInt, T...>(shape, std::move(high), std::forward(extra_args)...); + } +}; + +template +static Tensor rand_int_low_wrapper(SymIntArrayRef shape, T0 scalar0, T1 scalar1, T... extra_args) { + return Func(scalar0, scalar1, shape, std::forward(extra_args)...); +} + +template +struct RandTwoLeadingScalarsBatchRuleHelper; + +template +struct RandTwoLeadingScalarsBatchRuleHelper> { + static Tensor apply(T0 scalar0, T1 scalar1, SymIntArrayRef shape, T... extra_args) { + return random_batching_rule), + &rand_int_low_wrapper, + T0, T1, T...>(shape, scalar0, scalar1, std::forward(extra_args)...); + } +}; + +template +struct RandpermBatchRuleHelper; + +template +struct RandpermBatchRuleHelper> { + static Tensor apply(int64_t n, T... extra_args) { + return randperm_batching_rule(n, std::forward(extra_args)...); + } +}; + +template +struct UnaryPointwiseRandomBatchRule; + +template +struct UnaryPointwiseRandomBatchRule> { + static Tensor apply(const Tensor& tensor, T... extra_args) { + return unary_pointwise_random_batch_rule(tensor, std::forward(extra_args)...); + } +}; + +template +struct NormalPointwiseBatchRule; + +template +struct NormalPointwiseBatchRule> { + static Tensor apply(const Tensor& tensor, T... extra_args) { + return unary_pointwise_random_batch_rule(tensor, std::forward(extra_args)...); + } +}; + +template +static Tensor normal_wrapper(const Tensor& tensor, double scalar, T... extra_args) { + return Func(scalar, tensor, extra_args...); +} + +template +struct UnaryPointwiseRandomLeadingFloatBatchRule; + +template +struct UnaryPointwiseRandomLeadingFloatBatchRule> { + static Tensor apply(double scalar, const Tensor& tensor, T... extra_args) { + return unary_pointwise_random_batch_rule), + &normal_wrapper, double, + T...>(tensor, scalar, std::forward(extra_args)...); + } +}; + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + #define RANDOM_INPLACE_BATCH_RULE2(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + RandomInplaceBatchRuleHelper::parameter_types>::apply)) + + RANDOM_INPLACE_BATCH_RULE2(bernoulli_, float); + + #undef RANDOM_INPLACE_BATCH_RULE2 +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchVmapMode, m) { + #define RANDOM_BATCH_RULE(op) \ + m.impl(#op, SINGLE_ARG(\ + RandomBatchRuleHelper::parameter_types>::apply)) + + #define RANDOM_BATCH_RULE2(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + RandomBatchRuleHelper::parameter_types>::apply)) + + #define RANDOM_INPLACE_BATCH_RULE(op) \ + m.impl(#op, SINGLE_ARG(\ + RandomInplaceBatchRuleHelper::parameter_types>::apply)) + + #define RANDOM_INPLACE_BATCH_RULE2(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + RandomInplaceBatchRuleHelper::parameter_types>::apply)) + + #define RANDINT_BATCH_RULE(op) \ + m.impl(#op, SINGLE_ARG(\ + RandIntBatchRuleHelper::parameter_types>::apply)) + + #define RANDINT_BATCH_RULE2(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + RandIntBatchRuleHelper::parameter_types>::apply)) + + #define RAND_TWO_LEADING_SCALARS_BATCH_RULE(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + RandTwoLeadingScalarsBatchRuleHelper::parameter_types>::apply)) + #define RANDPERM_BATCH_RULE(op) \ + m.impl(#op, SINGLE_ARG(\ + RandpermBatchRuleHelper::parameter_types>::apply)) + + #define RANDPERM_BATCH_RULE2(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + RandpermBatchRuleHelper::parameter_types>::apply)) + + #define UNARY_POINTWISE_RANDOM(op) \ + m.impl(#op, SINGLE_ARG(\ + UnaryPointwiseRandomBatchRule::parameter_types>::apply)) + + #define UNARY_POINTWISE_RANDOM2(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + UnaryPointwiseRandomBatchRule::parameter_types>::apply)) + + #define UNARY_POINTWISE_RANDOM_LEADING_FLOAT(op, overload) \ + m.impl(#op"."#overload, SINGLE_ARG(\ + UnaryPointwiseRandomLeadingFloatBatchRule::parameter_types>::apply)) + + RANDOM_BATCH_RULE(randn); + RANDOM_BATCH_RULE2(randn, generator); + + RANDOM_BATCH_RULE(rand); + RANDOM_BATCH_RULE2(rand, generator); + + RANDOM_INPLACE_BATCH_RULE(random_); + RANDOM_INPLACE_BATCH_RULE2(random_, from); + RANDOM_INPLACE_BATCH_RULE2(random_, to); + + RANDOM_INPLACE_BATCH_RULE(cauchy_); + RANDOM_INPLACE_BATCH_RULE(exponential_); + RANDOM_INPLACE_BATCH_RULE(geometric_); + RANDOM_INPLACE_BATCH_RULE(log_normal_); + RANDOM_INPLACE_BATCH_RULE(normal_); + RANDOM_INPLACE_BATCH_RULE(uniform_); + + RANDINT_BATCH_RULE(randint); + RANDINT_BATCH_RULE2(randint, generator); + RAND_TWO_LEADING_SCALARS_BATCH_RULE(randint, low); + RAND_TWO_LEADING_SCALARS_BATCH_RULE(randint, low_generator); + + m.impl("bernoulli_.Tensor", at::functorch::bernoulli_inplace_Tensor_batching_rule); + RANDOM_INPLACE_BATCH_RULE2(bernoulli_, float); + UNARY_POINTWISE_RANDOM2(bernoulli, p); + + RANDPERM_BATCH_RULE(randperm); + RANDPERM_BATCH_RULE2(randperm, generator); + + RAND_TWO_LEADING_SCALARS_BATCH_RULE(normal, float_float); + UNARY_POINTWISE_RANDOM2(normal, Tensor_float); + UNARY_POINTWISE_RANDOM_LEADING_FLOAT(normal, float_Tensor); + + m.impl("native_dropout", native_dropout_batching_rule); // needs special casing because cuda version doesn't call bernoulli + m.impl("native_dropout_backward", native_dropout_backward_batch_rule); + + UNARY_POINTWISE_RANDOM(_standard_gamma); + UNARY_POINTWISE_RANDOM(_sample_dirichlet); + m.impl("multinomial", multinomial_batching_rule); + UNARY_POINTWISE_RANDOM(poisson); + UNARY_POINTWISE_RANDOM(bernoulli); + + #define TENSOR_LIKE_COMMON_ARG_TYPES std::optional, std::optional, std::optional, std::optional, std::optional + m.impl("randint_like", tensor_like_random_batch_rule); + m.impl("randint_like.low_dtype", tensor_like_random_batch_rule<\ + decltype(&ATEN_FN2(randint_like, low_dtype)), &ATEN_FN2(randint_like, low_dtype), int64_t, int64_t, TENSOR_LIKE_COMMON_ARG_TYPES>); + m.impl("rand_like", tensor_like_random_batch_rule); + m.impl("randn_like", tensor_like_random_batch_rule); + + #undef RANDOM_BATCH_RULE + #undef RANDOM_BATCH_RULE2 + #undef RANDOM_INPLACE_BATCH_RULE + #undef RANDOM_INPLACE_BATCH_RULE2 + #undef RANDINT_BATCH_RULE + #undef RANDINT_BATCH_RULE2 + #undef RAND_TWO_LEADING_SCALARS_BATCH_RULE + #undef RANDPERM_BATCH_RULE + #undef RANDPERM_BATCH_RULE2 + #undef UNARY_POINTWISE_RANDOM + #undef UNARY_POINTWISE_RANDOM2 + #undef UNARY_POINTWISE_RANDOM_LEADING_FLOAT + #undef TENSOR_LIKE_COMMON_ARG_TYPES +} + +} // namespace at::functorch +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesReduceOps.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesReduceOps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ea020ece080410d645cccbd01f6d1221d022d1e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesReduceOps.cpp @@ -0,0 +1,523 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +#include + +// NOLINTBEGIN(bugprone-unchecked-optional-access) +namespace at::functorch { + +static bool is_allowed_dim_on_scalar_tensor(int64_t dim) { + return dim == 0 || dim == -1; +} + +static Tensor sum_decomp( + const Tensor& self, std::optional dtype) { + return at::sum(self, range(0, self.dim()), false, dtype); +} + +static std::tuple> _is_all_true_batch_rule( + const Tensor& self, std::optional self_bdim) { + return std::make_tuple(at::_is_all_true(self), std::nullopt); +} + +static std::tuple> _is_any_true_batch_rule( + const Tensor& self, std::optional self_bdim) { + return std::make_tuple(at::_is_any_true(self), std::nullopt); + } + +static Tensor mean_decomp( + const Tensor& self, std::optional dtype) { + return at::mean(self, range(0, self.dim()), false, dtype); +} + +static Tensor prod_decomp( + const Tensor& self, std::optional dtype) { + return at::prod(self.flatten(), 0, false, dtype); +} + +static Tensor max_decomp( + const Tensor& self) { + return std::get<0>(at::max(self.flatten(), 0, false)); +} + +static Tensor min_decomp( + const Tensor& self) { + return std::get<0>(at::min(self.flatten(), 0, false)); +} + +static Tensor norm_scalar_decomp( + const Tensor& self, const Scalar& p) { + return at::norm(self, p, range(0, self.dim()), false); +} + +static Tensor nanmedian_decomp( + const Tensor& self) { + return std::get<0>(at::nanmedian(self.flatten(), 0, false)); +} + +static Tensor median_decomp( + const Tensor& self) { + return std::get<0>(at::median(self.flatten(), 0, false)); +} + +static Tensor all_decomp(const Tensor& self) { + return at::all(self.flatten(), 0, false); +} + +static Tensor any_decomp(const Tensor& self) { + return at::any(self.flatten(), 0, false); +} + +static Tensor count_nonzero_decomp( + const Tensor& self, std::optional dim) { +if (dim.has_value()) { + return at::count_nonzero(self, IntArrayRef{*dim}); +} +return at::count_nonzero(self, range(0, self.dim())); +} + +enum class ReductionCase:uint8_t { DimArray, Dim }; + +// Macros and templates have a difficult time dealing with enums, +// so we didn't turn this into an enum. +// See NOTE: [keepdim cases] for explanation of what these are. +static constexpr int KEEPDIM_CASE_FALSE = 0; +static constexpr int KEEPDIM_CASE_TRUE = 1; +static constexpr int KEEPDIM_CASE_VARIABLE = 2; + +// dim_arg_pos allows us to specify the location of the dim/dim array argument. +// For most PyTorch ops, this is equal to 1. +// +// NOTE: [keepdim cases] +// The operator in question either: +// - has a keepdim argument (KeepdimCase.Variable) +// In this case, `maybe_keepdim_arg_pos` says where the index of the keepdim arg is. +// example: sum(tensor, dim, keepdim) +// - always does a reduction with no keepdim (KeepdimCase.False) +// that is, the rank of the output tensor is less than the rank of the input tensor. +// - always does a reduction with keepdim=True semantics (KeepdimCase.True) +// That is, the rank of the output tensor is always the same as that of the input. +// examples: log_softmax(tensor, dim), cumsum(tensor, dim) +template< + int dim_arg_pos, + int keepdim_case, + // optional cannot be used in a template, otherwise we would use it here. + int maybe_keepdim_arg_pos +> +static void boxed_reduction_batch_rule(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + const auto num_arguments = schema.arguments().size(); + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "boxed_reduction_batch_rule"); + int64_t cur_level = maybe_layer->layerId(); + + auto orig_arguments = torch::jit::last(*stack, num_arguments); + if (std::none_of(orig_arguments.begin(), orig_arguments.end(), ivalueParticipatesInCurrentLevel)) { + c10::impl::ExcludeDispatchKeyGuard guard_2(DispatchKey::FuncTorchBatched); + op.callBoxed(stack); + return; + } + + auto arguments = torch::jit::pop(*stack, num_arguments); + + TORCH_INTERNAL_ASSERT(arguments[0].isTensor()); + auto [self, self_bdim] = unwrapTensorAtLevel(arguments[0].toTensor(), cur_level); + + self = moveBatchDimToFront(self, self_bdim); + + auto logical_dim = rankWithoutBatchDim(self, self_bdim); + std::vector dims; + ReductionCase reduction_case{}; + if (arguments[dim_arg_pos].isIntList()) { + reduction_case = ReductionCase::DimArray; + dims = arguments[dim_arg_pos].toIntList().vec(); + if (dims.empty()) { + auto all_dims = range(0, std::max(static_cast(1), logical_dim)); + dims = std::vector(all_dims.begin(), all_dims.end()); + } + } else if (arguments[dim_arg_pos].isInt()) { + reduction_case = ReductionCase::Dim; + dims = {arguments[dim_arg_pos].toInt()}; + } else if (arguments[dim_arg_pos].isNone()) { + auto param_type = schema.arguments()[dim_arg_pos].type()->expect()->getElementType(); + if (param_type->kind() == IntType::Kind) { + reduction_case = ReductionCase::Dim; + if (self.dim() > 1) { + self = self.flatten(1); + } + dims = {0}; + } else if (param_type->kind() == ListType::Kind) { + reduction_case = ReductionCase::DimArray; + if (logical_dim == 0) { + dims = {0}; + } else { + auto all_dims = range(0, self.dim() - 1); + dims = std::vector(all_dims.begin(), all_dims.end()); + } + } else { + TORCH_INTERNAL_ASSERT(false, "Unexpected dtype found at dims"); + } + } else{ + TORCH_INTERNAL_ASSERT(false, "Unexpected dtype found at dims"); + } + + VmapDimVector new_dims; + new_dims.reserve(dims.size()); + for (auto dim: dims) { + new_dims.push_back(getPhysicalDim(self, self_bdim.has_value(), dim)); + } + bool is_scalar_case = logical_dim == 0 && dims.size() == 1 && is_allowed_dim_on_scalar_tensor(dims[0]); + std::optional maybe_keepdim; + if (is_scalar_case) { + // NOTE: [boxed_reduction_batch_rule scalar tensor handling] + // Reduction operations in PyTorch have an edge case where they allow + // dim=0 and dim=-1 if the tensor has shape []. + // + // This can come up if we do something like + // vmap(lambda x: x.sum(0))(torch.tensor([10.])), + // + // In order to handle this edge case, we unsqueeze a dimension on the Tensor, + // run the operation (with dim=1 instead), and then process the output tensor. + // There are two cases: + // - keepdim = True + // unsqueeze op squeeze + // [B] -> [B, 1] -> [B, 1] -> [B] + // - keepdim = False + // unsqueeze op no need to squeeze + // [B] -> [B, 1] -> [B] + // if keepdim is True, then we need to squeeze the dimension of size 1. + + // Determine the value of keepdim + switch (keepdim_case) { + case KEEPDIM_CASE_FALSE: + maybe_keepdim = false; + break; + case KEEPDIM_CASE_TRUE: + maybe_keepdim = true; + break; + case KEEPDIM_CASE_VARIABLE: + TORCH_INTERNAL_ASSERT(maybe_keepdim_arg_pos >= 0); + maybe_keepdim = arguments[maybe_keepdim_arg_pos].toBool(); + break; + } + self = self.unsqueeze(-1); + new_dims = {1}; + } + arguments[0] = std::move(self); + if (reduction_case == ReductionCase::DimArray) { + arguments[dim_arg_pos] = std::vector(new_dims.begin(), new_dims.end()); + } else if (reduction_case == ReductionCase::Dim) { + arguments[dim_arg_pos] = new_dims[0]; + } + for (const auto arg_idx : c10::irange(0, num_arguments)) { + torch::jit::push(stack, arguments[arg_idx]); + } + op.callBoxed(stack); + + auto returns = torch::jit::pop(*stack, num_returns); + for (auto& ret : returns) { + if (ret.isTensor()) { + auto res = ret.toTensor(); + // see NOTE: [boxed_reduction_batch_rule scalar tensor handling] + if (is_scalar_case && maybe_keepdim.value()) { + // squeeze(-1) is a no-op if the shape of the dim is not 1. + // To make it safer, we internal assert here. + TORCH_INTERNAL_ASSERT(res.size(-1) == 1); + res = res.squeeze(-1); + } + torch::jit::push(stack, makeBatched(std::move(res), 0, cur_level)); + } else { + TORCH_INTERNAL_ASSERT(false, "This boxed batching rule does not currently support ops that return non-tensor values"); + } + } +} + +// Skipping all/any since they don't have opinfo tests right now :P + +static Tensor dist_decomp(const Tensor& self, const Tensor& other, const Scalar& p) { + return at::norm((self - other), p); +} + +static std::tuple expand_bdims( + const Tensor& a, bool a_has_bdim, + const Tensor& b, bool b_has_bdim) { + Tensor flagpole; + if (a_has_bdim) { + flagpole = a; + } else if (b_has_bdim) { + flagpole = b; + } else { + TORCH_INTERNAL_ASSERT(false); + } + return std::make_tuple( + a_has_bdim ? a : a.expand_as(flagpole), + b_has_bdim ? b : b.expand_as(flagpole)); +} + +static std::tuple> _softmax_backward_batch_rule( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& output, std::optional output_bdim, + int64_t dim, + ScalarType input_dtype) { + // softmax_backward's decomposition is y * gy - y * (y * gy).sum(dim, keepdim=True) + // NB: the CUDA kernel handles strides so we can just expand + // all of the tensors and call it a day. The CPU kernel is not as good but + // idk if the perf on that really matters + auto grad_output_ = moveBatchDimToFront(grad_output, grad_output_bdim); + auto output_ = moveBatchDimToFront(output, output_bdim); + + // Expand out that extra dimension for everyone + std::tie(grad_output_, output_) = expand_bdims( + grad_output_, grad_output_bdim.has_value(), + output_, output_bdim.has_value()); + + // Scalar tensor case. softmax turns into the identity when this happens. + // I don't know why the output is zeros, though, but that's what softmax tells me... + if (output_.dim() == 1 && (dim == 0 || dim == -1)) { + return std::make_tuple(at::zeros_like(grad_output_), 0); + } + + dim = getPhysicalDim(output_, /*has_batch_dim*/true, dim); + + // Not sure why output_ needs to be marked as .contiguous(). Something must + // have changed in PyTorch (and output of softmax is probably always contiguous) + return std::make_tuple(at::_softmax_backward_data(grad_output_, output_.contiguous(), dim, input_dtype), 0); +} + +static std::tuple> _log_softmax_backward_batch_rule( + const Tensor& grad_output, std::optional grad_output_bdim, + const Tensor& output, std::optional output_bdim, + int64_t dim, + c10::ScalarType input_dtype) { + // NB: It turns out that expanding + calling log_softmax_backward is generally + // faster than the decomposition. + // Benchmark here: https://gist.github.com/zou3519/ae3b33b5730a84aae8a80a05c89e078a + // Decomposition is (grad_output - grad_output.sum(dim, keepdim=True) * result.exp()) + // We can squeeze out a last mile of performance by writing custom kernels. + auto grad_output_ = moveBatchDimToFront(grad_output, grad_output_bdim); + auto output_ = moveBatchDimToFront(output, output_bdim); + + // Expand out that extra dimension for everyone + std::tie(grad_output_, output_) = expand_bdims( + grad_output_, grad_output_bdim.has_value(), + output_, output_bdim.has_value()); + + // Scalar tensor case. log_softmax returns zeros when this happens + if (output_.dim() == 1 && (dim == 0 || dim == -1)) { + return std::make_tuple(at::zeros_like(grad_output_), 0); + } + + dim = getPhysicalDim(output_, /*has_batch_dim*/true, dim); + + return std::make_tuple(at::_log_softmax_backward_data(grad_output_, output_, dim, input_dtype), 0); +} + +static std::tuple> searchsorted_batch_rule( + const Tensor& sorted_sequence, + std::optional sorted_sequence_bdim, + const Tensor& self, + std::optional self_bdim, + bool out_int32, + bool right, + std::optional side, + const std::optional& sorter, + std::optional sorter_bdim) { + auto buckets_logical_rank = rankWithoutBatchDim(sorted_sequence, sorted_sequence_bdim); + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + + // Preprocess sorter and sorted_sequence. + // If they both exist, and only one has a bdim, then we need to make sure both do. + // After this step, we can forget about sorter for a bit. + auto buckets = moveBatchDimToFront(sorted_sequence, sorted_sequence_bdim); + std::optional buckets_bdim; + if (sorted_sequence_bdim.has_value()) { + buckets_bdim = 0; + } + + std::optional sorter_; + if (sorter.has_value() && sorter->defined()) { + auto sorter__ = moveBatchDimToFront(*sorter, sorter_bdim); + if (sorted_sequence_bdim.has_value() != sorter_bdim.has_value()) { + auto bdim_size = get_bdim_size2( + sorted_sequence, sorted_sequence_bdim, + sorter.value(), sorter_bdim); + sorter__ = ensure_has_bdim(sorter__, sorter_bdim.has_value(), bdim_size); + buckets = ensure_has_bdim(buckets, sorted_sequence_bdim.has_value(), bdim_size); + buckets_bdim = 0; + } + sorter_ = sorter__; + } + + // Two cases: buckets_logical_rank is 1, or it is greater than 1. + // searchsorted is basically two operators with different semantics jammed + // into one + if (buckets_logical_rank > 1) { + // B<...>D, B<...>V -> no change + if (buckets_bdim.has_value() && self_bdim.has_value()) { + auto self_ = moveBatchDimToFront(self, self_bdim); + auto result = at::searchsorted(buckets, self_, out_int32, right, side, sorter_); + return std::make_tuple(std::move(result), 0); + } + // B<...>D, <...>V -> B<...>D, B<...>V + if (buckets_bdim.has_value() && !self_bdim.has_value()) { + auto self_ = moveBatchDimToFront(self, self_bdim); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), buckets.size(0)); + auto result = at::searchsorted(buckets, self_, out_int32, right, side, sorter_); + return std::make_tuple(std::move(result), 0); + } + // <...>D, B<...>V -> <...>D, <...>(BV) + if (!buckets_bdim.has_value() && self_bdim.has_value()) { + auto bdim_size = self.size(*self_bdim); + auto self_ = reshape_dim_into(*self_bdim, -1, self); + auto result = at::searchsorted(buckets, self_, out_int32, right, side, sorter_); + result = reshape_dim_outof(-1, bdim_size, result); + auto result_bdim = result.dim() - 2; + return std::make_tuple(std::move(result), result_bdim); + } + TORCH_INTERNAL_ASSERT(false); + } + // buckets_logical_rank == 1 case. + // BD, B* -> BD, B flat(*) + if (buckets_bdim.has_value() && self_bdim.has_value()) { + auto self_ = moveBatchDimToFront(self, self_bdim); + auto self_view_ = self_logical_rank == 0 ? self_.unsqueeze(-1) : self_.flatten(1); + auto result = at::searchsorted(buckets, self_view_, out_int32, right, side, sorter_); + result = self_logical_rank == 0 ? result.squeeze(-1) : result.view(self_.sizes()); + return std::make_tuple(std::move(result), 0); + } + // BD, * -> BD, flat(*) -> BD, B flat(*) + if (buckets_bdim.has_value() && !self_bdim.has_value()) { + auto bdim_size = buckets.size(*buckets_bdim); + auto self_ = ensure_has_bdim(self, false, bdim_size); + auto self_view_ = self_logical_rank == 0 ? self_.unsqueeze(-1) : self_.flatten(1); + auto result = at::searchsorted(buckets, self_view_, out_int32, right, side, sorter_); + result = self_logical_rank == 0 ? result.squeeze(-1) : result.view(self_.sizes()); + return std::make_tuple(std::move(result), 0); + } + // D, B* -> no change + if (!buckets_bdim.has_value() && self_bdim.has_value()) { + auto result = at::searchsorted(buckets, self, out_int32, right, side, sorter_); + return std::make_tuple(std::move(result), self_bdim); + } + TORCH_INTERNAL_ASSERT(false); +} + +static Tensor bucketize_decomp_Tensor( + const Tensor& self, + const Tensor& boundaries, + bool out_int32, + bool right) { + // checking logical rank + TORCH_CHECK(boundaries.dim() == 1, "bucketize: boundaries tensor must be 1 dimension, but got dim(", boundaries.dim(), ")"); + return at::searchsorted(boundaries, self, out_int32, right, std::nullopt, std::nullopt); +} + +static Tensor bucketize_decomp_Scalar( + const Scalar& self, + const Tensor& boundaries, + bool out_int32, + bool right) { + // checking logical rank + TORCH_CHECK(boundaries.dim() == 1, "bucketize: boundaries tensor must be 1 dimension, but got dim(", boundaries.dim(), ")"); + return at::searchsorted(boundaries, self, out_int32, right, std::nullopt, std::nullopt); +} + +// Use when the other macros don't work out. +// - dim_pos: index of the dim argument +// - keepdim_case: either True, False, or Variable. +// See NOTE: [keepdim cases] for more details. +// - maybe_keepdim_pos. The index of the keepdim argument, +// if exists. Otherwise, the value is ignored. +#define REDUCTION_BOXED_ARGS(op, dim_pos, keepdim_case, maybe_keepdim_pos) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction< \ + SINGLE_ARG(boxed_reduction_batch_rule)>()); + +// Provided for your convenience; most operators that have a keepdim arg +// will work with this macro. +// Assumes the dim arg is at position 1 and the keepdim arg is at pos 2. +#define REDUCTION_WITH_KEEPDIM_ARG(op) \ + REDUCTION_BOXED_ARGS(op, 1, KEEPDIM_CASE_VARIABLE, 2) + +// Provided for your convenience; most operators that do not have a keepdim +// arg will work with this macro. +// Assumes the dim arg is at position 1 and the operation always returns +// a tensor of the same rank (instead of a smaller rank). +#define REDUCTION_NO_KEEPDIM_ARG(op) \ + REDUCTION_BOXED_ARGS(op, 1, KEEPDIM_CASE_TRUE, -1) + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT2(searchsorted, Tensor, searchsorted_batch_rule); + REDUCTION_NO_KEEPDIM_ARG(_fft_r2c); + REDUCTION_NO_KEEPDIM_ARG(_fft_c2r); + REDUCTION_NO_KEEPDIM_ARG(_fft_c2c); + REDUCTION_WITH_KEEPDIM_ARG(amax); + REDUCTION_WITH_KEEPDIM_ARG(amin); + REDUCTION_WITH_KEEPDIM_ARG(aminmax); + m.impl("all", all_decomp); + REDUCTION_WITH_KEEPDIM_ARG(all.dim); + REDUCTION_WITH_KEEPDIM_ARG(all.dims); + m.impl("any", any_decomp); + REDUCTION_WITH_KEEPDIM_ARG(any.dim); + REDUCTION_WITH_KEEPDIM_ARG(any.dims); + REDUCTION_WITH_KEEPDIM_ARG(argmax); + REDUCTION_WITH_KEEPDIM_ARG(argmin); + m.impl("bucketize.Tensor", bucketize_decomp_Tensor); + m.impl("bucketize.Scalar", bucketize_decomp_Scalar); + m.impl("count_nonzero", count_nonzero_decomp); + REDUCTION_BOXED_ARGS(count_nonzero.dim_IntList, 1, KEEPDIM_CASE_FALSE, -1); + REDUCTION_NO_KEEPDIM_ARG(cummax); + REDUCTION_NO_KEEPDIM_ARG(cummin); + REDUCTION_NO_KEEPDIM_ARG(cumprod); + REDUCTION_NO_KEEPDIM_ARG(cumsum); + m.impl("dist", dist_decomp); + REDUCTION_BOXED_ARGS(kthvalue, 2, KEEPDIM_CASE_VARIABLE, 3); + REDUCTION_BOXED_ARGS(linalg_vector_norm, 2, KEEPDIM_CASE_VARIABLE, 3); + REDUCTION_NO_KEEPDIM_ARG(logcumsumexp); + REDUCTION_WITH_KEEPDIM_ARG(logsumexp); + m.impl("max", max_decomp); + REDUCTION_WITH_KEEPDIM_ARG(max.dim); + m.impl("mean", mean_decomp); + REDUCTION_WITH_KEEPDIM_ARG(mean.dim); + m.impl("median", median_decomp); + REDUCTION_WITH_KEEPDIM_ARG(median.dim); + m.impl("min", min_decomp); + REDUCTION_WITH_KEEPDIM_ARG(min.dim); + REDUCTION_WITH_KEEPDIM_ARG(mode); + m.impl("nanmedian", nanmedian_decomp); + REDUCTION_WITH_KEEPDIM_ARG(nanmedian.dim); + REDUCTION_WITH_KEEPDIM_ARG(nansum); + m.impl("norm.Scalar", norm_scalar_decomp); + REDUCTION_BOXED_ARGS(norm.ScalarOpt_dim, 2, KEEPDIM_CASE_VARIABLE, 3); + m.impl("prod", prod_decomp); + REDUCTION_WITH_KEEPDIM_ARG(prod.dim_int); + REDUCTION_BOXED_ARGS(std.correction, 1, KEEPDIM_CASE_VARIABLE, 3); + REDUCTION_NO_KEEPDIM_ARG(_softmax); + REDUCTION_NO_KEEPDIM_ARG(_safe_softmax); + REDUCTION_NO_KEEPDIM_ARG(sort); + REDUCTION_BOXED_ARGS(sort.stable, 2, KEEPDIM_CASE_TRUE, -1); + REDUCTION_BOXED_ARGS(std_mean.correction, 1, KEEPDIM_CASE_VARIABLE, 3); + m.impl("sum", sum_decomp); + REDUCTION_WITH_KEEPDIM_ARG(sum.dim_IntList); + REDUCTION_BOXED_ARGS(topk, 2, KEEPDIM_CASE_TRUE, -1); + REDUCTION_BOXED_ARGS(var.correction, 1, KEEPDIM_CASE_VARIABLE, 3); + REDUCTION_BOXED_ARGS(var_mean.correction, 1, KEEPDIM_CASE_VARIABLE, 3); + REDUCTION_NO_KEEPDIM_ARG(_log_softmax); + REDUCTION_BOXED_ARGS(rot90, 2, KEEPDIM_CASE_TRUE, -1); + VMAP_SUPPORT(_log_softmax_backward_data, _log_softmax_backward_batch_rule); + VMAP_SUPPORT(_softmax_backward_data, _softmax_backward_batch_rule); + VMAP_SUPPORT(_is_all_true, _is_all_true_batch_rule); + VMAP_SUPPORT(_is_any_true, _is_any_true_batch_rule); +} + +} // namespace at::functorch +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesScatterOps.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesScatterOps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52dd0a4319d1f46e1de63534403a0801e0a085cb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesScatterOps.cpp @@ -0,0 +1,1371 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include +#include +#include +#include +#include + + +// NOLINTBEGIN(bugprone-unchecked-optional-access) +namespace at::functorch { + +namespace { +bool any_has_value(ArrayRef> bdims) { + for (const auto& bdim : bdims) { + if (bdim.has_value()) { + return true; + } + } + return false; +} + +int64_t get_num_leading_nones(ArrayRef> indices) { + int64_t result = 0; + for (const auto& idx : indices) { + if (!idx.has_value() || !idx->defined()) { + result++; + } else { + return result; + } + } + return result; +} + +int64_t get_max_index_logical_dim( + ArrayRef> indices, + ArrayRef> indices_bdims) { + int64_t max_logical_dim = -1; + TORCH_INTERNAL_ASSERT(indices.size() == indices_bdims.size()); + TORCH_INTERNAL_ASSERT(!indices.empty()); + for (const auto i : c10::irange(0, indices.size())) { + const auto& maybe_tensor = indices[i]; + if (!maybe_tensor.has_value() || !maybe_tensor->defined()) { + continue; + } + auto logical_dim = rankWithoutBatchDim(maybe_tensor.value(), indices_bdims[i]); + max_logical_dim = std::max(logical_dim, max_logical_dim); + } + return max_logical_dim; +} + +std::vector> batchIndices( + at::TensorOptions options, + ArrayRef> indices, + ArrayRef> indices_bdims, + const c10::SymInt& batch_size, + std::optional self_bdim, + std::optional values_bdim = std::nullopt) { + // There are 3 main cases: + // 1. self is batched, indices/values are not batched + // In this case, we just need to augment indices with a None at the front to + // basically broadcast the indexing across the batch dimension of self. + // + // 2. self is not batched, some indices are batched. + // In this case, we don't need to do anything - indices will automatically + // broadcast to work with the unbatched self. + // + // 3. self is batched, some indices are batched. + // In this case, we simply need to add an arange that indexes along the first + // dimension (i.e. the batch dimension). We also need to make sure this + // broadcasts with the rest of the indices. + // + // In all three cases, depending on if advanced indices are adjacent we will + // have to permute the output. + // See NOTE: [advanced indexing (index.Tensor) batch rule] for more details + // + // There is one more case worth mentioning - boolean tensor indices. If we + // have "batched" boolean tensor indices, that is unrepresentable, as each + // batch would result in a tensor with different values. + std::vector> indices_; + + int64_t maxLogicalRank = get_max_index_logical_dim(indices, indices_bdims); + bool indices_batched = any_has_value(indices_bdims); + + for (size_t i = 0; i < indices.size(); i++) { + auto const & index = indices[i]; + if (index.has_value() && index->sym_numel() != 0) { + const auto idx_bdim = indices_bdims[i]; + indices_.emplace_back(maybePadToLogicalRank(moveBatchDimToFront(index.value(), idx_bdim), idx_bdim, maxLogicalRank)); + TORCH_CHECK( + !(index.value().dtype() == kBool) || !indices_bdims[i].has_value(), + "vmap: We do not support batching operators that can support dynamic shape. Attempting to batch over indexing with a boolean mask." + ); + } else { + indices_.push_back(index); + } + } + + auto maxIndexDim = maxLogicalRank; + if (indices_batched || values_bdim.has_value()) { + maxIndexDim += 1; + } + + if (!indices_batched && self_bdim.has_value()) { + indices_.insert(indices_.begin(), std::nullopt); + } else if (indices_batched && !self_bdim.has_value()) { + // do nothing + } else if (indices_batched && (self_bdim.has_value() || values_bdim.has_value())) { + auto arange_index = at::arange(batch_size, options.dtype(kLong)); + while (arange_index.dim() < maxIndexDim) { + arange_index = arange_index.unsqueeze(-1); + } + // TODO: this is O(N) + indices_.insert(indices_.begin(), arange_index); + } + return indices_; +} + +// Define an "advanced index" to be a selection object that is +// a non-trivial Tensor (i.e. it does not represent :). +bool is_advanced_index(const std::optional& idx) { + if (!idx.has_value()) { + return false; + } + if (!idx->defined()) { + return false; + } + return true; +} + +// See NOTE: [advanced indices adjacent] for definition +bool are_advanced_indices_adjacent(ArrayRef> indices) { + int64_t num_advanced_indices_regions = 0; + bool in_advanced_indices_region = false; + for (const auto& idx : indices) { + if (!in_advanced_indices_region && is_advanced_index(idx)) { + num_advanced_indices_regions++; + in_advanced_indices_region = true; + continue; + } + if (in_advanced_indices_region && !is_advanced_index(idx)) { + in_advanced_indices_region = false; + continue; + } + } + return num_advanced_indices_regions <= 1; +} + +// Given a Tensor[B, , , ...] +// Swaps the regions to produce Tensor[B, , , ...] +// +// Concretely speaking, given +// - tensor: Tensor[B, 2, 3, 4, 5, 6, 7, 8] +// - first_region_size: 2 +// - second_region_size: 3 +// Produces: +// - result: Tensor[B, 4, 5, 6, 2, 3, 7, 8] +// ------- ---- +// region2 region1 +Tensor swap_regions(const Tensor& tensor, int64_t first_region_size, int64_t second_region_size) { + VmapDimVector permutation(tensor.dim(), 0); + std::iota(permutation.begin(), permutation.end(), 0); + std::rotate( + permutation.begin() + 1, + permutation.begin() + 1 + first_region_size, + permutation.begin() + 1 + first_region_size + second_region_size); + return tensor.permute(permutation); +} + +std::tuple> index_batch_rule( + const Tensor& self, + std::optional self_bdim, + ArrayRef> indices, + ArrayRef> indices_bdims) { + + // NOTE: [advanced indexing (index.Tensor) batch rule] + // + // This is a three step procedure: + // 1. batch `indices`. Depends on self_bdim and indices_bdim. + // 2. call at::index + // 3. (maybe) reorder the dimensions in the result. + // Why is step 3 necessary? Let's take a detour first. + // + // NOTE: [advanced indices adjacent] + // Definition: In a list of std::optional indices, + // we say that "advanced indices are adjacent" if ALL advanced indices are + // not separated by a None (slice). + // + // So, for example, + // [:, :, (0, 1), (0, 1), :] -> True + // [:, (0, 1), :, (0, 1), :] -> False, the advanced indices are separated by a slice + // + // See https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing + // for more details. + // + // NOTE: [Why is step 3 necessary?] + // + // In the original self[*indices] expression, + // depending on whether or not the "advanced indices inside `indices` are + // adjacent", something different happens. + // + // For example: + // - self: Tensor[4, 5, 6, 7] + // - indices: [:, (0, 1), (0, 1), :] (advanced indices are adjacent) + // - self[*indices]: Tensor[4, 2, 7] + // If advanced indices are adjacent, you get the output you would expect. + // (0, 1), (0, 1) says "please index these two dimensions at (0, 0) and (1, 1) + // to produce two elements". + // + // If advanced indices are not adjacent, it is ambiguous to where the new + // dimension of size 2 should go. The numpy spec says it should go at the very + // front of the Tensor. + // + // - self: Tensor[4, 5, 6, 7] + // - indices: [:, (0, 1), :, (0, 1)] (advanced indices not adjacent) + // - self[*indices]: Tensor[2, 4, 6] + // + // Now, this leads to some weird interactions with vmap. + // The indices might originally have adjacent advanced indices, but after + // batching them with "batchIndices", they may no longer be adjacent! + // - indices: [:, (0, 1), (0, 1)] + // - batched_indices (for example): [(0, 1), :, (0, 1), (0, 1)] + // This leads to the dimension of size 2 appearing somewhere else. + // + // There are a couple of different cases that we walk through in the code below. + // + // Background reading for why we care about if the advanced indices are adjacent: + // https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing + auto self_ = moveBatchDimToFront(self, self_bdim); + TORCH_INTERNAL_ASSERT(indices.size() == indices_bdims.size()); + bool advanced_indices_are_adjacent = are_advanced_indices_adjacent(indices); + + // Step 1 + const auto batched_indices = batchIndices(self.options(), indices, indices_bdims, self_.sym_size(0), self_bdim); + auto num_leading_nones = get_num_leading_nones(indices); + auto max_index_dim = get_max_index_logical_dim(indices, indices_bdims); + + // Step 2 + auto res = at::index(self_, List>(batched_indices)); + + // Step 3: There are three cases (these match the cases outlined in batchIndices) + bool self_batched = self_bdim.has_value(); + bool indices_batched = any_has_value(indices_bdims); + + TORCH_INTERNAL_ASSERT(self_batched || indices_batched, "Requires at least one batched to get here"); + + // Case 1 + if (self_batched && !indices_batched) { + if (advanced_indices_are_adjacent) { + // self: Tensor[B, 5, 6, 7, 8] + // indices: [:, Tensor[2, 2], Tensor[2, 2], :] + // batched_indices: [:, :, Tensor[2, 2], Tensor[2, 2], :] + // res: Tensor[B, 5, 2, 2, 8] + return std::make_tuple(std::move(res), 0); + } else { + // self: Tensor[B, 5, 6, 7] + // indices: [Tensor[2, 2], :, Tensor[2, 2]] + // batched_indices: [:, Tensor[2, 2], :, Tensor[2, 2]] + // res: Tensor[2, 2, B, 6] + return std::make_tuple(std::move(res), max_index_dim); + } + } + + // Case 2 + if (!self_batched && indices_batched) { + if (advanced_indices_are_adjacent) { + // self: Tensor[5, 6, 7, 8] + // indices: [:, :, Tensor[B, 2, 2], Tensor[2, 2]] + // batched_indices: indices (no change) + // res: Tensor[5, 6, B, 2, 2] + return std::make_tuple(std::move(res), num_leading_nones); + } else { + // self: Tensor[5, 6, 7, 8, 9] + // indices: [:, :, Tensor[B, 2, 2], :, Tensor[2, 2]] + // batched_indices: indices (no change) + // res: Tensor[B, 2, 2, 5, 6, 8] + return std::make_tuple(std::move(res), 0); + } + } + + // Case 3: self_batched and indices_batched + TORCH_INTERNAL_ASSERT(self_batched && indices_batched); + if (!advanced_indices_are_adjacent) { + // self: Tensor[B, 5, 6, 7, 8] + // indices: [:, Tensor[B, 2, 2], :, Tensor[2, 2]] + // batched_indices: [arange(B).expand(B, 2, 2), :, Tensor[B, 2, 2], :, Tensor[2, 2]] + // res: Tensor[B, 2, 2, 5, 7] + return std::make_tuple(std::move(res), 0); + } + // In other words, in batched_indices, advanced indices are adjacent + if (num_leading_nones == 0) { + // self: Tensor[B, 5, 6, 7, 8] + // indices: [Tensor[B, 2, 2], Tensor[2, 2], :, :] + // batched_indices: [arange(B).expand(B, 2, 2), Tensor[B, 2, 2], Tensor[2, 2], :, :] + // res: Tensor[B, 2, 2, 7, 8] + return std::make_tuple(std::move(res), 0); + } + // This is the tricky case. In indices, advanced indices are adjacent. + // In batched_indices, advanced indices are no longer adjacent + // + // self: Tensor[B, 5, 6, 7, 8, 9] + // indices: [:, :, Tensor[B, 2, 3], Tensor[2, 3], :] + // batched_indices: [arange(B).expand(B, 2, 3), :, :, Tensor[B, 2, 3], Tensor[2, 3], :] + // res: Tensor[B, 2, 3, 5, 6, 9] + // expected: Tensor[B, 5, 6, 2, 3, 9] + // + // The resolution is to move dims around until we get the right shape. + // The result is set up as [B, , , ...] + // we just have to move the to before the to produce + // [B, , , ...] + return std::make_tuple(swap_regions(res, max_index_dim, num_leading_nones), 0); +} + +// plumbing done since we don't support List> in codegen +Tensor index_plumbing(const Tensor & self, const List> & indices +) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "index_plumbing"); + int64_t cur_level = maybe_layer->layerId(); + if (!isBatchedAtLevel(self, cur_level) && !isBatchedAtLevel(indices, cur_level)) { + return at::index(self, indices); + } + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + std::vector> indices_value; + std::vector> indices_bdims; + for (const auto&& indRef : indices) { + std::optional ind = indRef; + std::optional index; + std::optional index_bdim; + if (ind.has_value()) { + std::tie(index, index_bdim) = unwrapTensorAtLevel(ind.value(), cur_level); + } + indices_value.push_back(index); + indices_bdims.push_back(index_bdim); + } + auto results = index_batch_rule(self_value, self_bdim, indices_value, indices_bdims); + return makeBatched(std::get<0>(results), std::get<1>(results), cur_level); +} + +namespace { + // Code is mostly duplicated from + // https://github.com/pytorch/pytorch/blob/fb0e27d38a8fdab4e1c14d6378c9e41cb30fd6a3 + // /aten/src/ATen/native/TensorAdvancedIndexing.cpp#L294-L312 + VmapSymDimVector compute_indexed_shape(const Tensor &src, TensorList indices_list) + { + int64_t dims_before = 0, dims_indexed = 0; + SymIntArrayRef replacement_shape; + for (const auto dim : c10::irange(indices_list.size())) { + if (!indices_list[dim].defined()) { + if (dims_indexed == 0) { + dims_before++; + } + } else { + dims_indexed++; + replacement_shape = indices_list[dim].sym_sizes(); + } + } + + // Replace indexed dimensions in src with stride 0 and the size of the result tensor. + // The offset in these dimensions is computed by the kernel using the index tensor's + // values and the stride of src. The new shape is not meaningful. It's used to make + // the shape compatible with the result tensor. + auto shape = VmapSymDimVector(src.sym_sizes()); + int64_t end = dims_before + dims_indexed; + shape.erase(shape.begin() + dims_before, shape.begin() + end); + shape.insert(shape.begin() + dims_before, replacement_shape.begin(), replacement_shape.end()); + return shape; + } + + // Code is mostly duplicated from + // https://github.com/pytorch/pytorch/blob/fb0e27d38a8fdab4e1c14d6378c9e41cb30fd6a3 + // /aten/src/ATen/native/TensorAdvancedIndexing.cpp#L379-L405 + VmapSymDimVector get_indexed_shape(Tensor self, const torch::List> &orig) + { + at::native::checkIndexTensorTypes(orig, /*allow_int*/ true); + // first expand BoolTensor (masks) or ByteTensor (masks) into 1 or more LongTensors + auto indices = at::native::expandTensors(self, orig); + // next broadcast all index tensors together + try { + indices = at::expand_outplace(indices); + } catch (std::exception&) { + TORCH_CHECK_INDEX( + false, + "shape mismatch: indexing tensors could not be broadcast together" + " with shapes "); + } + // add missing null Tensors so that it matches self.dim() + while (indices.size() < static_cast(self.dim())) { + indices.emplace_back(); + } + // if the non-null indices are not all adjacent, transpose self and indices + // together so that they're adjacent at the front + if (!at::native::hasContiguousSubspace(indices)) { + std::tie(self, indices) = at::native::transposeToFront(self, indices); + } + return compute_indexed_shape(self, indices); + } + + std::tuple>, Tensor> + index_put_batch_rule_helper(const Tensor &self, + std::optional self_bdim, + ArrayRef> indices, + ArrayRef> indices_bdims, + const Tensor &values, + std::optional values_bdim, + std::optional opt_batch_size = {}) { + + Tensor self_ = moveBatchDimToFront(self, self_bdim); + Tensor values_ = moveBatchDimToFront(values, values_bdim); + // for inplace variants `index_put_` and `_index_put_impl_` we find the batch_size + // here while for `index_put` does it outside of this function. + const auto batch_size = opt_batch_size ? opt_batch_size.value() : self_.sym_size(0); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + values_ = ensure_has_bdim(values_, values_bdim.has_value(), batch_size); + TORCH_INTERNAL_ASSERT(indices.size() == indices_bdims.size()); + + // we've already made sure that self has bdim at 0. + const auto indices_ = batchIndices(self.options(), indices, indices_bdims, batch_size, /*self_bdim=*/0, values_bdim); + + auto indexed_shape = get_indexed_shape(self_, List>(indices_)); + + // handle broadcasting support for values + // Eg. Given `indexed_shape.size()` is 5 and + // shape of `values` is (N, 2, 3), then following block + // will reshape `values` to (N, 1, 1, 2, 3). + if ( static_cast(indexed_shape.size()) > values_.dim()) { + auto values_sizes = values_.sym_sizes(); + + // number of unit dims (for broadcasting value to indexed_shape) + auto n_unit_dims = indexed_shape.size() - values_sizes.size(); + VmapSymDimVector new_values_shape(values_sizes.size() + n_unit_dims); + + // add the batch-dim + new_values_shape[0] = batch_size; + + // insert the unit dims for broadcasting. + for (const auto idx : c10::irange(n_unit_dims)) { + // since batch-dim is already be filled. + new_values_shape[idx + 1] = 1; + } + for (const auto idx: c10::irange(1, values_sizes.size())) { + // since batch and unit dims are already be filled. + new_values_shape[idx + n_unit_dims] = values_sizes[idx]; + } + values_ = values_.view_symint(new_values_shape); + } + + return std::make_tuple(self_, indices_, values_); + } + + auto unpackSelfAndIndicesAndValuesAtCurrentLevel(const Tensor &self, + const List> &indices, + const Tensor &values, int64_t cur_level) + { + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + std::vector> indices_value; + std::vector> indices_bdims; + for (const auto &&indRef : indices) + { + std::optional ind = indRef; + std::optional index; + std::optional index_bdim; + if (ind.has_value()) { + std::tie(index, index_bdim) = unwrapTensorAtLevel(ind.value(), cur_level); + } + indices_value.push_back(index); + indices_bdims.push_back(index_bdim); + } + auto [values_value, values_bdim] = unwrapTensorAtLevel(values, cur_level); + return std::make_tuple( + std::move(self_value), + self_bdim, + std::move(indices_value), + std::move(indices_bdims), + std::move(values_value), + values_bdim); + } + +} // namespace + +void index_put__batch_rule( + const Tensor& self, + std::optional self_bdim, + ArrayRef> indices, + ArrayRef> indices_bdims, + const Tensor& values, + std::optional values_bdim, + bool accumulate) { + if (!self_bdim.has_value()) { + vmapIncompatibleInplaceError("index_put_"); + } + auto [self_, indices_, values_] = index_put_batch_rule_helper( + self, self_bdim, indices, indices_bdims, values, values_bdim); + at::index_put_(self_, List>(indices_), values_, accumulate); +} + +// plumbing done since we don't support List> in codegen +Tensor& index_put__plumbing(Tensor & self, const List> & indices +, const Tensor & values, bool accumulate) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "index_put__plumbing"); + int64_t cur_level = maybe_layer->layerId(); + + // on device mismatch, we can move 0d tensors to self device + auto values_ = values; + if (values.device() != self.device() && values.numel() == 1 && values.dim() == 0) { + values_ = values.to(self.device()); + } + + if (!isBatchedAtLevel(self, cur_level) && !isBatchedAtLevel(indices, cur_level) && !isBatchedAtLevel(values_, cur_level)) { + return self.index_put_(indices, values_, accumulate); + } + auto [self_value, self_bdim, indices_value, indices_bdims, values_value, values_bdim] = + unpackSelfAndIndicesAndValuesAtCurrentLevel(self, indices, values_, cur_level); + index_put__batch_rule(self_value, self_bdim, indices_value, indices_bdims, values_value, values_bdim, accumulate); + return self; +} + +void _index_put_impl__batch_rule( + const Tensor& self, + std::optional self_bdim, + ArrayRef> indices, + ArrayRef> indices_bdims, + const Tensor& values, + std::optional values_bdim, + bool accumulate, + bool unsafe) { + if (!self_bdim.has_value()) { + vmapIncompatibleInplaceError("_index_put_impl_"); + } + auto [self_, indices_, values_] = index_put_batch_rule_helper( + self, self_bdim, indices, indices_bdims, values, values_bdim); + at::_index_put_impl_(self_, List>(indices_), values_, accumulate, unsafe); +} + +// plumbing done since we don't support List> in codegen +Tensor &_index_put_impl__plumbing(Tensor &self, const List> &indices, + const Tensor &values, bool accumulate, bool unsafe) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "_index_put_impl__plumbing"); + int64_t cur_level = maybe_layer->layerId(); + if (!isBatchedAtLevel(self, cur_level) && !isBatchedAtLevel(indices, cur_level) && !isBatchedAtLevel(values, cur_level)) { + return at::_index_put_impl_(self, indices, values, accumulate, unsafe); + } + auto [self_value, self_bdim, indices_value, indices_bdims, values_value, values_bdim] = + unpackSelfAndIndicesAndValuesAtCurrentLevel(self, indices, values, cur_level); + _index_put_impl__batch_rule(self_value, self_bdim, indices_value, indices_bdims, values_value, values_bdim, accumulate, unsafe); + return self; +} + +Tensor maybe_permute_values( + const Tensor& values, + ArrayRef> orig_indices, + ArrayRef> orig_indices_bdims) { + bool indices_batched = any_has_value(orig_indices_bdims); + bool advanced_indices_are_adjacent = are_advanced_indices_adjacent(orig_indices); + auto num_leading_nones = get_num_leading_nones(orig_indices); + auto max_index_dim = get_max_index_logical_dim(orig_indices, orig_indices_bdims); + + // NB: values has its B dimension at the front + if (!indices_batched) { + if (advanced_indices_are_adjacent) { + // self: Tensor[B, 5, 6, 7, 8] + // indices: [:, Tensor[2, 2], Tensor[2, 2], :] + // batched_indices: [:, :, Tensor[2, 2], Tensor[2, 2], :] + // required values: Tensor[B, 5, 2, 2, 8] + return values; + } + // self: Tensor[B, 5, 6, 7] + // indices: [Tensor[2, 2], :, Tensor[2, 2]] + // batched_indices: [:, Tensor[2, 2], :, Tensor[2, 2]] + // required values: Tensor[2, 2, B, 6] + return values.movedim(0, max_index_dim); + } + if (!advanced_indices_are_adjacent) { + // self: Tensor[B, 5, 6, 7, 8] + // indices: [:, Tensor[B, 2, 2], :, Tensor[2, 2]] + // batched_indices: [arange(B).expand(B, 2, 2), :, Tensor[B, 2, 2], :, Tensor[2, 2]] + // required values: Tensor[B, 2, 2, 5, 7] + return values; + } + // In other words, in batched_indices, advanced indices are adjacent + if (num_leading_nones == 0) { + // self: Tensor[B, 5, 6, 7, 8] + // indices: [Tensor[B, 2, 2], Tensor[2, 2], :, :] + // batched_indices: [arange(B).expand(B, 2, 2), Tensor[B, 2, 2], Tensor[2, 2], :, :] + // required values: Tensor[B, 2, 2, 7, 8] + return values; + } + // This is the tricky case. In indices, advanced indices are adjacent. + // In batched_indices, advanced indices are no longer adjacent + // + // self: Tensor[B, 5, 6, 7, 8, 9] + // indices: [:, :, Tensor[B, 2, 3], Tensor[2, 3], :] + // batched_indices: [arange(B).expand(B, 2, 3), :, :, Tensor[B, 2, 3], Tensor[2, 3], :] + // required values: Tensor[B, 2, 3, 5, 6, 9] + // actual values: Tensor[B, 5, 6, 2, 3, 9] + // + // The resolution is to move dims around until we get the right shape. + // The values is set up as [B, , , ...] + // we just have to move the to before the to produce + // [B, , , ...] + return swap_regions(values, num_leading_nones, max_index_dim); +} + +std::tuple> index_put_batch_rule( + const Tensor& self, + std::optional self_bdim, + ArrayRef> indices, + ArrayRef> indices_bdims, + const Tensor& values, + std::optional values_bdim, + bool accumulate) { + TORCH_INTERNAL_ASSERT(indices.size() == indices_bdims.size()); + + // find the batch_size + c10::SymInt batch_size = 0; + if (self_bdim || values_bdim) { + batch_size = get_bdim_size2_symint(self, self_bdim, values, values_bdim); + } else { + // one or more of the indices is batched. + for (size_t i = 0; i < indices.size(); i++) { + if (indices_bdims[i] && indices[i].has_value()) { + batch_size = indices[i].value().sym_size(*indices_bdims[i]); + break; + } + } + } + + auto [self_, indices_, values_] = index_put_batch_rule_helper( + self, self_bdim, indices, indices_bdims, values, values_bdim, batch_size); + + // Why do we need to permute values? + // See NOTE [Advanced indexing (index.Tensor) batch rule] for details, + // but the gist is that index_put effectively does the following: + // - result = self_.clone() + // - result[indices_] = values + // - return result + // Now, the problem is, result[indices_] might return a Tensor whose shape is + // the shape of values, but permuted. This is because the shape of result[indices_] + // depends on if the original indices "have adjacent advanced indices" + // and the batched `indices_` might change the "have adjacent advanced indices" property + values_ = maybe_permute_values(values_, indices, indices_bdims); + + auto result = at::index_put(self_, List>(indices_), values_, accumulate); + return std::make_tuple(std::move(result), 0); +} + +// plumbing done since we don't support List> in codegen +Tensor index_put_plumbing(const Tensor & self, const List> & indices, + const Tensor & values, bool accumulate) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "index_put_plumbing"); + int64_t cur_level = maybe_layer->layerId(); + + // on device mismatch, we can move 0d tensors to self device + auto values_ = values; + if (values.device() != self.device() && values.numel() == 1 && values.dim() == 0) { + values_ = values.to(self.device()); + } + + if (!isBatchedAtLevel(self, cur_level) && !isBatchedAtLevel(indices, cur_level) && !isBatchedAtLevel(values_, cur_level)) { + return self.index_put(indices, values_, accumulate); + } + auto [self_value, self_bdim, indices_value, indices_bdims, values_value, values_bdim] = + unpackSelfAndIndicesAndValuesAtCurrentLevel(self, indices, values_, cur_level); + auto results = index_put_batch_rule(self_value, self_bdim, indices_value, indices_bdims, values_value, values_bdim, accumulate); + return makeBatched(std::get<0>(results), std::get<1>(results), cur_level); +} + +namespace { + +template +std::tuple> scatter_batch_rule( + Func f, + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Scalar& value, Args... args) { + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto index_logical_rank = rankWithoutBatchDim(index, index_bdim); + auto batch_size = get_bdim_size2(self, self_bdim, index, index_bdim); + + auto self_ = moveBatchDimToFront(self, self_bdim); + auto index_ = moveBatchDimToFront(index, index_bdim); + + if (self_logical_rank == 0) { + self_ = self_.unsqueeze(-1); + } + if (index_logical_rank == 0) { + index_ = index_.unsqueeze(-1); + } + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + index_ = ensure_has_bdim(index_, index_bdim.has_value(), batch_size); + auto physical_dim = getPhysicalDim(self_, /*has_batch_dim*/true, dim); + + auto result = f(self_, physical_dim, index_, value, args...); + // result should have same shape as self + if (self_logical_rank == 0) { + result = result.squeeze(-1); + } + return std::make_tuple(std::move(result), 0); +} + +template +inline std::tuple> scatter_batch_rule( + Func f, + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim, Args... args) { + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto index_logical_rank = rankWithoutBatchDim(index, index_bdim); + auto src_logical_rank = rankWithoutBatchDim(src, src_bdim); + auto batch_size = get_bdim_size3(self, self_bdim, index, index_bdim, src, src_bdim); + + auto self_ = moveBatchDimToFront(self, self_bdim); + auto index_ = moveBatchDimToFront(index, index_bdim); + auto src_ = moveBatchDimToFront(src, src_bdim); + + if (self_logical_rank == 0) { + self_ = self_.unsqueeze(-1); + } + if (index_logical_rank == 0) { + index_ = index_.unsqueeze(-1); + } + if (src_logical_rank == 0) { + src_ = src_.unsqueeze(-1); + } + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + index_ = ensure_has_bdim(index_, index_bdim.has_value(), batch_size); + src_ = ensure_has_bdim(src_, src_bdim.has_value(), batch_size); + auto physical_dim = getPhysicalDim(self_, /*has_batch_dim*/true, dim); + + auto result = f(self_, physical_dim, index_, src_, args...); + // result should have same shape as self + if (self_logical_rank == 0) { + result = result.squeeze(-1); + } + return std::make_tuple(std::move(result), 0); +} + +} // namespace + +std::tuple> scatter_value_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Scalar& value) { + return scatter_batch_rule(ATEN_FN2(scatter, value), + self, self_bdim, dim, index, index_bdim, value); +} + +std::tuple> scatter_src_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim) { + return scatter_batch_rule(ATEN_FN2(scatter, src), + self, self_bdim, dim, index, index_bdim, src, src_bdim); +} + +std::tuple> scatter_add_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim) { + return scatter_batch_rule(ATEN_FN(scatter_add), + self, self_bdim, dim, index, index_bdim, src, src_bdim); +} + +static void check_scatter_inplace_bdim( + std::optional self_bdim, + std::optional index_bdim, + std::optional src_bdim, + const char* schema_name) { + if (!self_bdim.has_value() && (index_bdim.has_value() || src_bdim.has_value())) { + vmapIncompatibleInplaceError(schema_name); + } +} + +std::tuple> scatter_add__batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim) { + check_scatter_inplace_bdim(self_bdim, index_bdim, src_bdim, "scatter_add_"); + return scatter_batch_rule(ATEN_FN(scatter_add_), + self, self_bdim, dim, index, index_bdim, src, src_bdim); +} + +std::tuple> scatter_reduce_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim, + const std::string_view reduce) { + return scatter_batch_rule(ATEN_FN2(scatter, reduce), + self, self_bdim, dim, index, index_bdim, src, src_bdim, reduce); +} + +std::tuple> scatter_reduce_two_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim, + const std::string_view reduce, + bool include_self) { + return scatter_batch_rule(ATEN_FN2(scatter_reduce, two), + self, self_bdim, dim, index, index_bdim, src, src_bdim, reduce, include_self); +} + +std::tuple> scatter_reduce__two_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& src, std::optional src_bdim, + const std::string_view reduce, + bool include_self) { + check_scatter_inplace_bdim( + self_bdim, index_bdim, src_bdim, "scatter_reduce_"); + return scatter_batch_rule(ATEN_FN2(scatter_reduce_, two), + self, self_bdim, dim, index, index_bdim, src, src_bdim, reduce, include_self); +} + +std::tuple> scatter_value_reduce_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Scalar& src, + const std::string_view reduce) { + return scatter_batch_rule(ATEN_FN2(scatter, value_reduce), + self, self_bdim, dim, index, index_bdim, src, reduce); +} + +std::tuple> gather_batch_rule( + const Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + bool sparse_grad) { + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto index_logical_rank = rankWithoutBatchDim(index, index_bdim); + auto batch_size = get_bdim_size2(self, self_bdim, index, index_bdim); + + auto self_ = moveBatchDimToFront(self, self_bdim); + auto index_ = moveBatchDimToFront(index, index_bdim); + + if (self_logical_rank == 0) { + self_ = self_.unsqueeze(-1); + } + if (index_logical_rank == 0) { + index_ = index_.unsqueeze(-1); + } + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + index_ = ensure_has_bdim(index_, index_bdim.has_value(), batch_size); + auto physical_dim = getPhysicalDim(self_, /*has_batch_dim*/true, dim); + + auto result = at::gather(self_, physical_dim, index_, sparse_grad); + // result should have same rank as index + if (index_logical_rank == 0) { + result = result.squeeze(-1); + } + return std::make_tuple(std::move(result), 0); +} + +Tensor get_expanded_index(const Tensor& index, SymIntArrayRef self_size, int64_t dim) { + if (index.dim() == 0) { + return index.expand_symint(self_size); + } + dim = maybe_wrap_dim(dim, static_cast(self_size.size())); + + // setup new_index_shape as [BS, 1, ..., idx_size, ..., 1] + // to reshape index_ + auto idx_size = index.sym_size(0); // get non-batch size of index tensor + Tensor index_; + { + VmapSymDimVector new_index_shape(self_size.size(), 1); + new_index_shape[dim] = idx_size; + index_ = index.view_symint(new_index_shape); + } + // Now apply expand to index_ + { + VmapSymDimVector new_index_shape = {self_size.begin(), self_size.end()}; + new_index_shape[dim] = idx_size; + index_ = index_.expand_symint(new_index_shape); + } + return index_; +} + +Tensor index_select_decomp(const Tensor &self, int64_t dim, const Tensor &index) +{ + Tensor index_ = index; + if (self.dim() > index.dim()) { + index_ = get_expanded_index(index, self.sym_sizes(), dim); + } + + auto result = at::gather(self, dim, index_); + + // output of gather has same dimension as `index` while + // output of index_select has same dimension as self + // Eg. t = torch.tensor(1) + // idx = torch.tensor([0]) + // torch.index_select(t, 0, idx) # 0-D + // torch.gather(t, 0, idx) # 1-D + if (self.dim() == 0 && result.dim() != 0) { + result = result.squeeze(-1); + } + + return result; +} + +Tensor index_copy_decomp( + const Tensor &self, int64_t dim, + const Tensor &index, const Tensor &source) +{ + Tensor index_ = index; + if (self.dim() > index.dim()) { + index_ = get_expanded_index(index, self.sym_sizes(), dim); + } + + return at::scatter(self, dim, index_, source); ; +} + +// Note [Fix vmap slice_scatter] +// registers a decomposition for `slice_scatter` that calls into `slice.src` +// *_scatter operators have some special semantics though, that we can't easily +// through a decomposition: slice_scatter's output needs to have the same +// size, size, strides and storage_offset as the input. +Tensor slice_scatter_decomp(const Tensor &self, const Tensor &src, + int64_t dim, std::optional start, + std::optional end, int64_t step) +{ + auto idx = at::arange(start.value_or(0), end.value_or(self.size(dim)), step, self.options().dtype(kLong)); + idx = get_expanded_index(idx, self.sym_sizes(), dim); + return at::scatter(self, dim, idx, src); +} + +Tensor select_scatter_decomp( + const Tensor &self, const Tensor &source, + int64_t dim, int64_t index) +{ + // supports negative index + index = maybe_wrap_dim(index, self.size(dim)); + auto index_ = at::scalar_tensor(index, self.options().dtype(kLong)); + + return at::scatter(self, dim, index_.expand_as(self), source.unsqueeze(dim).expand_as(self)); +} + +std::tuple> diagonal_scatter_batch_rule( + const Tensor &self, std::optional self_bdim, + const Tensor &src, std::optional src_bdim, + int64_t offset, int64_t dim1, int64_t dim2) +{ + auto self_ = moveBatchDimToFront(self, self_bdim); + auto src_ = moveBatchDimToFront(src, src_bdim); + + auto batch_size = get_bdim_size2(self, self_bdim, src, src_bdim); + + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + src_ = ensure_has_bdim(src_, src_bdim.has_value(), batch_size); + + auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + dim1 = maybe_wrap_dim(dim1, self_logical_rank) + 1; + dim2 = maybe_wrap_dim(dim2, self_logical_rank) + 1; + + return std::make_tuple(at::diagonal_scatter(self_, src_, offset, dim1, dim2), 0); +} + +std::tuple> index_add_batch_rule_impl( + Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& other, std::optional other_bdim, + const Scalar& alpha, + const bool inplace) { + + if (inplace && !self_bdim.has_value()){ + vmapIncompatibleInplaceError("index_add_"); + } + + if (!index_bdim) { + // Handle scalar tensors... self, other can be scalar tensors + const auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + const auto other_logical_rank = rankWithoutBatchDim(other, other_bdim); + auto self_ = moveBatchDimToFront(self, self_bdim); + if (self_logical_rank == 0) { + self_ = self_.unsqueeze(-1); + } + auto other_ = moveBatchDimToFront(other, other_bdim); + if (other_logical_rank == 0) { + other_ = other_.unsqueeze(-1); + } + dim = maybe_wrap_dim(dim, self_logical_rank); + + const auto batch_size = get_bdim_size2(self, self_bdim, other, other_bdim); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + other_ = ensure_has_bdim(other_, other_bdim.has_value(), batch_size); + + if (inplace) { + self_.index_add_(dim + 1, index, other_, alpha); + if (self_logical_rank == 0) { + self_ = self_.squeeze(-1); + } + return std::make_tuple(self, 0); + } + + auto result = self_.index_add(dim + 1, index, other_, alpha); + if (self_logical_rank == 0) { + result = result.squeeze(-1); + } + return std::make_tuple(std::move(result), 0); + } + + // Index is batched. For-loop and stack is the best thing I can come up with + // right now. We really want generalized index_add kernel in PyTorch + auto batch_size = get_bdim_size3(self, self_bdim, other, other_bdim, index, index_bdim); + std::vector results; + if (!inplace) { + results.reserve(batch_size); + } + for (const auto i : c10::irange(0, batch_size)) { + const auto& self_slice = self_bdim.has_value() ? + self.select(*self_bdim, i) : self; + const auto& other_slice = other_bdim.has_value() ? + other.select(*other_bdim, i) : other; + const auto& index_slice = index_bdim.has_value() ? + index.select(*index_bdim, i) : index; + + if (inplace) { + self_slice.index_add_(dim, index_slice, other_slice, alpha); + } else { + results.push_back(at::index_add(self_slice, dim, index_slice, other_slice, alpha)); + } + } + if (inplace) { + return std::make_tuple(at::stack(self), 0); + } + return std::make_tuple(at::stack(results), 0); +} + +void index_add__batch_rule( + Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& other, std::optional other_bdim, + const Scalar& alpha) { + index_add_batch_rule_impl(self, self_bdim, dim, index, index_bdim, other, + other_bdim, alpha, true); +} + +std::tuple> index_add_batch_rule( + Tensor& self, std::optional self_bdim, + int64_t dim, + const Tensor& index, std::optional index_bdim, + const Tensor& other, std::optional other_bdim, + const Scalar& alpha) { + auto self_ = self.clone(at::MemoryFormat::Preserve); + return index_add_batch_rule_impl(self_, self_bdim, dim, index, index_bdim, + other, other_bdim, alpha, false); +} + +std::tuple binary_pointwise_align( + const Tensor & self, + std::optional self_bdim, + const Tensor & mask, + std::optional mask_bdim) { + // compute max logical rank + auto tensor_logical_rank = rankWithoutBatchDim(self, self_bdim); + auto other_logical_rank = rankWithoutBatchDim(mask, mask_bdim); + auto max_logical_rank = std::max(tensor_logical_rank, other_logical_rank); + + auto tensor_ = moveBatchDimToFront(self, self_bdim); + auto other_ = moveBatchDimToFront(mask, mask_bdim); + + // If the dimensions aren't aligned, we need to line them up. + // Tensor[B, 3] + Tensor[2, 5, 3] -> Tensor[B, 1, 1, 3] + Tensor[2, 5, 3] + // Note that only tensors that have a batch dim need to be modified. + // Tensor[B, 2, 3, 5] + Tensor[5] -> no changes needed + tensor_ = maybePadToLogicalRank(tensor_, self_bdim, max_logical_rank); + other_ = maybePadToLogicalRank(other_, mask_bdim, max_logical_rank); + + return std::make_tuple(std::move(tensor_), std::move(other_)); +} + +std::tuple> masked_fill_scalar_batch_rule( + const Tensor & self, + std::optional self_bdim, + const Tensor & mask, + std::optional mask_bdim, + const Scalar& source) { + auto tensors = binary_pointwise_align(self, self_bdim, mask, mask_bdim); + auto result = at::masked_fill(std::get<0>(tensors), std::get<1>(tensors), source); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> index_fill_batch_rule_helper( + int64_t batch_size, + int64_t self_logical_rank, + int64_t index_logical_rank, + Tensor & self_, + int64_t dim, + Tensor & index_, + const Scalar & value + ){ + if (self_logical_rank != 0){ + auto index_offset = at::arange( + batch_size, + at::TensorOptions().dtype(index_.scalar_type()).device(index_.device()) + ); + if (index_logical_rank == 0){ + index_ = index_.unsqueeze(-1); + } + index_ = index_.add(index_offset.unsqueeze(-1), self_.size(dim + 1)); + index_ = reshape_dim_into(0, 0, index_); + self_ = reshape_dim_into(0, dim, self_); + self_.index_fill_(dim, index_, value); + self_ = reshape_dim_outof(dim, batch_size, self_); + return std::make_tuple(self_, dim); + } + + // If self_logical_rank == 0, the batch dim is certainly 0, and we must apply batched indices to each row. + if (index_logical_rank != 0){ + index_ = reshape_dim_into(0, 0, index_); + } + self_.unsqueeze_(-1); + self_.index_fill_(dim + 1, index_, value); + self_.squeeze_(-1); + + return std::make_tuple(self_, 0); +} + +std::tuple> index_fill_int_scalar_batch_rule_impl( + Tensor & self, std::optional self_bdim, + int64_t dim, + const Tensor & index, std::optional index_bdim, + const Scalar & value, + const bool inplace) { + const auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + const auto index_logical_rank = rankWithoutBatchDim(index, index_bdim); + Tensor self_ = moveBatchDimToFront(self, self_bdim); + Tensor index_ = moveBatchDimToFront(index, index_bdim); + dim = maybe_wrap_dim(dim, self_logical_rank); + + if (inplace && !self_bdim.has_value()) { + vmapIncompatibleInplaceError("index_fill_"); + } + + if (!index_bdim) { + if (self_logical_rank == 0){ + self_.unsqueeze_(-1); + } + self_.index_fill_(dim + 1, index_, value); + if (self_logical_rank == 0) { + self_.squeeze_(-1); + } + return std::make_tuple(self_, 0); + } + + auto batch_size = get_bdim_size2(self, self_bdim, index, index_bdim); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + index_ = ensure_has_bdim(index_, index_bdim.has_value(), batch_size); + + if (inplace) { + // Do for-loop for in-place because we cannot reshape + // `self_` having an incompatible stride without copying. + for (const auto i : c10::irange(0, batch_size)) { + const auto& self_slice = self_.select(0, i); + const auto& index_slice = index_.select(0, i); + self_slice.index_fill_( + dim, + index_slice, + value + ); + } + return std::make_tuple(self_, 0); + } + + if (!self_bdim.has_value()) { + self_ = self_.clone(); + } + + return index_fill_batch_rule_helper(batch_size, self_logical_rank, index_logical_rank, self_, dim, index_, value); +} + +std::tuple> index_fill_int_tensor_batch_rule_impl( + Tensor & self, std::optional self_bdim, + int64_t dim, + const Tensor & index, std::optional index_bdim, + const Tensor & value, std::optional value_bdim, + const bool inplace) { + const auto self_logical_rank = rankWithoutBatchDim(self, self_bdim); + const auto index_logical_rank = rankWithoutBatchDim(index, index_bdim); + Tensor self_ = moveBatchDimToFront(self, self_bdim); + Tensor index_ = moveBatchDimToFront(index, index_bdim); + Tensor value_ = moveBatchDimToFront(value, value_bdim); + dim = maybe_wrap_dim(dim, self_logical_rank); + + if (inplace && !self_bdim.has_value()) { + vmapIncompatibleInplaceError("index_fill_"); + } + + if (!index_bdim && !value_bdim) { + if (self_logical_rank == 0){ + self_.unsqueeze_(-1); + } + self_.index_fill_(dim + 1, index_, value); + if (self_logical_rank == 0) { + self_.squeeze_(-1); + } + return std::make_tuple(self_, 0); + } + + auto batch_size = get_bdim_size3(self, self_bdim, index, index_bdim, value, value_bdim); + self_ = ensure_has_bdim(self_, self_bdim.has_value(), batch_size); + index_ = ensure_has_bdim(index_, index_bdim.has_value(), batch_size); + + if (inplace || value_bdim.has_value()) { + // Do for-loop for in-place because we cannot reshape + // `self_` having an incompatible stride without copying. + // If value has a batch dim, we do for-loop as well because + // index_fill_ supports 1-element tensor only. + for (const auto i : c10::irange(0, batch_size)) { + const auto& self_slice = self_.select(0, i); + const auto& index_slice = index_.select(0, i); + self_slice.index_fill_( + dim, + index_slice, + value_bdim.has_value() ? value_.select(0, i) : value_ + ); + } + return std::make_tuple(self_, 0); + } + + if (!self_bdim.has_value()) { + self_ = self_.clone(); + } + + // calling .item() on value is safe here because value is guaranteed to not be a batched tensor. + return index_fill_batch_rule_helper(batch_size, self_logical_rank, index_logical_rank, self_, dim, index_, value.item()); +} + +void index_fill__int_scalar_batch_rule( + Tensor & self, std::optional self_bdim, + int64_t dim, + const Tensor & index, std::optional index_bdim, + const Scalar & value) { + index_fill_int_scalar_batch_rule_impl(self, self_bdim, dim, index, index_bdim, value, true); +} + +void index_fill__int_tensor_batch_rule( + Tensor & self, std::optional self_bdim, + int64_t dim, + const Tensor & index, std::optional index_bdim, + const Tensor & value, std::optional value_bdim) { + index_fill_int_tensor_batch_rule_impl(self, self_bdim, dim, index, index_bdim, value, value_bdim, true); +} + +std::tuple> index_fill_int_scalar_batch_rule( + const Tensor & self, std::optional self_bdim, + int64_t dim, + const Tensor & index, std::optional index_bdim, + const Scalar & value) { + auto self_ = self.clone(at::MemoryFormat::Preserve); + return index_fill_int_scalar_batch_rule_impl(self_, self_bdim, dim, index, index_bdim, value, false); +} + +std::tuple> index_fill_int_tensor_batch_rule( + const Tensor & self, std::optional self_bdim, + int64_t dim, + const Tensor & index, std::optional index_bdim, + const Tensor & value, std::optional value_bdim) { + auto self_ = self.clone(at::MemoryFormat::Preserve); + return index_fill_int_tensor_batch_rule_impl(self_, self_bdim, dim, index, index_bdim, value, value_bdim, false); +} + +std::tuple> repeat_interleave_Tensor_batch_rule( + const Tensor& repeat, std::optional repeat_bdim, + std::optional output_size) { + if (!repeat_bdim.has_value()) { + // `repeat` is not batched, so the output length (the sum of `repeat`) is + // the same for every element of the batch. Re-dispatch to the regular + // implementation, which also handles any outer vmap levels correctly. + auto result = at::repeat_interleave_symint(repeat, std::move(output_size)); + return std::make_tuple(std::move(result), std::nullopt); + } + // When `repeat` is batched the output length is data-dependent (it equals the + // sum of `repeat`, which may differ between batch elements), so vmap cannot + // infer a single static output shape. Require the user to pass `output_size`. + TORCH_CHECK( + output_size.has_value(), + "repeat_interleave: vmapping over the `repeats` tensor requires the " + "`output_size` argument to be specified, because the size of the output " + "equals the sum of `repeats`, which is data-dependent and may differ " + "between batch elements. Please pass output_size, e.g. " + "output_size=int(repeats.sum(-1).max())."); + + const auto repeat_ = moveBatchDimToFront(repeat, repeat_bdim); + TORCH_CHECK( + repeat_.dim() == 2, + "repeat_interleave: the `repeats` tensor must be 1-dimensional for each " + "batch element, but got a ", repeat_.dim() - 1, "-dimensional tensor."); + + auto out_size = output_size.value(); + // Construct the gather indices without any data-dependent shapes so the rule + // is a regular batched computation. For each batch element b: + // marks[b, cumsum(repeat[b])] += 1 + // out[b] = marks[b, :output_size].cumsum() + // which yields index i repeated repeat[b, i] times, e.g. + // repeat = [4, 0, 8] -> [0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2]. + const auto batch_size = repeat_.sym_size(0); + // Accumulate in int64 to avoid overflowing `repeat_`'s dtype for large + // outputs, and to keep the gather indices in the dtype repeat_interleave + // is expected to return. + const auto cumsum = repeat_.cumsum(-1, at::kLong); + auto marks = at::zeros_symint( + {batch_size, out_size + 1}, repeat_.options().dtype(at::kLong)); + marks = marks.scatter_add(-1, cumsum, at::ones_like(cumsum)); + auto result = marks.narrow_symint(-1, 0, std::move(out_size)).cumsum(-1); + return std::make_tuple(std::move(result), 0); +} + +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + m.impl("index.Tensor", index_plumbing); + m.impl("index_put_", index_put__plumbing); + m.impl("index_put", index_put_plumbing); + m.impl("_index_put_impl_", _index_put_impl__plumbing); + m.impl("slice_scatter", slice_scatter_decomp); + m.impl("select_scatter", select_scatter_decomp); + m.impl("index_copy", index_copy_decomp); + m.impl("index_select", index_select_decomp); + VMAP_SUPPORT2(masked_fill, Scalar, masked_fill_scalar_batch_rule); + VMAP_SUPPORT2(index_fill_, int_Tensor, index_fill__int_tensor_batch_rule); + VMAP_SUPPORT2(index_fill_, int_Scalar, index_fill__int_scalar_batch_rule); + VMAP_SUPPORT2(index_fill, int_Tensor, index_fill_int_tensor_batch_rule); + VMAP_SUPPORT2(index_fill, int_Scalar, index_fill_int_scalar_batch_rule); + VMAP_SUPPORT(index_add_, index_add__batch_rule); + VMAP_SUPPORT(index_add, index_add_batch_rule); + VMAP_SUPPORT(diagonal_scatter, diagonal_scatter_batch_rule); + VMAP_SUPPORT(gather, gather_batch_rule); + VMAP_SUPPORT2(repeat_interleave, Tensor, repeat_interleave_Tensor_batch_rule); + VMAP_SUPPORT2(scatter, value, scatter_value_batch_rule); + VMAP_SUPPORT2(scatter, src, scatter_src_batch_rule); + VMAP_SUPPORT(scatter_add, scatter_add_batch_rule); + VMAP_SUPPORT(scatter_add_, scatter_add__batch_rule); + VMAP_SUPPORT2(scatter, reduce, scatter_reduce_batch_rule); + VMAP_SUPPORT2(scatter, value_reduce, scatter_value_reduce_batch_rule); + VMAP_SUPPORT2(scatter_reduce, two, scatter_reduce_two_batch_rule); + VMAP_SUPPORT2(scatter_reduce_, two, scatter_reduce__two_batch_rule); + // as_strided_scatter does not work with the for-loop fallback today, + // because as_strided_scatter will return an output that matches + // the strides/storage_offset of its input. + // With the for loop fallback, each input tensor is a slice into + // the larger batched tensor. + m.impl("as_strided_scatter", torch::CppFunction::makeFromBoxedFunction<&vmapErrorFallback>()); +} + +} // namespace at::functorch +// NOLINTEND(bugprone-unchecked-optional-access) diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesUnaryOps.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesUnaryOps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac82e82a8883a609414d0678ba546cfaf5a30cfb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesUnaryOps.cpp @@ -0,0 +1,182 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include + +namespace at::functorch { + +namespace{ +std::tuple> +clone_batch_rule( + const Tensor& self, + std::optional self_bdim, + std::optional memory_format) { + // Memory format support is a little tricky because vmap is allowed to move + // around batch dimensions and some memory formats are rank-dependent. + // Another weird case is: + // - a tensor with MemoryFormat::ChannelsLast MUST have 4 dimensions. Do we + // allow the user to clone a Tensor with 3 logical dimensions and 1 batch + // dim into a ChannelsLast Tensor? What about a Tensor with 3 logical dims + // and N>1 batch dims? + TORCH_CHECK(!memory_format.has_value() || memory_format == MemoryFormat::Preserve + || memory_format == MemoryFormat::Contiguous, + "NYI: Tensor.clone(memory_format) inside vmap is only supported with ", + "memory_format torch.preserve_format or torch.contiguous_format (got ", + *memory_format, ")"); + + if (memory_format == MemoryFormat::Contiguous) { + // There is an ambiguity here when the batch dims are not at the front of + // the tensor. + // >>> x = torch.randn(3, B0, 5) + // >>> y = vmap(lambda x: x.clone(torch.contiguous_format), in_dims=1, out_dims=0)(x) + // >>> y[0].is_contiguous() + // ??? + // Should we make the whole tensor contiguous, or should we + // make the non-batch dims contiguous? We've chosen the latter because + // philosophically vmap hides the batch dims and operates on a per-sample level. + auto self_ = moveBatchDimToFront(self, self_bdim); + auto result = at::clone(self_, memory_format); + return std::make_tuple(std::move(result), 0); + } + + TORCH_INTERNAL_ASSERT(!memory_format.has_value() || memory_format == MemoryFormat::Preserve); + auto result = at::clone(self, memory_format); + return std::make_tuple(std::move(result), self_bdim); +} + +std::tuple> +view_as_complex_batch_rule(const Tensor& self, std::optional self_bdim) { + // guard against the user passing in a batch of scalar tensors with batch + // size equal to 2. + TORCH_CHECK(self.sym_sizes().size() > 1, "Input tensor must have one or more dimensions"); + + auto self_ = moveBatchDimToFront(self, self_bdim); + auto result = at::view_as_complex(self_); + return std::make_tuple(std::move(result), 0); +} + +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + +#define UNARY_POINTWISE_ALL2(op, overload) \ + POINTWISE_BOXED2(op ## _, overload); \ + VMAP_SUPPORT2(op, overload, BASIC_UNARY_BATCH_RULE(ATEN_FN2(op, overload))); +#define UNARY_POINTWISE_ALL(op) \ + POINTWISE_BOXED(op ## _); \ + VMAP_SUPPORT(op, BASIC_UNARY_BATCH_RULE(ATEN_FN(op))); + + UNARY_POINTWISE(view_as_real); + VMAP_SUPPORT(view_as_complex, view_as_complex_batch_rule); + VMAP_SUPPORT(clone, clone_batch_rule); + + UNARY_POINTWISE(_to_copy); + UNARY_POINTWISE(alias); + UNARY_POINTWISE_ALL(abs); + UNARY_POINTWISE_ALL(acos); + UNARY_POINTWISE_ALL(acosh); + UNARY_POINTWISE(angle); + UNARY_POINTWISE_ALL(asin); + UNARY_POINTWISE_ALL(asinh); + UNARY_POINTWISE_ALL(atan); + UNARY_POINTWISE_ALL(atanh); + UNARY_POINTWISE_ALL(bitwise_not); + UNARY_POINTWISE_ALL(ceil); + UNARY_POINTWISE_ALL(cos); + UNARY_POINTWISE_ALL(cosh); + UNARY_POINTWISE(_conj); + UNARY_POINTWISE_ALL(deg2rad); + UNARY_POINTWISE(detach); + UNARY_POINTWISE_ALL(digamma); + UNARY_POINTWISE_ALL(erf); + UNARY_POINTWISE_ALL(exp); + UNARY_POINTWISE_ALL(expm1); + UNARY_POINTWISE_ALL(floor); + UNARY_POINTWISE_ALL(frac); + UNARY_POINTWISE(isnan); + UNARY_POINTWISE(isinf); + UNARY_POINTWISE(isposinf); + UNARY_POINTWISE(isneginf); + UNARY_POINTWISE_ALL(lgamma); + UNARY_POINTWISE_ALL(log); + UNARY_POINTWISE_ALL(log10); + UNARY_POINTWISE_ALL(log1p); + UNARY_POINTWISE_ALL(log2); + UNARY_POINTWISE_ALL(logical_not); + UNARY_POINTWISE_ALL(logit); + UNARY_POINTWISE_ALL(mish); + UNARY_POINTWISE_ALL(mvlgamma); + UNARY_POINTWISE_ALL(nan_to_num); + UNARY_POINTWISE_ALL(neg); + UNARY_POINTWISE_ALL(rad2deg); + UNARY_POINTWISE_ALL(reciprocal); + UNARY_POINTWISE_ALL(round); + UNARY_POINTWISE_ALL2(round, decimals); + UNARY_POINTWISE_ALL(rsqrt); + UNARY_POINTWISE_ALL(sgn); + UNARY_POINTWISE_ALL(sign); + UNARY_POINTWISE(signbit); + UNARY_POINTWISE_ALL(sin); + UNARY_POINTWISE_ALL(sinc); + UNARY_POINTWISE_ALL(sinh); + UNARY_POINTWISE_ALL(sqrt); + UNARY_POINTWISE_ALL(tan); + UNARY_POINTWISE_ALL(threshold); + UNARY_POINTWISE_ALL(trunc); + + // special-related + UNARY_POINTWISE_ALL(i0); + UNARY_POINTWISE_ALL(erfc); + UNARY_POINTWISE_ALL(erfinv); + UNARY_POINTWISE_ALL(exp2); + + // torch.special.* functions + UNARY_POINTWISE(special_entr); + UNARY_POINTWISE(special_erfcx); + UNARY_POINTWISE(special_i0e); + UNARY_POINTWISE(special_i1); + UNARY_POINTWISE(special_i1e); + UNARY_POINTWISE(special_ndtri); + POINTWISE_BOXED(special_bessel_j0); + POINTWISE_BOXED(special_spherical_bessel_j0); + POINTWISE_BOXED(special_bessel_j1); + POINTWISE_BOXED(special_modified_bessel_i0); + POINTWISE_BOXED(special_modified_bessel_i1); + POINTWISE_BOXED(special_scaled_modified_bessel_k0); + POINTWISE_BOXED(special_modified_bessel_k0); + POINTWISE_BOXED(special_scaled_modified_bessel_k1); + POINTWISE_BOXED(special_modified_bessel_k1); + POINTWISE_BOXED(special_bessel_y0); + POINTWISE_BOXED(special_bessel_y1); + + // Activation functions (from https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity) + UNARY_POINTWISE_ALL(elu); + UNARY_POINTWISE(hardshrink); + UNARY_POINTWISE_ALL(hardsigmoid); + UNARY_POINTWISE_ALL(hardtanh); + UNARY_POINTWISE_ALL(hardswish); + UNARY_POINTWISE_ALL(leaky_relu); + UNARY_POINTWISE_ALL(relu); + UNARY_POINTWISE_ALL(celu); + UNARY_POINTWISE(gelu); + UNARY_POINTWISE_ALL(sigmoid); + UNARY_POINTWISE_ALL(silu); + UNARY_POINTWISE(softplus); + UNARY_POINTWISE(softshrink); + UNARY_POINTWISE_ALL(tanh); + + POINTWISE_BOXED(fill_.Scalar); + POINTWISE_BOXED(zero_); + // This is special because this op doesn't return anything + m.impl("_assert_tensor_metadata", native::_assert_tensor_metadata); + +#undef UNARY_POINTWISE +#undef UNARY_POINTWISE_ALL + +} + +#undef INVOKE +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesViews.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesViews.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f33119581ca750c5b0c163f33112f286cd3dbf6b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchRulesViews.cpp @@ -0,0 +1,692 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace at::functorch { + +// Note [Adding vmap support for an operator] +// Hey there! So you have an operator and you want to get it to work with vmap. +// For example, let's say you just invented the `sum.int` operator and want to make +// it so that the following works. +// >>> tensor = torch.randn(B, 3) +// >>> vmap(torch.sum, (0, None))(tensor, 0)` works +// There are three main ways to do so. +// +// Note [Writing batch rule for out-of-place operators] +// If your operator is out-of-place, you can write a batch rule for it. +// The batch rule defines how to perform the operator on inputs where each +// Tensor input may have an additional dimension that is being vmapped over. +// We refer to this dimension as the *batch dimension* or bdim for short. +// +// For example, let's consider writing a batch rule for +// `Tensor sum(const Tensor& self, int64_t dim)`. The signature of the +// batch rule has an additional std::optional argument after each +// Tensor argument and return. So, in this case, the batch rule has signature +// tuple> sum_batch_rule( +// const Tensor& self, std::optional self_bdim, int64_t dim); +// +// The vmap call above invokes the batch rule with `self = tensor`, +// `self_bdim = 0`, and `dim = 0`. Note that there are **no BatchedTensors** +// involved in this case; there exists some plumbing that automatically unwraps +// BatchedTensors before calling the batch rule. +// +// To write the logic of the batch rule: think about the semantics of the +// `sum` operation if `self` had an additional dimension (indicated by self_bdim): +// - If `self_bdim` is null, then we just do `result = self.sum(dim)` as usual +// - If `self_bdim` is not-null, then we need to modify `dim`. `dim` is equal +// to whatever the user passed in (0 in this case), but we should actually +// perform the reduction over dimension 1 and do `result = self.sum(1)` +// because dim 0 is being vmapped over. +// Finally, we return the result as well as a new bdim +// - If `self_bdim` is null, then there's no batch dim in the result. +// - If `self_bdim` is not-null, then we return where the bdim is. +// Since we invoked `result = self.sum(1)`, the bdim is still at dim 0. +// +// Now that we have written `sum_batch_rule`, we have to register it inside a +// TORCH_LIBRARY_IMPL block: +// TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { +// ... +// VMAP_SUPPORT2(sum, int, sum_batch_rule); +// ... +// } +// +// Note [Reusing batch rules to add vmap support for a complicated operator] +// Can't figure out how to write a batch rule for a big operation? If the +// operation can be expressed as a composition of other operations that do have +// batch rules, then that is another way to add vmap support. For example, +// consider the following schema +// func: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) +// and assume we already have batching rules for basic arithmetic operators. +// +// To add vmap support, define a decomposition using the same signature: +// Tensor addcmul_decomp(const Tensor& self, const Tensor& tensor1, +// const Tensor& tensor2, const Scalar& value) { +// auto product = torch.mul(tensor1, tensor2); +// return torch.add(self, product, value); +// } +// And register it inside a TORCH_LIBRARY_IMPL block: +// TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { +// ... +// m.impl("addcmul", addcmul_decomp); +// ... +// } +// +// Note [Writing batch rule for in-place operators] +// TODO: This is kinda complicated. Saving this for a future date. + +namespace{ + +std::tuple> clone_batch_rule_result( + const Tensor& result, + std::optional result_bdim) { + return std::make_tuple( + result.clone(at::MemoryFormat::Contiguous), result_bdim); +} + +std::tuple> unsqueeze_batch_rule( + const Tensor& self, + std::optional self_bdim, + int64_t dim) { + auto self_ = moveBatchDimToFront(self, self_bdim); + auto rank = rankWithoutBatchDim(self, self_bdim); + dim = maybe_wrap_dim(dim, rank + 1) + 1; + return std::make_tuple(self_.unsqueeze(dim), 0); +} + +std::tuple> unsqueeze_copy_batch_rule( + const Tensor& self, + std::optional self_bdim, + int64_t dim) { + auto [result, result_bdim] = unsqueeze_batch_rule(self, self_bdim, dim); + return clone_batch_rule_result(result, result_bdim); +} + +// NB: repeat is not actually a view, but it is in this file +std::tuple> repeat_batch_rule( + const Tensor& self, + std::optional self_bdim, + c10::SymIntArrayRef sizes) { + + SymDimVector sizes_with_bdim = { sizes.begin(), sizes.end() }; + sizes_with_bdim.insert(sizes_with_bdim.begin(), 1); + auto self_ = moveBatchDimToFront(self, self_bdim); + while (self_.dim() < static_cast(sizes_with_bdim.size())) { + self_ = self_.unsqueeze(1); + } + return std::make_tuple(self_.repeat_symint(sizes_with_bdim), 0); +} + + +std::tuple> _unsafe_view_batch_rule( + const Tensor& self, + std::optional self_bdim, + c10::SymIntArrayRef size) { + auto self_ = moveBatchDimToFront(self, self_bdim); + SymDimVector view_size(size); + view_size.insert(view_size.begin(), self_.sym_size(0)); + + // See if the view is valid. If it's not, then we copy. + // It's OK to copy, because _unsafe_view(x) guarantees that x isn't used + // anymore. + const at::SymDimVector inferred_size = at::infer_size_dv(view_size, self_.sym_numel()); + const auto stride = at::detail::computeStride(self_.sym_sizes(), + self_.sym_strides(), + inferred_size); + if (!stride.has_value()) { + self_ = self_.contiguous(); + } + return std::make_tuple(at::_unsafe_view_symint(self_, view_size), 0); +} + +std::tuple> flip_batch_rule(const Tensor& self, std::optional self_bdim, IntArrayRef dims) { + auto self_ = moveBatchDimToFront(self, self_bdim); + VmapDimVector new_dims; + for (auto i: dims) { + new_dims.push_back(getPhysicalDim(self_, true, i)); + } + return std::make_tuple(at::flip(self_, new_dims), 0); +} + +const Tensor& resize__plumbing( + const Tensor& self, + IntArrayRef size, + std::optional optional_memory_format) { + TORCH_CHECK( + !optional_memory_format.has_value() || + optional_memory_format == c10::MemoryFormat::Contiguous, + "resize_: batching rule only supports None or Contiguous MemoryFormat"); + auto maybe_layer = maybeCurrentDynamicLayer(); + vmap_check_escaped(maybe_layer, "resize__plumbing"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + int64_t cur_level = maybe_layer->layerId(); + if (!isBatchedAtLevel(self, cur_level)) { + c10::impl::ExcludeDispatchKeyGuard guard2(DispatchKey::FuncTorchBatched); + return self.resize_(size, optional_memory_format); + } + + auto [self_value, self_bdim] = unwrapTensorAtLevel(self, cur_level); + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + + // TODO: The following algorithm only works for batch dim == 0. + // To get it to work for something else we need the ability to modify + // the BatchDims attribute of BatchedTensorImpl + TORCH_INTERNAL_ASSERT(self_bdim == 0, "NYI: resize_ batch rule for batch dim != 0"); + + // Resize the wrapped tensor + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + self_value = moveBatchDimToFront(self_value, self_bdim); + VmapDimVector new_size(size); + new_size.insert(new_size.begin(), self_value.size(*self_bdim)); + self_value.resize_(new_size); + + // Update the sizes and strides of the wrapper + auto* batched = maybeGetBatchedImpl(self); + TORCH_INTERNAL_ASSERT(batched); + batched->refreshTensorMetadata(); + + return self; +} + +std::tuple> squeeze_batch_rule(const Tensor& self, std::optional bdim) { + TORCH_INTERNAL_ASSERT(bdim.has_value()); + // Special case for scalar arrays to replicate PyTorch behavior. + if (self.dim() == 1) { + return std::make_tuple(self.alias(), bdim); + } + + // Manually calculate the output shape by eliding all dimensions of + // size 1 keeping track of where the batch index started and where it + // ended up moving to. We also ensure we do not drop the batch index. + auto shape = self.sym_sizes(); + SymDimVector squeezed_sizes; + bool before_batch_idx = true; + int64_t new_batch_idx = 0; + int64_t original_idx = 0; + + for (const auto& it : shape) { + // Keep only dimensions != 1 and the batch dimension (irrespective of size). + if (it != 1 || original_idx == bdim) { + squeezed_sizes.push_back(it); + if (original_idx == bdim) { + before_batch_idx = false; + } + // Only increment for the dimensions that will be kept in the output. + if (before_batch_idx) { + ++new_batch_idx; + } + } + ++original_idx; + } + + auto result = self.view_symint(squeezed_sizes); + return std::make_tuple(std::move(result), std::optional(new_batch_idx)); +} + +std::tuple> squeeze_copy_batch_rule( + const Tensor& self, + std::optional bdim) { + auto [result, result_bdim] = squeeze_batch_rule(self, bdim); + return clone_batch_rule_result(result, result_bdim); +} + +std::tuple> squeeze_dims_batch_rule( + const Tensor& self, std::optional bdim, IntArrayRef dims) { + TORCH_INTERNAL_ASSERT(bdim.has_value()); + // Special case for scalar arrays to replicate PyTorch behavior. + auto ndim = self.dim(); + if (ndim == 1) { + TORCH_CHECK( + dims.empty() || (dims.size() == 1 && dims[0] == 0), + "Dimension is out of range (expected to be in range of [-1, 0], but got ", dims); + return std::make_tuple(self.alias(), bdim); + } + + // Adjust any dimensions higher than the batch dimension + DimVector adjusted_dims(dims.begin(), dims.end()); + int64_t updated_batch_idx = *bdim; + for (auto &d : adjusted_dims) { + auto actual_dim = c10::maybe_wrap_dim(d, ndim - 1); + if (actual_dim < *bdim) { + d = actual_dim; + if (self.sym_size(actual_dim) == 1) { + // A column before batch dimension will be dropped so adjust accordingly. + --updated_batch_idx; + } + } else { + // Since dimension to be squeezed is after the batch dimension adjust by one to account + // for the original batch dimension. In this case batch dimension won't move. + d = actual_dim + 1; + } + } + return std::make_tuple(self.squeeze(adjusted_dims), std::optional(updated_batch_idx)); +} + +std::tuple> squeeze_copy_dims_batch_rule( + const Tensor& self, std::optional bdim, IntArrayRef dims) { + auto [result, result_bdim] = squeeze_dims_batch_rule(self, bdim, dims); + return clone_batch_rule_result(result, result_bdim); +} + +std::tuple> squeeze_dim_batch_rule( + const Tensor& self, std::optional bdim, int64_t dim) { + return squeeze_dims_batch_rule(self, bdim, {dim}); +} + +std::tuple> squeeze_copy_dim_batch_rule( + const Tensor& self, std::optional bdim, int64_t dim) { + return squeeze_copy_dims_batch_rule(self, bdim, {dim}); +} + +std::tuple> select_batching_rule(const Tensor& self, std::optional bdim, int64_t dim, c10::SymInt index) { + if (!bdim) { + return std::make_tuple(self.select_symint(dim, std::move(index)), std::nullopt); + } + + auto _self = moveBatchDimToFront(self, bdim); + auto dim_physical = getPhysicalDim(_self, true, dim); + auto result = _self.select_symint(dim_physical, std::move(index)); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> _reshape_alias_batch_rule(const Tensor& self, std::optional bdim, const c10::SymIntArrayRef shape, const c10::SymIntArrayRef strides) { + (void) strides; + TORCH_INTERNAL_ASSERT(bdim.has_value()); + + auto self_ = moveBatchDimToFront(self, bdim); + c10::SymDimVector new_shape(shape.size() + 1); + new_shape[0] = self_.sym_size(0); + std::copy(shape.begin(), shape.end(), new_shape.begin() + 1); + return std::make_tuple(at::reshape_symint(self_, new_shape), 0); +} + +std::tuple> roll_batch_rule(const Tensor& self, std::optional bdim, SymIntArrayRef shifts, IntArrayRef dims) { + TORCH_INTERNAL_ASSERT(bdim.has_value()); + + auto self_ = moveBatchDimToFront(self, bdim); + VmapDimVector new_dims; + if (!dims.empty()) { + for (auto i: dims) { + new_dims.push_back(getPhysicalDim(self, true, i)); + } + return std::make_tuple(at::roll_symint(self_, shifts, new_dims), 0); + } + // We will do something like: t.reshape(a, -1).roll(1, dims=[1, ]).reshape(old_shape) + auto old_shape = self_.sym_sizes(); + new_dims.push_back(1); + auto logical_rank = rankWithoutBatchDim(self, bdim); + if (logical_rank == 0) { + self_ = self_.unsqueeze(0); + } + + auto output = at::roll_symint(self_.flatten(1), shifts, new_dims); + // NOTE: For scalar tensor, we don't need to unsqueeze as reshape + // with `old_shape` takes care of it. + output = output.reshape_symint(old_shape); + return std::make_tuple(std::move(output), 0); +} + +std::tuple> diagonal_batching_rule( + const Tensor &self, std::optional self_bdim, + int64_t offset, int64_t dim1, int64_t dim2) +{ + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto dim1_ = maybe_wrap_dim(dim1, logical_rank) + 1; + auto dim2_ = maybe_wrap_dim(dim2, logical_rank) + 1; + auto result = at::diagonal(self_, offset, dim1_, dim2_); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> diagonal_backward_batch_rule( + const Tensor& grad_input, std::optional grad_input_bdim, + c10::SymIntArrayRef input_sizes, int64_t offset, int64_t dim1, int64_t dim2) { + auto logical_rank = rankWithoutBatchDim(grad_input, grad_input_bdim); + auto grad_input_ = moveBatchDimToFront(grad_input, grad_input_bdim); + dim1 = maybe_wrap_dim(dim1, logical_rank + 1) + 1; + dim2 = maybe_wrap_dim(dim2, logical_rank + 1) + 1; + c10::SymDimVector input_sizes_(input_sizes.size() + 1); + input_sizes_[0] = grad_input_.size(0); + std::copy(input_sizes.begin(), input_sizes.end(), input_sizes_.begin() + 1); + auto result = at::diagonal_backward_symint(grad_input_, input_sizes_, offset, dim1, dim2); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> slice_batch_rule( + const Tensor& self, + std::optional self_bdim, + int64_t dim, + std::optional start, + std::optional end, + c10::SymInt step) { + auto self_ = moveBatchDimToFront(self, self_bdim); + dim = getPhysicalDim(self, self_bdim.has_value(), dim); + + auto result = self_.slice_symint(dim, std::move(start), std::move(end), std::move(step)); + return std::make_tuple(std::move(result), 0); +} + +bool is_allowed_dim_on_scalar_tensor(int64_t dim) { + return dim == 0 || dim == -1; +} + +std::tuple> +transpose_int_batch_rule( + const Tensor& self, + std::optional self_bdim, + int64_t dim0, + int64_t dim1) { + // PyTorch has a special case where scalar_tensor.transpose(dim0, dim1) works + // for dim0, dim1 in {0, -1} and returns the scalar tensor. If the following happens: + // >>> x = torch.randn(B0) # the per-examples are all scalars + // >>> vmap(lambda x: x.transpose(0, -1), x) + // then we replicate this behavior. + if (/*physical*/self.dim() == 1 && is_allowed_dim_on_scalar_tensor(dim0) && + is_allowed_dim_on_scalar_tensor(dim1)) { + return std::make_tuple(self, self_bdim); + } + auto self_ = moveBatchDimToFront(self, self_bdim); + dim0 = getPhysicalDim(self, self_bdim.has_value(), dim0); + dim1 = getPhysicalDim(self, self_bdim.has_value(), dim1); + auto result = self_.transpose(dim0, dim1); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> +transpose_copy_int_batch_rule( + const Tensor& self, + std::optional self_bdim, + int64_t dim0, + int64_t dim1) { + auto [result, result_bdim] = + transpose_int_batch_rule(self, self_bdim, dim0, dim1); + return clone_batch_rule_result(result, result_bdim); +} + +std::tuple> permute_batching_rule( + const Tensor &self, std::optional self_bdim, IntArrayRef dims) +{ + if (!self_bdim.has_value()) { + return std::make_tuple(self.permute(dims), self_bdim); + } + + auto self_ = moveBatchDimToFront(self, self_bdim); + VmapDimVector dims_; + dims_.reserve(dims.size() + 1); + dims_.emplace_back(0); + for (auto dim : dims) { + dims_.emplace_back(getPhysicalDim(self_, self_bdim.has_value(), dim)); + } + + return std::make_tuple(self_.permute(dims_), 0); +} + +std::tuple> permute_copy_batching_rule( + const Tensor &self, std::optional self_bdim, IntArrayRef dims) +{ + auto [result, result_bdim] = permute_batching_rule(self, self_bdim, dims); + return clone_batch_rule_result(result, result_bdim); +} + +std::tuple> t_copy_batching_rule( + const Tensor& self, + std::optional self_bdim) { + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + TORCH_CHECK( + logical_rank <= 2, + "t() expects a tensor with <= 2 dimensions, but self is ", + logical_rank, + "D"); + if (logical_rank < 2) { + auto self_ = moveBatchDimToFront(self, self_bdim); + std::optional result_bdim; + if (self_bdim.has_value()) { + result_bdim = 0; + } + return clone_batch_rule_result(self_, result_bdim); + } + return transpose_copy_int_batch_rule(self, self_bdim, 0, 1); +} + +std::tuple> select_backward_batch_rule( + const Tensor& grad_input, std::optional grad_input_bdim, + c10::SymIntArrayRef input_sizes, int64_t dim, c10::SymInt index) { + auto logical_rank = rankWithoutBatchDim(grad_input, grad_input_bdim); + auto grad_input_ = moveBatchDimToFront(grad_input, grad_input_bdim); + dim = maybe_wrap_dim(dim, logical_rank + 1) + 1; + c10::SymDimVector input_sizes_(input_sizes.size() + 1); + input_sizes_[0] = grad_input_.sym_size(0); + std::copy(input_sizes.begin(), input_sizes.end(), input_sizes_.begin() + 1); + auto result = at::select_backward_symint(grad_input_, input_sizes_, dim, std::move(index)); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> slice_backward_batch_rule( + const Tensor& grad_input, std::optional grad_input_bdim, + SymIntArrayRef input_sizes, int64_t dim, c10::SymInt start, c10::SymInt end, c10::SymInt step) { + auto logical_rank = rankWithoutBatchDim(grad_input, grad_input_bdim); + auto grad_input_ = moveBatchDimToFront(grad_input, grad_input_bdim); + dim = maybe_wrap_dim(dim, logical_rank) + 1; + c10::SymDimVector input_sizes_(input_sizes.size() + 1); + input_sizes_[0] = grad_input_.size(0); + std::copy(input_sizes.begin(), input_sizes.end(), input_sizes_.begin() + 1); + auto result = at::slice_backward_symint(grad_input_, input_sizes_, dim, std::move(start), std::move(end), std::move(step)); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> view_batching_rule( + const Tensor &self, std::optional self_bdim, SymIntArrayRef sym_size) +{ + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + auto self_ = moveBatchDimToFront(self, self_bdim); + c10::SmallVector size_(sym_size.size() + 1); + // copy batch size + size_[0] = self_.sym_size(0); + std::copy(sym_size.cbegin(), sym_size.cend(), size_.begin() + 1); + return std::make_tuple(self_.view_symint(size_), 0); +} + +std::tuple> view_dtype_batch_rule( + const Tensor& self, + std::optional self_bdim, + ScalarType dtype) { + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + TORCH_CHECK( + logical_rank != 0 || self.itemsize() == c10::elementSize(dtype), + "self.dim() cannot be 0 to view ", self.scalar_type(), " as ", dtype, " (different element sizes)"); + auto self_ = moveBatchDimToFront(self, self_bdim); + return std::make_tuple(self_.view(dtype), 0); +} + +std::tuple> view_copy_batch_rule( + const Tensor& self, + std::optional self_bdim, + c10::SymIntArrayRef size) { + auto self_ = moveBatchDimToFront(self, self_bdim); + SymDimVector view_size(size.size() + 1); + view_size[0] = self_.size(0); + std::copy(size.cbegin(), size.cend(), view_size.begin() + 1); + + return std::make_tuple(at::view_copy_symint(self_, view_size), 0); +} + + +template +std::tuple> expand_batch_rule( + const Tensor &self, std::optional self_bdim, SymIntArrayRef size, bool implicit) +{ + auto self_dim = self.dim(); + TORCH_CHECK(static_cast(self_dim - 1) <= size.size(), + "expand: the number of sizes provided (", size.size(), ") ", + "must be greater or equal to the number of dimensions in the tensor (", static_cast(self_dim - 1), ")"); + + auto self_ = moveBatchDimToFront(self, self_bdim); + auto self_sizes = self_.sym_sizes(); + const auto& batch_size = self_sizes[0]; + + c10::SmallVector size_(size.size() + 1); + size_[0] = batch_size; + std::copy(size.cbegin(), size.cend(), size_.begin() + 1); + + // Here, we know we are expanding a (logical) tensor to a larger number + // of dimensions. We have to be careful because we can't call expand directly + // due to the presence of batch dimensions. + // + // As an example, let B0 be a batch dimension and consider expand(Tensor[B0, 3], [2, 3]). + // The result should be a tensor of size [B0, 2, 3]. + // A physical view of size [B0, 3] can't directly be expanded to size [B0, 2, 3] + // so the strategy here is to view it first as a tensor of size [B0, 1, 3] and + // then expand. + auto extra_dims = size.size() - (self_dim - 1); + c10::SmallVector view_shape(size_.size(), /*init_value*/1); + view_shape[0] = batch_size; + std::copy(self_sizes.cbegin() + 1, self_sizes.cend(), + view_shape.begin() + 1 + extra_dims); + + return std::make_tuple(Func(self_.view_symint(view_shape), size_, implicit), 0); +} + +std::tuple> unfold_batch_rule( + const Tensor &self, std::optional self_bdim, int64_t dim, int64_t size, int64_t step) +{ + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + dim = maybe_wrap_dim(dim, logical_rank) + 1; + if (logical_rank==0) { + self_ = self_.unsqueeze(-1); + } + auto result = self_.unfold(dim, size, step); + if (logical_rank==0) { + result = result.squeeze(-1); + } + return std::make_tuple(std::move(result), 0); +} + +std::tuple> narrow_copy_batch_rule( + const Tensor &self, std::optional self_bdim, int64_t dim, c10::SymInt start, c10::SymInt length) +{ + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + dim = maybe_wrap_dim(dim, logical_rank) + 1; + auto result = self_.narrow_copy_symint(dim, std::move(start), std::move(length)); + return std::make_tuple(std::move(result), 0); +} + +std::tuple, std::optional> unsafe_split_batch_rule( + const Tensor& self, + std::optional self_bdim, + c10::SymInt split_size, + int64_t dim) { + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + dim = maybe_wrap_dim(dim, logical_rank) + 1; + auto result = self_.unsafe_split_symint(std::move(split_size), dim); + return std::make_tuple(std::move(result), 0); +} + +std::tuple, std::optional> unbind_copy_batch_rule( + const Tensor& self, + std::optional self_bdim, + int64_t dim) { + TORCH_INTERNAL_ASSERT(self_bdim.has_value()); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + dim = maybe_wrap_dim(dim, logical_rank) + 1; + auto result = at::unbind_copy(self_, dim); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> diag_embed_batch_rule(const Tensor& self, std::optional self_bdim, int64_t offset, int64_t dim1, int64_t dim2) { + auto logical_rank = rankWithoutBatchDim(self, self_bdim); + auto self_ = moveBatchDimToFront(self, self_bdim); + dim1 = maybe_wrap_dim(dim1, logical_rank + 1) + 1; + dim2 = maybe_wrap_dim(dim2, logical_rank + 1) + 1; + return std::make_tuple(at::diag_embed(self_, offset, dim1, dim2), 0); +} + +Tensor trace_decomp(const Tensor& tensor) { + TORCH_CHECK(tensor.dim() == 2, "trace: expected a matrix, but got tensor with dim ", tensor.dim()); + return tensor.diagonal().sum(); +} + +std::tuple> tril_batch_rule( + const Tensor& self, + std::optional self_bdim, + c10::SymInt diagonal = 0) { + TORCH_CHECK(self.dim() >= 2, "tril: The input tensor must have at least 2 dimensions."); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto result = at::tril_symint(self_, std::move(diagonal)); + return std::make_tuple(std::move(result), 0); +} + +std::tuple> triu_batch_rule( + const Tensor& self, + std::optional self_bdim, + c10::SymInt diagonal = 0) { + TORCH_CHECK(self.dim() >= 2, "triu: The input tensor must have at least 2 dimensions."); + auto self_ = moveBatchDimToFront(self, self_bdim); + auto result = at::triu_symint(self_, std::move(diagonal)); + return std::make_tuple(std::move(result), 0); +} + +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + VMAP_SUPPORT(flip, flip_batch_rule); + m.impl("trace", trace_decomp); + VMAP_SUPPORT(tril, tril_batch_rule); + VMAP_SUPPORT(triu, triu_batch_rule); + VMAP_SUPPORT(repeat, repeat_batch_rule); + VMAP_SUPPORT(_unsafe_view, _unsafe_view_batch_rule); + VMAP_SUPPORT(unsqueeze, unsqueeze_batch_rule); + VMAP_SUPPORT(unsqueeze_copy, unsqueeze_copy_batch_rule); + m.impl("resize_", resize__plumbing); + VMAP_SUPPORT2(select, int, select_batching_rule); + VMAP_SUPPORT(squeeze, squeeze_batch_rule); + VMAP_SUPPORT(squeeze_copy, squeeze_copy_batch_rule); + VMAP_SUPPORT2(squeeze, dim, squeeze_dim_batch_rule); + VMAP_SUPPORT2(squeeze_copy, dim, squeeze_copy_dim_batch_rule); + VMAP_SUPPORT2(squeeze, dims, squeeze_dims_batch_rule); + VMAP_SUPPORT2(squeeze_copy, dims, squeeze_copy_dims_batch_rule); + VMAP_SUPPORT(_reshape_alias, _reshape_alias_batch_rule); + VMAP_SUPPORT(roll, roll_batch_rule); + VMAP_SUPPORT(permute, permute_batching_rule); + VMAP_SUPPORT(permute_copy, permute_copy_batching_rule); + VMAP_SUPPORT(diagonal, diagonal_batching_rule); + VMAP_SUPPORT(diagonal_backward, diagonal_backward_batch_rule); + VMAP_SUPPORT(select_backward, select_backward_batch_rule); + VMAP_SUPPORT(slice_backward, slice_backward_batch_rule); + VMAP_SUPPORT2(unbind_copy, int, unbind_copy_batch_rule); + VMAP_SUPPORT(view, view_batching_rule); + VMAP_SUPPORT2(view, dtype, view_dtype_batch_rule); + VMAP_SUPPORT(view_copy, view_copy_batch_rule); + VMAP_SUPPORT(expand, SINGLE_ARG(expand_batch_rule)); + VMAP_SUPPORT(expand_copy, SINGLE_ARG(expand_batch_rule)); + VMAP_SUPPORT(unfold, unfold_batch_rule); + VMAP_SUPPORT2(slice, Tensor, slice_batch_rule); + VMAP_SUPPORT2(transpose, int, transpose_int_batch_rule); + VMAP_SUPPORT2(transpose_copy, int, transpose_copy_int_batch_rule); + m.impl("t", native::t); // CompositeExplicitAutograd, should not go in BatchRulesDecompositions.cpp + m.impl("t_", native::t_); // CompositeExplicitAutograd, should not go in BatchRulesDecompositions.cpp + VMAP_SUPPORT(t_copy, t_copy_batching_rule); + VMAP_SUPPORT(diag_embed, diag_embed_batch_rule); + VMAP_SUPPORT(narrow_copy, narrow_copy_batch_rule); + VMAP_SUPPORT2(unsafe_split, Tensor, unsafe_split_batch_rule); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedFallback.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedFallback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ae139f117fb5fa7ea55649e9f485dc432986917 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedFallback.cpp @@ -0,0 +1,515 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +namespace at::functorch { + +static constinit std::atomic kVmapFallbackWarningEnabled{true}; + +bool isVmapFallbackWarningEnabled() { + return kVmapFallbackWarningEnabled.load(std::memory_order_relaxed); +} + +void setVmapFallbackWarningEnabled(bool enabled) { + kVmapFallbackWarningEnabled.store(enabled, std::memory_order_relaxed); +} + +static constinit std::atomic kVmapFallbackEnabled{true}; + +bool isVmapFallbackEnabled() { + return kVmapFallbackEnabled.load(std::memory_order_relaxed); +} + +void setVmapFallbackEnabled(bool enabled) { + kVmapFallbackEnabled.store(enabled, std::memory_order_relaxed); +} + +// Given a linear index, return the actual index. +// Example: Given linear_idx = 3, sizes = [5, 2], we would return [1, 0] +static at::SmallVector +computeIndex(int64_t linear_idx, IntArrayRef sizes) { + at::SmallVector result; + result.reserve(sizes.size()); + for (auto it = sizes.rbegin(); it != sizes.rend(); it++) { + auto remainder = linear_idx % *it; + result.push_back(remainder); + linear_idx -= remainder; + linear_idx /= *it; + } + std::reverse(std::begin(result), std::end(result)); + return result; +} + +static bool areAllReturnsTensors(const at::FunctionSchema& schema) { + return std::all_of( + schema.returns().begin(), + schema.returns().end(), + [] (const Argument& arg) { return arg.type() == TensorType::get(); }); +} + +static bool areAnyArgumentsTensorList(const at::FunctionSchema& schema) { + return std::any_of( + schema.arguments().begin(), + schema.arguments().end(), + [] (const Argument& arg) { + return arg.type()->isSubtypeOf(ListType::ofTensors()) || + arg.type()->isSubtypeOf(ListType::ofOptionalTensors()); + }); +} + +static void warnFallback(const c10::FunctionSchema& schema, bool is_inplace, bool is_nested=false) { + TORCH_CHECK(isVmapFallbackEnabled(), + schema.operator_name(), " hit the vmap fallback which is currently disabled"); + if (!isVmapFallbackWarningEnabled()) { + return; + } + TORCH_WARN("There is a performance drop because we have not yet implemented ", + "the ", (is_nested ? "nested " : "") , "batching rule for ", + schema.operator_name(), ". Please file us an issue on GitHub so that ", + "we can prioritize its implementation."); +} + +// The general flow of the algorithm is as follows. +// - First, we figure out which arguments are BatchedTensors and save them +// to a vector. We also store a vector of which index of the arguments list +// each BatchedTensor appears in. This will be useful for bookkeeping later. +// - Next, we apply the MultiBatchVmapTransform to all of the BatchedTensors. +// This returns a vector of VmapPhysicalView that hold tensors that contain +// all of the collective batch dimensions at the front of the tensors. +// - Then, we attempt to call `op` once per slice of the inputs. To do this, +// we repeatedly we slice the input arguments (if they are BatchedTensors), +// put the sliced (or a not-sliced) version of the input onto the stack, invoke +// the operator, and then pop the results off the stack. +static void batchedTensorInplaceForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + warnFallback(schema, /*in_place*/true); + + const auto num_arguments = schema.arguments().size(); + const auto arguments = torch::jit::last(stack, num_arguments); + const auto arguments_begin = stack->size() - num_arguments; + + // `self` is the Tensor being modified in-place + Tensor self = arguments[0].toTensor(); + const auto* self_impl = maybeGetBatchedImpl(self); + std::bitset self_vmap_levels; + if (self_impl) { + self_vmap_levels = createVmapLevelsBitset(self_impl->level()); + } + + // Figure out which arguments are BatchedTensor. Save them to a vector. + // For each BatchedTensor, also record what position of `arguments` they came from. + at::SmallVector batched_tensor_inputs; + VmapDimVector batched_tensor_inputs_position; + for (const auto idx : c10::irange(0, arguments.size())) { + const auto& ivalue = arguments[idx]; + if (!ivalue.isTensor()) { + continue; + } + const auto& tensor = ivalue.toTensor(); + if (!tensor.defined()) { + continue; + } + const auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + continue; + } + + // NOTE: [vmap-incompatible in-place operations] + // In-place operations on `self` are not possible if there exists some vmap + // level `l` such that `self` is not being vmapped on that level but another + // argument is. For example, let B0 be a batch dim inside vmap and consider + // vmap(Tensor.add_, in_dims=(None, 0))(torch.ones(3), torch.ones(B0, 3)) + // - self is torch.ones(3) and does not participate in this vmap + // - other is BatchedTensor(torch.ones(B0, 3)) + // There's no way to do self.add_(other) because `other` has more elements + // elements than `self` due to being vmapped over. + // + // In the vmap fallback, we should error out when we detect this. + auto other_vmap_levels = createVmapLevelsBitset(batched->level()); + if (self_vmap_levels != (self_vmap_levels | other_vmap_levels)) { + // Find one vmap level to complain about + auto additional_bdims = (self_vmap_levels | other_vmap_levels) ^ self_vmap_levels; + [[maybe_unused]] auto offending_level = llvm::findLastSet(additional_bdims.to_ulong()); + // The following prints out "vmap: aten::add_(tensor, ...) is not possible", + // but it would be better to print out "tensor.add_(...) is not possible". + // Afaict there's no official way to get the add_ and there is no way to + // tell if an operator has method or function variants. + TORCH_CHECK(false, + "vmap: ", schema.name(), "(self, *extra_args) is not possible because ", + "there exists a Tensor `other` in extra_args that has more elements ", + "than `self`. This happened due to `other` being vmapped over but ", + "`self` not being vmapped over at level ", offending_level, ". ", + "Please try to use out-of-place operators instead of ", schema.name(), ". ", + "If said operator is being called inside the PyTorch framework, ", + "please file a bug report instead."); + } + batched_tensor_inputs.push_back(tensor); + batched_tensor_inputs_position.push_back(static_cast(idx)); + } + TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty()); + + // MultiBatchVmapTransform the BatchedTensor arguments. This returns + // VmapPhysicalViews that contain all of the batch dimensions. + const auto input_physical_views = MultiBatchVmapTransform::logicalToPhysical( + batched_tensor_inputs); + + // Compute the total number of batches + auto num_batch_dims = input_physical_views.front().numBatchDims(); + auto first_physical_view_sizes = input_physical_views.front().tensor().sizes(); + auto batch_sizes = ArrayRef( + first_physical_view_sizes.begin(), first_physical_view_sizes.begin() + num_batch_dims); + const auto num_batches = c10::multiply_integers(batch_sizes); + // Without a shape-checking API, we're unable to compute the correct shape of + // the output so we just error out. + TORCH_CHECK(num_batches > 0, + "Batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support vmap over dims of size 0."); + + // Strategy: For each batch, we are going to push slices (where applicable) + // of the arguments onto `stack`, and call `op`. + for (int64_t linear_idx = 0; linear_idx < num_batches; ++linear_idx) { + auto index = computeIndex(linear_idx, batch_sizes); + auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin(); + auto input_physical_views_iter = input_physical_views.begin(); + for (const auto arg_idx : c10::irange(0, num_arguments)) { + // We assume that torch::jit::Stack is backed by vector for + // simplicity. When that is not the case, this code should be updated. + const auto& argument = (*stack)[arguments_begin + arg_idx]; + if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end() + || static_cast(arg_idx) != *batched_tensor_inputs_pos_iter) { + // argument isn't a BatchedTensor + torch::jit::push(stack, argument); + continue; + } + // argument is a BatchedTensor + TORCH_INTERNAL_ASSERT(input_physical_views_iter != input_physical_views.end()); + const auto& physical_view_for_argument = *input_physical_views_iter; + auto thing = physical_view_for_argument.tensor().index(index); + torch::jit::push(stack, thing); + batched_tensor_inputs_pos_iter++; + input_physical_views_iter++; + } + + op.callBoxed(stack); + torch::jit::drop(stack, 1); + } + + // Return the tensor that was written to in-place + torch::jit::drop(stack, num_arguments); + torch::jit::push(stack, self); +} + +static Tensor safeStack(TensorList tensors) { + auto is_defined = [](const Tensor& t) { return t.defined(); }; + if (std::all_of(tensors.begin(), tensors.end(), is_defined)) { + return at::stack(tensors); + } + // NOTE [vmap through backward and undefined grad] + // While vmapping through backward functions (to compute batched grad), it + // is possible for the backward function to return an undefined grad for some + // grad_input for each example. In that case, we return an undefined grad. + // + // It is theoretically possible for *some* of the examples to produce an + // undefined grad (a kernel could peek at the gradient values and return an + // undefined tensor if it determines the gradient is full of zeros). We + // could handle this by treating the undefined grad as a zero-filled tensor + // of the correct shape while stacking the tensors together. However I expect + // this to happen very rarely (I have not been able to find an example in our + // codebase) so we just error out in this case. + if (std::none_of(tensors.begin(), tensors.end(), is_defined)) { + return Tensor(); + } + TORCH_CHECK(false, + "vmap: slow fallback received a mix of undefined and defined tensors ", + "as the result of an operation. This is not supported, please file us ", + "an issue on github."); +} + +// TODO: Consider rewriting the following to look like: +// https://gist.github.com/zou3519/7b7c6a4a258d580f62d1d969851be6b1 + +// The general flow of the algorithm is as follows. +// - First, we figure out which arguments are BatchedTensors and save them +// to a vector. We also store a vector of which index of the arguments list +// each BatchedTensor appears in. This will be useful for bookkeeping later. +// - Next, we apply the MultiBatchVmapTransform to all of the BatchedTensors. +// This returns a vector of VmapPhysicalView that hold tensors that contain +// all of the collective batch dimensions at the front of the tensors. +// - Then, we attempt to call `op` once per slice of the inputs. To do this, +// we repeatedly we slice the input arguments (if they are BatchedTensors), +// put the sliced (or a not-sliced) version of the input onto the stack, invoke +// the operator, and then pop the results off the stack. +// - Each result obtained from the previous step is a slice of the total result, +// so we stack those tensors together to form the final result. +void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + const auto num_arguments = schema.arguments().size(); + const auto arguments = torch::jit::last(stack, num_arguments); + + TORCH_CHECK(areAllReturnsTensors(schema) && !areAnyArgumentsTensorList(schema), + "Batching rule not implemented for ", schema.operator_name(), ". ", + "We could not generate a fallback."); + + if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + op.callBoxed(stack); + return; + } + + if (isInplaceOp(schema)) { + batchedTensorInplaceForLoopFallback(op, stack); + return; + } + TORCH_CHECK(!schema.is_mutable() && !schema.hasAnyAliasInfo(), + "Batching rule not implemented for ", schema.operator_name(), "; ", + "the fallback path doesn't work on out= or view ops."); + TORCH_CHECK(num_returns >= 1, + "Batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support operations with no returns."); + warnFallback(schema, /*in_place*/false); + + const auto arguments_begin = stack->size() - num_arguments; + + // Figure out which arguments are BatchedTensor. Save them to a vector. + // For each BatchedTensor, also record what position of `arguments` they came from. + at::SmallVector batched_tensor_inputs; + VmapDimVector batched_tensor_inputs_position; + for (const auto idx : c10::irange(0, arguments.size())) { + const auto& ivalue = arguments[idx]; + if (!ivalue.isTensor()) { + continue; + } + const auto& tensor = ivalue.toTensor(); + if (!tensor.defined()) { + continue; + } + const auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + continue; + } + batched_tensor_inputs.push_back(tensor); + batched_tensor_inputs_position.push_back(static_cast(idx)); + } + TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty()); + + // MultiBatchVmapTransform the BatchedTensor arguments. This returns + // VmapPhysicalViews that contain all of the batch dimensions. + const auto input_physical_views = MultiBatchVmapTransform::logicalToPhysical( + batched_tensor_inputs); + + // Compute the total number of batches + auto num_batch_dims = input_physical_views.front().numBatchDims(); + auto some_sizes = input_physical_views.front().tensor().sizes(); + auto batch_sizes = ArrayRef(some_sizes.begin(), some_sizes.begin() + num_batch_dims); + const auto num_batches = c10::multiply_integers(batch_sizes); + // Without a shape-checking API, we're unable to compute the correct shape of + // the output so we just error out. + TORCH_CHECK(num_batches > 0, + "Batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support vmap over dims of size 0."); + + // Strategy: For each batch, we are going to push slices (where applicable) + // of the arguments onto `stack`, call `op`, and store the result in + // `output_shards`. + // + // NOTE: [Output shards layout] + // Assume that the operator has three outputs: a, b, c. + // The layout of output_shards is as follows: + // [ a0, a1, a2, a3, b0, b1, b2, b3, c0, c1, c2, c3] + // This is so that we can call at::stack([a0...a3]), at::stack([b0...b3]) + // more easily in the next step. + std::vector output_shards(num_batches * num_returns); + + for (int64_t linear_idx = 0; linear_idx < num_batches; ++linear_idx) { + auto index = computeIndex(linear_idx, batch_sizes); + auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin(); + auto input_physical_views_iter = input_physical_views.begin(); + for (const auto arg_idx : c10::irange(0, num_arguments)) { + // We assume that torch::jit::Stack is backed by vector for + // simplicity. When that is not the case, this code should be updated. + const auto& argument = (*stack)[arguments_begin + arg_idx]; + if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end() + || static_cast(arg_idx) != *batched_tensor_inputs_pos_iter) { + // argument isn't a BatchedTensor + torch::jit::push(stack, argument); + continue; + } + // argument is a BatchedTensor + TORCH_INTERNAL_ASSERT(input_physical_views_iter != input_physical_views.end()); + const auto& physical_view_for_argument = *input_physical_views_iter; + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + torch::jit::push(stack, physical_view_for_argument.tensor().index(index)); + batched_tensor_inputs_pos_iter++; + input_physical_views_iter++; + } + + // std::cout << "[Fallback]: "; + // at::dump_tensor((*stack)[stack->size() - 1].toTensor()); + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + op.callBoxed(stack); + + // Store the result into `output_shards`. See NOTE: [Output shards layout] + // to learn about the details of how we store the shards. + const auto returns = torch::jit::last(stack, num_returns); + for (const auto return_idx : c10::irange(0, returns.size())) { + output_shards[num_batches * return_idx + linear_idx] = returns[return_idx].toTensor(); + } + torch::jit::drop(stack, num_returns); + } + + // For each output Tensor, stack the shards of the tensor together to form a return + torch::jit::drop(stack, num_arguments); + auto output_shards_chunks = MatrixRef(output_shards, num_batches); + for (const auto return_idx : c10::irange(0, num_returns)) { + auto shards = output_shards_chunks[return_idx]; + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto flat_output = safeStack(shards); + // See NOTE [vmap through backward and undefined grad] + if (!flat_output.defined()) { + torch::jit::push(stack, flat_output); + continue; + } + VmapDimVector output_sizes(batch_sizes); + output_sizes.insert( + output_sizes.end(), + flat_output.sizes().begin() + 1, + flat_output.sizes().end()); + torch::jit::push( + stack, + input_physical_views.front().getPhysicalToLogicalMap().apply(flat_output.view(output_sizes))); + } +} + +void batchedNestedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + const auto& schema = op.schema(); + const auto num_returns = schema.returns().size(); + const auto num_arguments = schema.arguments().size(); + const auto arguments = torch::jit::last(stack, num_arguments); + + TORCH_CHECK(areAllReturnsTensors(schema) && !areAnyArgumentsTensorList(schema), + "Nested batching rule not implemented for ", schema.operator_name(), ". ", + "We could not generate a fallback."); + + if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + c10::impl::ExcludeDispatchKeyGuard nt_guard(DispatchKey::BatchedNestedTensor); + op.callBoxed(stack); + return; + } + + TORCH_INTERNAL_ASSERT(!isInplaceOp(schema), "vmap fallback not supported for in-place ops on nested tensors"); + + TORCH_CHECK(!schema.is_mutable() && !schema.hasAnyAliasInfo(), + "Nested batching rule not implemented for ", schema.operator_name(), "; ", + "the fallback path doesn't work on out= or view ops."); + TORCH_CHECK(num_returns >= 1, + "Nested batching rule not implemented for ", schema.operator_name(), ". ", + "The fallback path does not support operations with no returns."); + warnFallback(schema, /*in_place*/false, /*is_nested*/true); + + const auto arguments_begin = stack->size() - num_arguments; + + // Figure out which arguments are BatchedTensor. Save them to a vector. + // For each BatchedTensor, also record what position of `arguments` they came from. + at::SmallVector batched_tensor_inputs; + VmapDimVector batched_tensor_inputs_position; + for (const auto idx : c10::irange(0, arguments.size())) { + const auto& ivalue = arguments[idx]; + if (!ivalue.isTensor()) { + continue; + } + const auto& tensor = ivalue.toTensor(); + if (!tensor.defined()) { + continue; + } + const auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + continue; + } + batched_tensor_inputs.push_back(tensor); + batched_tensor_inputs_position.push_back(static_cast(idx)); + } + TORCH_INTERNAL_ASSERT(!batched_tensor_inputs.empty()); + + std::vector> unbound; + for (auto const &batched_tensor_input: batched_tensor_inputs) { + auto *batched_impl = maybeGetBatchedImpl(batched_tensor_input); + TORCH_INTERNAL_ASSERT(batched_impl->value().is_nested() || batched_impl->bdim() == 0, + "Fallback not supported for mixed nested / non-nested arguments without bdim=0"); + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::BatchedNestedTensor); + auto this_unbound = batched_impl->value().unbind(); + if (!unbound.empty()) { + TORCH_INTERNAL_ASSERT(unbound.front().size() == this_unbound.size(), + "Fallback not supported for differently-sized nested arguments"); + } + unbound.push_back(this_unbound); + } + + const auto num_components = unbound.front().size(); + std::vector output_shards(num_components * num_returns); + for (const auto component_idx : c10::irange(0, num_components)) { + auto batched_idx = 0; + auto batched_tensor_inputs_pos_iter = batched_tensor_inputs_position.begin(); + for (const auto arg_idx : c10::irange(0, num_arguments)) { + // We assume that torch::jit::Stack is backed by vector for + // simplicity. When that is not the case, this code should be updated. + const auto& argument = (*stack)[arguments_begin + arg_idx]; + if (batched_tensor_inputs_pos_iter == batched_tensor_inputs_position.end() + || static_cast(arg_idx) != *batched_tensor_inputs_pos_iter) { + // argument isn't a BatchedTensor + torch::jit::push(stack, argument); + continue; + } + // argument is a BatchedTensor + torch::jit::push(stack, unbound[batched_idx][component_idx]); + ++batched_idx; + ++batched_tensor_inputs_pos_iter; + } + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::BatchedNestedTensor); + op.callBoxed(stack); + + // Store the result into `output_shards`. See NOTE: [Output shards layout] + // to learn about the details of how we store the shards. + const auto returns = torch::jit::last(stack, num_returns); + for (const auto return_idx : c10::irange(0, returns.size())) { + output_shards[num_components * return_idx + component_idx] = returns[return_idx].toTensor(); + } + torch::jit::drop(stack, num_returns); + } + + // For each output Tensor, stack the shards of the tensor together to form a nested return + // TODO: Determine when the output needs to be nested and when it can be non-nested? + torch::jit::drop(stack, num_arguments); + auto output_shards_chunks = MatrixRef(output_shards, num_components); + for (const auto return_idx : c10::irange(0, num_returns)) { + auto shards = output_shards_chunks[return_idx]; + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::BatchedNestedTensor); + auto out_nt = at::_nested_tensor_from_tensor_list(shards); + // NB: NTs only support batching over dim 0 + torch::jit::push(stack, makeBatched(out_nt, 0, maybeCurrentDynamicLayer()->layerId())); + } +} + +void vmapErrorFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, "Error: ", op.operator_name(), " requires special handling, and does not yet have a batching rule. Feel free to file a github issue!"); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedFallback.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedFallback.h new file mode 100644 index 0000000000000000000000000000000000000000..ab4fbc662aa3e0f28bc4e15432e56377a471a196 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedFallback.h @@ -0,0 +1,81 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once +#include +#include +#include + +namespace at::functorch { + +// This file contains code for the vmap fallback (also known as the +// BatchedTensor fallback or the Batched fallback). This code runs +// when an operation doesn't have a batching rule implemented. + +// If an operator doesn't have a batching rule implemented then we fallback +// to this implementation. The fallback doesn't work on out= variants or +// view operations; that is, it works for out-of-place operations and +// in-place non-view operations. +// +// For out-of-place operations, the fallback effectively takes all of the +// BatchedTensors in `stack`, slices them, and runs `op` on all of the +// corresponding slices to produce slices of the outputs. The output slices +// then get `torch.stack`ed to create the +// final returns. +// +// The performance of the fallback is not very good because it introduces an +// extra copy from stacking the sliced outputs. Because of this, we prefer to +// write batching rules for operators whenever possible. +void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack); +void batchedNestedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack); + +void vmapErrorFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack); + +// The vmap fallback emits a warning by default, but it may be disabled if +// the user finds it to be too annoying. +TORCH_API bool isVmapFallbackWarningEnabled(); +TORCH_API void setVmapFallbackWarningEnabled(bool enabled); + +// Used for testing. The vmap fallback is enabled by default. When it is disabled, +// it raises an error. +TORCH_API bool isVmapFallbackEnabled(); +TORCH_API void setVmapFallbackEnabled(bool enabled); + +template A vector_to_result(const std::vector& buffer) { + return buffer[0].to(); +} +template std::tuple vector_to_result(const std::vector& buffer) { + return std::make_tuple(buffer[0].to(), buffer[1].to()); +} +template std::tuple vector_to_result(const std::vector& buffer) { + return std::make_tuple(buffer[0].to(), buffer[1].to(), buffer[2].to()); +} + +// slow_fallback is a way to call the vmap fallback inside some boxed kernel. +// There is probably some better way to metaprogram this. +template +Ret slow_fallback(const c10::OperatorHandle& op, ArrayRef args) { + std::vector stack(args.begin(), args.end()); + batchedTensorForLoopFallback(op, &stack); + return vector_to_result(stack); +} + +template +std::tuple slow_fallback(const c10::OperatorHandle& op, ArrayRef args) { + std::vector stack(args.begin(), args.end()); + batchedTensorForLoopFallback(op, &stack); + return vector_to_result(stack); +} + +template +std::tuple slow_fallback(const c10::OperatorHandle& op, ArrayRef args) { + std::vector stack(args.begin(), args.end()); + batchedTensorForLoopFallback(op, &stack); + return vector_to_result(stack); +} + + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedTensorImpl.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedTensorImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa1ac0fe96a6292b1a6bc255534667fd92119299 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedTensorImpl.cpp @@ -0,0 +1,186 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. +#include + +#include +#include + +#include + +namespace at::functorch { + +BatchedTensorImpl::BatchedTensorImpl(DispatchKeySet key_set, Tensor value, int64_t bdim, int64_t level) + : TensorImpl( + key_set.add( + value.is_nested() ? DispatchKey::BatchedNestedTensor : DispatchKey::FuncTorchBatched), + value.dtype(), + value.device() + ) + , value_(std::move(value)) + , level_(level) + , bdim_(bdim) +{ + TORCH_INTERNAL_ASSERT(value_.defined()); + if (value_.is_nested() || value_.key_set().has(DispatchKey::BatchedNestedTensor)) { + TORCH_CHECK(bdim_ == 0, + "Nested tensors can only be vmapped over dim=0, but got dim=", bdim_); + TORCH_CHECK(level_ == 1, + "Only one level of vmap is supported when vmapping over nested tensors"); + } + set_storage_access_should_throw(); + set_custom_sizes_strides( + value_.is_nested() ? SizesStridesPolicy::CustomSizes : SizesStridesPolicy::CustomStrides); + checkInvariants(); + refreshTensorMetadata(); +} + +void BatchedTensorImpl::refreshTensorMetadata() { + const auto public_dims = value_.dim() - 1; + if (value_.is_nested()) { + sizes_and_strides_.resize(public_dims); + storage_offset_= value_.storage_offset(); + refresh_numel(); + refresh_contiguous(); + } else { + c10::SymDimVector new_sizes; + c10::SymDimVector new_strides; + new_sizes.reserve(public_dims); + new_strides.reserve(public_dims); + + // update size, strides and storage_offset + // for tensor with symbolic size and strides + const auto value_sizes = value_.sym_sizes(); + const auto value_strides = value_.sym_strides(); + + for (const auto dim : c10::irange(0, public_dims)) { + auto actual_dim = actualDim(dim, /*wrap_dim=*/false); + new_sizes.push_back(value_sizes.at(actual_dim)); + new_strides.push_back(value_strides.at(actual_dim)); + } + + // `set_sizes_and_strides` takes care of calling `refresh_numel` and + // `refresh_contiguous` + set_sizes_and_strides(new_sizes, new_strides, value_.sym_storage_offset()); + } +} + +int64_t BatchedTensorImpl::actualDim(int64_t dim, bool wrap_dim) const { + if (wrap_dim) { + const auto ndim = sizes_and_strides_.size(); + dim = maybe_wrap_dim(dim, static_cast(ndim)); + } + if (bdim_ <= dim) { + return dim + 1; + } else { + return dim; + } +} + +void BatchedTensorImpl::checkInvariants() const { + TORCH_INTERNAL_ASSERT(level_ > -1); +} + +int64_t BatchedTensorImpl::size_custom(int64_t d) const { + if (!value_.is_nested()) { + d = maybe_wrap_dim(d, dim(), /*wrap_scalar=*/false); + return sizes_default()[d]; + } + // TODO: Error messages will mention the actualDim, which could be confusing; fix this + auto actual_dim = actualDim(d, /*wrap_dim=*/ true); + return value_.size(actual_dim); +} + +c10::SymInt BatchedTensorImpl::sym_size_custom(int64_t d) const { + if (!value_.is_nested()) { + d = maybe_wrap_dim(d, dim(), /*wrap_scalar=*/false); + return sym_sizes_default()[d]; + } + // TODO: Error messages will mention the actualDim, which could be confusing; fix this + auto actual_dim = actualDim(d, /*wrap_dim=*/ true); + return value_.sym_size(actual_dim); +} + +IntArrayRef BatchedTensorImpl::sizes_custom() const { + TORCH_CHECK(!value_.is_nested(), "sizes() is not supported for batched nested tensors"); + return sizes_default(); +} + +SymIntArrayRef BatchedTensorImpl::sym_sizes_custom() const { + TORCH_CHECK(!value_.is_nested(), "sizes() is not supported for batched nested tensors"); + return sym_sizes_default(); +} + +// The following are publicly exposed as methods of Tensor + +IntArrayRef BatchedTensorImpl::strides_custom() const { + return strides_default(); +} + +SymIntArrayRef BatchedTensorImpl::sym_strides_custom() const { + return sym_strides_default(); +} + + +// TODO: implement proper contiguity on batched tensor, then put +// sizes_strides_policy back to Default +c10::SymBool BatchedTensorImpl::sym_is_contiguous_custom(at::MemoryFormat memory_format) const { + TORCH_CHECK(memory_format == MemoryFormat::Contiguous, + "NYI: querying is_contiguous inside of vmap for memory_format ", + "other than torch.contiguous_format"); + return is_contiguous_default(memory_format); +} + +// The following are some internal inherited methods that we do not support. +// They should never get called. +void BatchedTensorImpl::set_size(int64_t dim, int64_t new_size) { + TORCH_INTERNAL_ASSERT(false, "Can't set_size for BatchedTensorImpl"); +} +void BatchedTensorImpl::set_stride(int64_t dim, int64_t new_stride) { + TORCH_INTERNAL_ASSERT(false, "Can't set_stride for BatchedTensorImpl"); +} +#ifdef DEBUG +bool BatchedTensorImpl::has_storage() const { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!storage_, "BatchedTensorImpl assumes that storage_ is never set"); + return false; +} +#endif + +const char* BatchedTensorImpl::tensorimpl_type_name() const { + return "BatchedTensorImpl"; +} + +c10::intrusive_ptr BatchedTensorImpl::shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const { + TORCH_CHECK(false, "accessing `data` under vmap transform is not allowed"); +} + +c10::intrusive_ptr BatchedTensorImpl::shallow_copy_and_detach( + // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const { + TORCH_CHECK(false, "accessing `data` under vmap transform is not allowed"); +} + +void BatchedTensorImpl::shallow_copy_from(const c10::intrusive_ptr& impl) { + TORCH_CHECK(false, "mutating directly with `.data` under vmap transform is not allowed."); +} + +Tensor makeBatched(Tensor tensor, int64_t bdim, int64_t level) { + DispatchKeySet key_set = getKeysToPropagateToWrapper(tensor); + auto* batched = maybeGetBatchedImpl(tensor); + if (batched) { + auto batched_level = batched->level(); + TORCH_INTERNAL_ASSERT(level > batched_level, " batched_level: ", batched_level, " level: ", level); + } + return at::detail::make_tensor(key_set, std::move(tensor), bdim, level); +} + +Tensor addBatchDim(Tensor tensor, int64_t dim, int64_t level) { + return makeBatched(std::move(tensor), dim, level); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedTensorImpl.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedTensorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..e6a916a607e3f1eeb45041669c39a32317894755 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchedTensorImpl.h @@ -0,0 +1,177 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include + +#include +#include +#include + +namespace at::functorch { + +using Tensor = at::Tensor; + +// We assume this in a few other places in the codebase, +// but there isn't a centralized definition. +constexpr int64_t kVmapMaxTensorDims = 64; + +// The valid vmap levels range from [0, 64). This effectively means that we +// support a maximum of 64 nested vmaps. +constexpr int64_t kVmapNumLevels = 64; + +// Store this number of elements of BatchDims on the stack. Most people will +// probably use <= 5 nested vmaps, but adjust this number as necessary. +constexpr int64_t kBatchDimsStackSize = 5; + +// A BatchedTensorImpl holds an underlying Tensor and a single batch dim +// NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a +// BatchedTensorImpl. +// +// The batch dimensions are treated as being "private"; they are not user-visible. +// For example, in the following Tensor, +// bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0) +// dimension 0 is batch dimension. +// +// bt.sizes() returns (5, 7); bt.sum(0) performs a reduction over the (public) +// dim 0, which is equivalent to dim 3 in the underlying ones(2, 3, 5, 7) tensor. +struct TORCH_API BatchedTensorImpl : public c10::TensorImpl { + explicit BatchedTensorImpl(at::DispatchKeySet key_set, Tensor value, int64_t dim, int64_t level); + + // Returns batch dimension of this tensor + int64_t bdim() const { return bdim_; } + + // Returns batch dimension of this tensor + int64_t level() const { return level_; } + + // BatchedTensorImpl wraps a Tensor + const Tensor& value() const { return value_; } + + // Given a public dimension index, return the dimension index in the underlying + // value() tensor. + // For example, if we have + // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0) + // bt.actualDim(0) -> 1 + // bt.actualDim(1) -> 2 + // bt.actualDim(2) -> 3 + // bt.actualDim(3) -> Error + int64_t actualDim(int64_t dim, bool wrap_dim = true) const; + + IntArrayRef sizes_custom() const override; + SymIntArrayRef sym_sizes_custom() const override; + int64_t size_custom(int64_t d) const override; + c10::SymInt sym_size_custom(int64_t d) const override; + // We have to override this because we opted into CustomStrides + IntArrayRef strides_custom() const override; + SymIntArrayRef sym_strides_custom() const override; + // Override a bunch of methods inherited from TensorImpl to return error messages. + c10::SymBool sym_is_contiguous_custom(at::MemoryFormat memory_format) const override; + void set_size(int64_t dim, int64_t new_size) override; + void set_stride(int64_t dim, int64_t new_stride) override; + c10::intrusive_ptr shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const override; + c10::intrusive_ptr shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const override; + void shallow_copy_from(const c10::intrusive_ptr& impl) override; +#ifdef DEBUG + bool has_storage() const override; +#endif + + void refreshTensorMetadata(); + + // Used in torchdim. torchdim uses non-lexical BatchedTensor; the way it + // accomplishes this is a hack where it is able to modify the levels of + // BatchedTensor to match the level of the current vmap transform. + void _unsafe_set_level(int64_t level) { + level_ = level; + } + + // Used in batching rule for in-place view operations that can change + // the index of the bdim (think squeeze_, unsqueeze_) + void unsafe_set_bdim(int64_t bdim) { + // NB: you MUST call refreshTensorMetadata after doing this. + bdim_ = bdim; + } + private: + // see NOTE: [BatchedTensorImpl levels invariant] + void checkInvariants() const; + const char* tensorimpl_type_name() const override; + + Tensor value_; + + int64_t level_; + int64_t bdim_; +}; + +// NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a +// BatchedTensorImpl. +inline bool isBatchedTensor(const Tensor& tensor) { + return tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::FuncTorchBatched) || + tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::BatchedNestedTensor); +} + +// It is unsafe to call this on a Tensor that is not backed by a +// BatchedTensorImpl. Please use `maybeGetBatchedImpl` whenever possible. +inline BatchedTensorImpl* unsafeGetBatchedImpl(const Tensor& tensor) { + return static_cast(tensor.unsafeGetTensorImpl()); +} + +inline BatchedTensorImpl* maybeGetBatchedImpl(const Tensor& tensor) { + if (!isBatchedTensor(tensor)) { + return nullptr; + } + return unsafeGetBatchedImpl(tensor); +} + +// Returns a bitset. If bit i is set, then that means dim i is a batchdim. +inline std::bitset createBatchDimBitset(int64_t dim) { + std::bitset is_bdim; + is_bdim.set(dim); + return is_bdim; +} + +// Creates a bitset for the given level +inline std::bitset createVmapLevelsBitset(int64_t level) { + std::bitset result; + result.set(level); + return result; +} + +// Use this to construct a BatchedTensor from a regular Tensor +TORCH_API Tensor makeBatched(Tensor tensor, int64_t dim, int64_t level); + +// Adds a batch dim to `tensor`, returning a BatchedTensor +TORCH_API Tensor addBatchDim(Tensor tensor, int64_t dim, int64_t level); + +// Certain dispatch keys must be propagated to the BatchedTensor (or, in general, +// any wrapper Tensor subclasses). This is because there are methods on Tensor +// that skip dispatch and check for the presence of a dispatch key (e.g. is_cpu()). +// TODO: should probably contain more (or all?) backend keys +constexpr DispatchKeySet kKeysToPropagateToWrapper({ + DispatchKey::Negative, + DispatchKey::Conjugate, + DispatchKey::XLA, + DispatchKey::XPU, + DispatchKey::HPU, + DispatchKey::CUDA, + DispatchKey::CPU, + DispatchKey::MPS, + DispatchKey::PrivateUse1, + DispatchKey::SparseCPU, + DispatchKey::SparseCUDA, + DispatchKey::SparseCsrCPU, + DispatchKey::SparseCsrCUDA, +}); + +inline DispatchKeySet getKeysToPropagateToWrapper(const Tensor& tensor, DispatchKeySet to_propagate=kKeysToPropagateToWrapper) { + auto key_set = tensor.unsafeGetTensorImpl()->key_set(); + return key_set & kKeysToPropagateToWrapper; +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchingMetaprogramming.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchingMetaprogramming.h new file mode 100644 index 0000000000000000000000000000000000000000..9f58df839d442afb9f979841770edc8f80427582 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/BatchingMetaprogramming.h @@ -0,0 +1,126 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once +#include +#include + +// This file contains template metaprogramming things that are used for our +// batching rules. +// +// See NOTE: [vmap plumbing] for more details on why this is necessary. +// The plumbing has a bunch of metaprogramming hacks for determining the signature +// of a batching rule from the signature of the operator, many of which use the +// helper functions in this file. + +namespace at::functorch { + +// Metaprogramming things +template using typelist = c10::guts::typelist::typelist; +template using head_t = c10::guts::typelist::head_t; +template using concat_t = c10::guts::typelist::concat_t; +template class debug_t; + +// tail operation +template +struct tail final { + static_assert(c10::guts::false_t::value, + "In typelist::tail, the T argument must be typelist<...>."); +}; +template +struct tail> final { + using type = typelist; +}; +template using tail_t = typename tail::type; + +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext { + using type = Next; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, std::optional, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext&, std::optional, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext&, std::optional, Next, Tail> { + using type = Tail; +}; +template +struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext, std::optional, Next, Tail> { + using type = Tail; +}; +template struct RemoveBatchDimAfterTensor { + using first = head_t; + using next = tail_t; + using second = head_t; + using tail = tail_t; + + using type = concat_t< + typelist, + typename RemoveBatchDimAfterTensor< + typename IfFirstIsTensorAndSecondisBatchDimThenTailElseNext::type + >::type + >; +}; +template struct RemoveBatchDimAfterTensor> { + using type = typelist; +}; +template <> struct RemoveBatchDimAfterTensor> { + using type = typelist<>; +}; +template using remove_batch_dim_after_tensor_t = typename RemoveBatchDimAfterTensor::type; + +template struct UnpackSingleItemTuple { + using type = T; +}; +template struct UnpackSingleItemTuple> { + using type = T; +}; +template using unpack_single_item_tuple_t = typename UnpackSingleItemTuple::type; + +template struct BuildFunctionHelper; +template struct BuildFunctionHelper> { + using type = Return(Args...); +}; +template +struct BuildFunction { + using type = typename BuildFunctionHelper>::type; +}; +template using build_function_t = typename BuildFunction::type; + + +template struct ToOperatorType { + using batch_rule_return_type = typename c10::guts::function_traits::return_type; + using batch_rule_parameter_types = typename c10::guts::function_traits::parameter_types; + + using operator_parameter_types = remove_batch_dim_after_tensor_t; + using operator_return_type = + unpack_single_item_tuple_t< + c10::guts::typelist::to_tuple_t< + remove_batch_dim_after_tensor_t< + c10::guts::typelist::from_tuple_t>>>; + + using type = build_function_t; +}; +template using to_operator_t = typename ToOperatorType::type; + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/DynamicLayer.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/DynamicLayer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6af7f76189ed31d43f4c0c7e7856de2566971dc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/DynamicLayer.cpp @@ -0,0 +1,495 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace at::functorch { + +void setDynamicLayerFrontBackKeysIncluded(bool included) { + c10::impl::tls_set_dispatch_key_included(DispatchKey::FuncTorchDynamicLayerFrontMode, included); + c10::impl::tls_set_dispatch_key_included(DispatchKey::FuncTorchDynamicLayerBackMode, included); +} + +DynamicLayer::DynamicLayer( + TransformType transform_type, + int64_t layerId, + std::optional batchSize, + std::optional randomness, + std::optional prev_grad_mode, + std::optional prev_fwd_grad_mode, + std::optional functionalize_add_back_views, + std::optional prev_inference_mode) +{ + if (transform_type == TransformType::Grad) { + TORCH_INTERNAL_ASSERT(prev_grad_mode.has_value()); + } + if (transform_type == TransformType::Jvp) { + TORCH_INTERNAL_ASSERT(prev_fwd_grad_mode.has_value()); + } + switch (transform_type) { + case TransformType::Vmap: + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + interpreter_ = Interpreter::Vmap(layerId, std::move(batchSize.value()), randomness.value()); + break; + case TransformType::Grad: + interpreter_ = Interpreter::Grad(layerId, prev_grad_mode.value(), prev_inference_mode.value_or(false)); + break; + case TransformType::Jvp: + interpreter_ = Interpreter::Jvp(layerId, prev_fwd_grad_mode.value(), prev_inference_mode.value_or(false)); + break; + case TransformType::Functionalize: + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + interpreter_ = Interpreter::Functionalize(layerId, functionalize_add_back_views.value()); + break; + default: + TORCH_INTERNAL_ASSERT(false); + } +} + +TransformType DynamicLayer::key() const { + return interpreter_.key(); +} + +int64_t DynamicLayer::layerId() const { + return interpreter_.level(); +} + +c10::SymInt DynamicLayer::batchSize() const { + return VmapInterpreterPtr(&interpreter_).batchSize(); +} + +RandomnessType DynamicLayer::randomness() const { + return VmapInterpreterPtr(&interpreter_).randomness(); +} + +// functorch stores some TLS. Inside the TLS is the stack of transforms. +// Unfortunately, since functorch isn't a part of libtorch, we have +// a level of indirection. FuncTorchTLSBase is the interface that lives in libtorch, +// while FuncTorchTLS implements all the methods and stores data. +// +// TODO: after functorch C++ code is moved into PyTorch, we can get rid of +// this layer of indirection. +class FuncTorchTLS : public FuncTorchTLSBase { + public: + FuncTorchTLS() = default; + + std::unique_ptr deepcopy() const override { + auto result = std::make_unique(); + result->dynamicLayerStack = dynamicLayerStack; + return result; + } + + int64_t checkSupportsSingleLevelAutogradFunction() const override { + TORCH_INTERNAL_ASSERT(dynamicLayerStack.empty() || getSingleLevelAutogradFunctionAllowed(), + "functorch functions (vmap, grad, vjp, etc.) incorrectly used with ", + "torch.autograd.function._SingleLevelFunction. ", + "This is not expected, please file a bug."); + return 0; + } + + void checkSupportsCppAutogradFunction() const override { + TORCH_CHECK( + dynamicLayerStack.empty(), + "cannot use C++ torch::autograd::Function with functorch transforms (vmap, grad, vjp, etc)"); + } + + void checkSupportsInplaceRequiresGrad() const override { + TORCH_CHECK(dynamicLayerStack.empty() || allow_inplace_requires_grad_, + "You are attempting to call Tensor.requires_grad_() (or perhaps using ", + "torch.autograd.functional.* APIs) inside of a function being transformed ", + "by a functorch transform. ", + "This is unsupported, please attempt to use the functorch transforms ", + "(e.g. grad, vjp, jacrev, jacfwd, hessian) or call requires_grad_() " + "outside of a function being transformed instead."); + } + void checkSupportsRetainGrad() const override { + TORCH_CHECK(dynamicLayerStack.empty(), + "You are attempting to call Tensor.retain_grad() ", + "inside of a function being transformed ", + "by a functorch transform. ", + "This is unsupported, please attempt to use the functorch transforms ", + "(e.g. grad, vjp, jacrev, jacfwd, hessian) or call retain_grad() " + "outside of a function being transformed instead."); + } + + std::vector dynamicLayerStack; + bool allow_inplace_requires_grad_ = false; + bool allow_single_level_autograd_function_ = false; +}; + +static FuncTorchTLS* getRawFunctorchTLS() { + auto& state = functorchTLSAccessor(); + if (state == nullptr) { + state = std::make_unique(); + } + // Raw pointer usage OK, `state` keeps the pointer alive + FuncTorchTLSBase* raw_state = state.get(); + FuncTorchTLS* result = static_cast(raw_state); + return result; +} + +void setInplaceRequiresGradAllowed(bool allowed) { + auto* functorch_tls = getRawFunctorchTLS(); + functorch_tls->allow_inplace_requires_grad_ = allowed; +} + +bool getInplaceRequiresGradAllowed() { + auto* functorch_tls = getRawFunctorchTLS(); + return functorch_tls->allow_inplace_requires_grad_; +} + +void setSingleLevelAutogradFunctionAllowed(bool allowed) { + auto* functorch_tls = getRawFunctorchTLS(); + functorch_tls->allow_single_level_autograd_function_ = allowed; +} + +bool getSingleLevelAutogradFunctionAllowed() { + auto* functorch_tls = getRawFunctorchTLS(); + return functorch_tls->allow_single_level_autograd_function_; +} + +static std::vector& dynamicLayerStackAccessor() { + return getRawFunctorchTLS()->dynamicLayerStack; +} + +const std::shared_ptr& getLifeHandleForLevel(int64_t level) { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + TORCH_INTERNAL_ASSERT( + (int64_t)dynamicLayerStack.size() >= level && level >= 1, + "If you're trying to construct a tensor with the current level (", + level, + ") then the interpreter for that level must be on the DynamicLayerStack "); + + auto& dynamic_layer = dynamicLayerStack[level - 1]; + return dynamic_layer.interpreter().is_alive_ptr(); +} + +std::optional maybeCurrentDynamicLayer() { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + if (dynamicLayerStack.empty()) { + return {}; + } + return dynamicLayerStack.back(); +} + +struct SaveLocalDispatchKeySet { + public: + SaveLocalDispatchKeySet() { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + TORCH_INTERNAL_ASSERT(!dynamicLayerStack.empty()); + auto& layer = dynamicLayerStack.back(); + auto tmp = c10::impl::tls_local_dispatch_key_set(); + layer.interpreter().saveLocalDispatchKeySet(tmp); + } + ~SaveLocalDispatchKeySet() { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + TORCH_INTERNAL_ASSERT(!dynamicLayerStack.empty()); + auto& layer = dynamicLayerStack.back(); + auto tmp = layer.interpreter().getSavedLocalDispatchKeySet(); + layer.interpreter().clearSavedLocalDispatchKeySet(); + c10::impl::_force_tls_local_dispatch_key_set(tmp); + } + SaveLocalDispatchKeySet(const SaveLocalDispatchKeySet&) = delete; + SaveLocalDispatchKeySet& operator=(const SaveLocalDispatchKeySet&) = delete; + SaveLocalDispatchKeySet(SaveLocalDispatchKeySet&&) = delete; + SaveLocalDispatchKeySet& operator=(SaveLocalDispatchKeySet&&) = delete; +}; + +const std::vector& getDynamicLayerStack() { + return dynamicLayerStackAccessor(); +} + +void setDynamicLayerStack(const std::vector& stack) { + dynamicLayerStackAccessor() = stack; +} + +DynamicLayer popDynamicLayer() { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + TORCH_INTERNAL_ASSERT(!dynamicLayerStack.empty()); + auto result = dynamicLayerStack.back(); + dynamicLayerStack.pop_back(); + + if (dynamicLayerStack.empty()) { + setDynamicLayerFrontBackKeysIncluded(false); + } + + return result; +} + +int64_t pushDynamicLayer(DynamicLayer&& dynamic_layer) { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + int64_t layerId = static_cast(1 + dynamicLayerStack.size()); + TORCH_INTERNAL_ASSERT(layerId == dynamic_layer.layerId()); + dynamicLayerStack.emplace_back(std::move(dynamic_layer)); + + if (layerId == 1) { + setDynamicLayerFrontBackKeysIncluded(true); + } + + return layerId; +} + +int64_t initAndPushDynamicLayer( + TransformType transform_type, + std::optional batch_size, + std::optional randomness, + std::optional prev_grad_mode, + std::optional prev_fwd_grad_mode, + std::optional functionalize_add_back_views, + std::optional prev_inference_mode) { + const auto& dynamicLayerStack = dynamicLayerStackAccessor(); + const int64_t layerId = static_cast(1 + dynamicLayerStack.size()); + DynamicLayer new_layer(transform_type, layerId, std::move(batch_size), randomness, prev_grad_mode, prev_fwd_grad_mode, functionalize_add_back_views, prev_inference_mode); + // NB: this function should be called while holding the GIL to avoid races + new_layer.interpreter().set_is_alive(true); + pushDynamicLayer(std::move(new_layer)); + + + if (transform_type == TransformType::Grad) { + TORCH_INTERNAL_ASSERT(prev_grad_mode.has_value()); + } + if (transform_type == TransformType::Jvp) { + TORCH_INTERNAL_ASSERT(prev_fwd_grad_mode.has_value()); + } + return layerId; +} + +DynamicLayer popDynamicLayerAndDeleteMetadata() { + auto result = popDynamicLayer(); + + // NB: this function should be called while holding the GIL to avoid races + result.interpreter().set_is_alive(false); + return result; +} + +bool isDeadTensorWrapper(const Tensor& tensor) { + auto* wrapped = maybeGetTensorWrapper(tensor); + if (!wrapped) { + return false; + } + return !wrapped->is_alive(); +} + +Tensor unwrapIfDead(const Tensor& tensor) { + auto* wrapped = maybeGetTensorWrapper(tensor); + if (!wrapped) { + return tensor; + } + if (wrapped->is_alive()) { + return tensor; + } + return wrapped->value(); +} + +void foreachTensorInplace(std::vector& args, int64_t begin, int64_t end, + std::function func) { + auto func_with_bool = [&](const Tensor& tensor, bool unused) { return func(tensor); }; + foreachTensorInplaceWithFlag(args, begin, end, std::bitset<64>(), func_with_bool); +} + +void foreachTensorInplaceWithFlag(std::vector& args, int64_t begin, int64_t end, + const std::bitset<64> use_flag_relative, const std::function& func){ + TORCH_INTERNAL_ASSERT(begin >= 0); + TORCH_INTERNAL_ASSERT(end >= 0); + TORCH_INTERNAL_ASSERT(begin <= end); + for (int64_t relative_idx = 0; relative_idx < end - begin; relative_idx++) { + const bool flag = use_flag_relative[relative_idx] == 1; + + const auto idx = relative_idx + begin; + auto ivalue = args[idx]; + // Tensor?[] translates to a c10::List so we need to peek inside List + if (ivalue.isList()) { + bool modified = false; + // TODO: might be more efficient if we scan first then not copy? Depends. + auto list = ivalue.toList().copy(); + for (const auto list_idx : c10::irange(0, list.size())) { + const auto& elt = list.get(list_idx); + if (elt.isTensor()) { + list.set(list_idx, func(elt.toTensor(), flag)); + modified = true; + } + } + if (modified) { + args[idx] = list; + } + continue; + } + if (ivalue.isTensorList()) { + auto list = ivalue.toTensorList(); + for (const auto list_idx : c10::irange(0, list.size())) { + list[list_idx] = func(list[list_idx], flag); + } + args[idx] = list; + } + TORCH_INTERNAL_ASSERT(!ivalue.isGenericDict(), "No operators can accept GenericDict"); + if (!ivalue.isTensor()) { + continue; + } + args[idx] = func(ivalue.toTensor(), flag); + // sanity checks + if (ivalue.toTensor().defined()) { + TORCH_INTERNAL_ASSERT(args[idx].toTensor().defined()); + } + } +} + +std::ostream& operator<< (std::ostream& os, const DynamicLayer& layer) { + os << layer.layerId() << ':' << layer.key(); + return os; +} +std::ostream& operator<< (std::ostream& os, const std::vector& dls) { + os << "DynamicLayerStack[ "; + for (const auto& layer : dls) { + os << layer << ' '; + } + os << ']'; + return os; +} + +bool isInplaceOp(const FunctionSchema& schema) { + if (!schema.is_mutable() || schema.returns().size() != 1) { + return false; + } + // Check that the first argument is being written to + const auto& first_arg_alias_info = schema.arguments().begin()->alias_info(); + if (!first_arg_alias_info || !first_arg_alias_info->isWrite()) { + return false; + } + // Check that none of the other args are being aliased + for (auto it = schema.arguments().begin() + 1; it != schema.arguments().end(); ++it) { + const auto& alias_info = it->alias_info(); + if (alias_info) { + return false; + } + } + // Check that the first tensor is being returned (i.e., output has a (a!)) + const auto& return_alias_info = schema.returns()[0].alias_info(); + return return_alias_info && return_alias_info->isWrite(); +} + +std::optional findAliasedOutput(const FunctionSchema& schema, const int64_t immutable_input_idx) { + for (size_t res_idx = 0; res_idx != schema.returns().size(); ++res_idx) { + if (schema.may_contain_alias(SchemaArgument(SchemaArgType::input, immutable_input_idx), SchemaArgument(SchemaArgType::output, res_idx))) { + return res_idx; // for everything currently in native_functions, each input aliases at most one output (tensor list counts as one output) + } + } + return std::nullopt; +} + +struct WithoutTop { + WithoutTop(); + WithoutTop(WithoutTop&& other) = delete; + WithoutTop(const WithoutTop&) = delete; + WithoutTop& operator=(const WithoutTop&) = delete; + WithoutTop& operator=(WithoutTop&&) = delete; + ~WithoutTop(); + DynamicLayer layer_; +}; + +WithoutTop::WithoutTop(): layer_(popDynamicLayer()) {} +WithoutTop::~WithoutTop() { + pushDynamicLayer(std::move(layer_)); +} + +// NOTE: [functorch front and back key fallbacks] +// +// Please read NOTE: [functorch interpreter stack] first for some context. +// The following doc also provides some visuals: +// https://docs.google.com/document/d/14qyaa3xIjmVxYiMLlIlQErunYgR_uR1WupsKMZlnGY4/edit +// +// functorch's "stack of transforms" is implemented as the following: +// - each transform is associated with one or more dispatch keys in the PyTorch +// dispatcher. For example, vmap -> {FuncTorchBatched, FuncTorchVmapMode}, +// Autograd -> {Autograd{Backend}, ADInplaceOrView} +// - Whenever a functorch transform is active, the FuncTorchDynamicLayer{Front, Back}Mode +// keys are added to the dispatcher's local dispatch key set. +// +// DynamicLayerFrontMode is responsible for: +// 1. selecting the transform that is at the top of the stack and grabbing its +// interpreter +// 2. Calling interpreter.process(), which does the following: +// 2a. enables/disables a bunch of dispatch keys, so that the only dispatch +// keys that are enabled are the ones that belong to the transform. +// 2b. redispatching +// +// Eventually, DynamicLayerBackMode captures the redispatch from the transforms. +// DynamicLayerBackMode is responsible for: +// - redirecting back to DynamicLayerFrontMode + +static void dynamicLayerFrontFallback( + const c10::OperatorHandle& op, + torch::jit::Stack* stack) { + auto& dynamicLayerStack = dynamicLayerStackAccessor(); + TORCH_INTERNAL_ASSERT(!dynamicLayerStack.empty()); + // Save the current LocalDispatchKeySet (to the current DynamicLayer). + // Upon exiting the current scope, that LocalDispatchKeySet gets restored. + // When the current DynamicLayer dispatches to the next (inner) DynamicLayer, + // it will also temporarily restore the saved LocalDispatchKeySet. + SaveLocalDispatchKeySet guard; + + // Unwrap escaped GradWrappers + auto num_args = op.schema().arguments().size(); + foreachTensorInplace(*stack, static_cast(stack->size() - num_args), static_cast(stack->size()), unwrapIfDead); + + auto& layer = dynamicLayerStack.back(); + layer.interpreter().process(op, stack); +} + +static c10::impl::ForceDispatchKeyGuard +restoreLocalDispatchKeySetRAII(const c10::impl::LocalDispatchKeySet& key_set) { + return c10::impl::ForceDispatchKeyGuard(key_set); +} + +// right now grad_special_case as a bool is sufficient because this is the only special case for grad. If we need to add +// more special cases, it's more scalable to add an enum to know which op we're looking at without looking at the schema +static void dynamicLayerBack(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case) { + auto restore_guard = restoreLocalDispatchKeySetRAII( + dynamicLayerStackAccessor().back().interpreter().getSavedLocalDispatchKeySet()); + WithoutTop guard; + + // WithoutTop stores the popped DynamicLayer object. + guard.layer_.interpreter().sendToNextInterpreter(op, stack, grad_special_case); +} + +// used for functions that have aliasing operations but should be treated like they're out of place (i.e. lift_fresh) +static void dynamicLayerBackGradSpecialCase(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + dynamicLayerBack(op, stack, true); +} + +static void dynamicLayerBackFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + dynamicLayerBack(op, stack, false); +} + +TORCH_LIBRARY_IMPL(_, FuncTorchDynamicLayerFrontMode, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&dynamicLayerFrontFallback>()); +} + +TORCH_LIBRARY_IMPL(_, FuncTorchDynamicLayerBackMode, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&dynamicLayerBackFallback>()); +} + + +#define SPECIAL_GRAD_CASE(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction<&dynamicLayerBackGradSpecialCase>()); + +TORCH_LIBRARY_IMPL(aten, FuncTorchDynamicLayerBackMode, m) { + // lift_fresh: it's must be freshly allocated and should be wrapped. User shouldn't have access to input version + // alias: this is needed for the CompositeImplicit instance norm (running_mean/var get set to be a wrapped value) + // It's not a user facing function, but is more prone to possible errors + SPECIAL_GRAD_CASE(lift_fresh); + SPECIAL_GRAD_CASE(alias); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/DynamicLayer.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/DynamicLayer.h new file mode 100644 index 0000000000000000000000000000000000000000..a908d74de791bcc7837e133ba4550f95d5c7d1e8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/DynamicLayer.h @@ -0,0 +1,126 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Forward declared +namespace c10 { struct AutogradMetaInterface; } + +namespace at::functorch { + +// This file contains the implementation of functorch's interpreter stack. +// See NOTE: [functorch interpreter stack] first before reading on. +// +// NB: the functorch interpreter stack is also referred to as: +// - the "dynamic layer stack" -- an older name for "interpreter" was +// "dynamic layer". +// - the "functorch mode stack". You can think of each functorch transform as a +// "mode" (in the same sense as torch_dispatch mode or torch_function mode), +// and functorch being an implementation of a "mode stack" where the modes +// may be arbitrary composed. + +// DynamicLayer is basically the same thing as an Interpreter. +// It represents a functorch transform and it holds an Interpreter, +// which contains metadata related to the transform and instructions on +// how to perform the transform. +// +// TODO: we can excise DynamicLayer in favor of Interpreter, +// But I am going to leave it for now as a compatibility shim to avoid +// needing to refactor a lot of callsites... +struct TORCH_API DynamicLayer { + explicit DynamicLayer( + TransformType transform_type, + int64_t layerId, + std::optional batchSize = std::nullopt, + std::optional randomness = std::nullopt, + std::optional prev_grad_mode = std::nullopt, + std::optional pre_fwd_grad_mode = std::nullopt, + std::optional functionalize_add_back_views = std::nullopt, + std::optional prev_inference_mode = std::nullopt); + + TransformType key() const; + int64_t layerId() const; + + const Interpreter& interpreter() const { return interpreter_; } + Interpreter& interpreter() { return interpreter_; } + + // Only valid for vmap + c10::SymInt batchSize() const; + RandomnessType randomness() const; + + private: + Interpreter interpreter_; +}; + +TORCH_API int64_t initAndPushDynamicLayer( + TransformType transform_type, + std::optional batch_size = std::nullopt, + std::optional randomness = std::nullopt, + std::optional prev_grad_mode = std::nullopt, + std::optional prev_fwd_grad_mode = std::nullopt, + std::optional functionalize_add_back_views = std::nullopt, + std::optional prev_inference_mode = std::nullopt); +TORCH_API DynamicLayer popDynamicLayerAndDeleteMetadata(); +TORCH_API std::optional maybeCurrentDynamicLayer(); +TORCH_API const std::vector& getDynamicLayerStack(); +TORCH_API void setDynamicLayerStack(const std::vector& stack); +TORCH_API void setDynamicLayerFrontBackKeysIncluded(bool included); + +// NOTE: [Life handles and lexically scoped transforms] +// functorch transforms are lexically scoped. +// Given a level, we store a "life handle" that is a boolean that tells us if the +// transform with that level is active or not. +// +// functorch's TensorWrapper (for grad transforms) stores a life handle. +// If a TensorWrapper escapes from the scope of the transform, then somehow +// it must know it escaped; it can tell by querying the life handle. +TORCH_API const std::shared_ptr& getLifeHandleForLevel(int64_t level); + +// Returns if an operator is in-place. An operator is inplace if: +// 1. The first argument is a Tensor and it is being written to +// 2. The first argument is being returned +// 3. No other arguments are aliased +// Here is an example of an in-place operator: +// add_(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) +TORCH_API bool isInplaceOp(const c10::FunctionSchema& schema); + +// Given the indices of unwrapped inputs and the schema, this returns the indices of any outputs that should remain unwrapped +TORCH_API std::optional findAliasedOutput(const FunctionSchema& schema, const int64_t immutable_input); + +TORCH_API Tensor unwrapIfDead(const Tensor& tensor); +TORCH_API bool isDeadTensorWrapper(const Tensor& tensor); + +// Pretty printers +TORCH_API std::ostream& operator<<(std::ostream& os, const DynamicLayer& layer); +TORCH_API std::ostream& operator<<(std::ostream& os, const std::vector& dynamicLayerStack); + +// While a functorch transform is active, torch.autograd.function._SingleLevelFunction +// is disabled by default. The following two APIs are APIs for enabling +// it. These are not user-facing APIs. We can delete this in the future, but +// it is useful for debugging when something goes wrong with the +// autograd.Function <> functorch interaction, which uses _SingleLevelFunction, +// because it leads to loud errors if something is incorrect. +TORCH_API void setSingleLevelAutogradFunctionAllowed(bool allowed); +TORCH_API bool getSingleLevelAutogradFunctionAllowed(); + +// While a functorch grad transform is active, Tensor.requires_grad_() gets +// disabled. These two functions are the mechanism to controlling that. +TORCH_API void setInplaceRequiresGradAllowed(bool allowed); +TORCH_API bool getInplaceRequiresGradAllowed(); + +TORCH_API DynamicLayer popDynamicLayer(); +TORCH_API int64_t pushDynamicLayer(DynamicLayer&& layer); + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/FunctionalizeInterpreter.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/FunctionalizeInterpreter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9970cd4b5ceb94e3b9f3c9895fa378d7b7f61343 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/FunctionalizeInterpreter.cpp @@ -0,0 +1,67 @@ +#include +#include +#include + +namespace at::functorch { + +static void sanityCheckNotFunctional(const c10::OperatorHandle& op, torch::jit::Stack* stack, size_t num_args) { + foreachTensorInplace(*stack, static_cast(stack->size() - num_args), static_cast(stack->size()), + [](const Tensor& tensor) { + TORCH_INTERNAL_ASSERT(!at::functionalization::impl::isFunctionalTensor(tensor)); + return tensor; + }); +} + +void FunctionalizeInterpreterPtr::processImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack) { + // We always want to call the functionalization kernels if functionalize() is on the layer stack. + // It's the responsibility of the functionalization kernel to no-op and redispatch + // if none of the input tensors are functional. + setup_dispatch_key_tls(TransformType::Functionalize, DispatchKeySet(DispatchKey::Functionalize)); + auto functionalization_add_back_views = functionalizeAddBackViews(); + // We have some side-car TLS that we can set to toggle the functionaliation behavior. + // If set, then we functionalization will only remove mutations, instead of + // removing both mutations AND view operators. + at::functionalization::impl::FunctionalizationReapplyViewsGuard functional_guard(functionalization_add_back_views); + + op.callBoxed(stack); + + auto ret_size = op.schema().returns().size(); + foreachTensorInplace(*stack, static_cast(stack->size() - ret_size), static_cast(stack->size()), + [&](const Tensor& tensor) { + if (at::functionalization::impl::isFunctionalTensor(tensor)) { + auto wrapper = at::functionalization::impl::unsafeGetFunctionalWrapper(tensor); + // Functorch is responsible for setting the level on the wrapper, since we don't + // have that info available in core (for now). + // We could just "propagate" the level from the input tensors inside of the functionalize kernels, + // but unfortunately we can't do that for factory operators. + wrapper->set_level(level()); + } + return tensor; + } + ); +} + +void FunctionalizeInterpreterPtr::sendToNextInterpreterImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + bool grad_special_case) { + // For now, we don't support nested functionalization calls. + // This check just enforces that - after the functionalize kernel runs + // and we hit the BackModeFallback, we'll have unwrapped our FunctionalTensors + // so we can check that the unwrapped thing is not another (nested) FunctionalTensor. + auto args_size = op.schema().arguments().size(); + sanityCheckNotFunctional(op, stack, args_size); + + // Re-dispatch + if (getDynamicLayerStack().empty()) { + sanityCheckStack(op, stack); + } + op.callBoxed(stack); + + auto ret_size = op.schema().returns().size(); + sanityCheckNotFunctional(op, stack, ret_size); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/FunctionalizeInterpreter.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/FunctionalizeInterpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..5ae0bcdccdf5fc5c061b542d175f677eace9a4c2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/FunctionalizeInterpreter.h @@ -0,0 +1,22 @@ +#pragma once +#include + +namespace at::functorch { + +// This is the interpreter that handles the functionalize() transform. +// See NOTE: [functorch interpreter stack] for more details. + +struct FunctionalizeInterpreterPtr { + explicit FunctionalizeInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Functionalize); } + TransformType key() const { return base_->key(); } + int64_t level() const { return base_->level(); } + void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack); + void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case); + bool functionalizeAddBackViews() const { + return std::get(base_->meta()).functionalizeAddBackViews_; + } + private: + const Interpreter* base_; +}; + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/Interpreter.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/Interpreter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..467f00fb66b973ad8f5ea4b4ae5a8aa10c523672 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/Interpreter.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace at::functorch { + +static DispatchKeySet get_all_dynlayer_keyset() { + // NB: FULL_AFTER does not include the dispatch key + + // "all dispatch keys between DynamicLayer{Front, Back}Mode, inclusive" + auto result = + DispatchKeySet(DispatchKeySet::FULL_AFTER, DispatchKey::FuncTorchDynamicLayerFrontMode) - + DispatchKeySet(DispatchKeySet::FULL_AFTER, DispatchKey::FuncTorchDynamicLayerBackMode); + result = result | DispatchKeySet({DispatchKey::FuncTorchDynamicLayerFrontMode}); + + // Hack: don't handle the autocast dispatch keys. Their interaction with functorch + // is weird. + result = result - autocast_dispatch_keyset; + + // Hack: don't handle DispatchKey::FuncTorchVmapMode. We need a better way of modeling this. + // In e.g. grad(vmap(f)), DispatchKey::FuncTorchVmapMode makes it so that all random operations, + // even after we are done handling the vmap layer, error out. + result = result.remove(DispatchKey::FuncTorchVmapMode); + + return result; +} + +// TODO: This should be constexpr, but there are some methods +// of DispatchKeySet that haven't been marked constexpr yet. +static DispatchKeySet all_dynlayer_keyset = get_all_dynlayer_keyset(); + +static DispatchKeySet keysForEnteringDynamicLayer(TransformType key) { + if (key == TransformType::Vmap) { + // NB: Does not include DispatchKey::FuncTorchVmapMode. We may modulate the key when + // constructing the DynamicLayer, but we don't control it when entering/exiting + // the DynamicLayer. + return DispatchKeySet({DispatchKey::FuncTorchBatched, DispatchKey::BatchedNestedTensor}); + } else if (key == TransformType::Grad || key == TransformType::Jvp) { + return autograd_dispatch_keyset.add(DispatchKey::ADInplaceOrView); + } else if (key == TransformType::Functionalize) { + return DispatchKeySet(DispatchKey::Functionalize); + } else { + TORCH_INTERNAL_ASSERT(false, "Unsupported key: ", key); + } +} + +DispatchKeySet keysToExcludeWhenEnteringDynamicLayer(TransformType key) { + DispatchKeySet exclude = all_dynlayer_keyset; + exclude = exclude.remove(DispatchKey::FuncTorchDynamicLayerBackMode); + exclude = exclude - keysForEnteringDynamicLayer(key); + return exclude; +} + +void setup_dispatch_key_tls(TransformType key, DispatchKeySet also_include) { + auto local_keyset = c10::impl::tls_local_dispatch_key_set(); + auto to_exclude = local_keyset.excluded_; + to_exclude = to_exclude | keysToExcludeWhenEnteringDynamicLayer(key); + to_exclude = to_exclude - keysForEnteringDynamicLayer(key); + local_keyset.excluded_ = to_exclude; + local_keyset.included_ = local_keyset.included_ | also_include; + c10::impl::_force_tls_local_dispatch_key_set(local_keyset); +} + +std::ostream& operator<<(std::ostream& os, const TransformType& t) { + switch (t) { + case TransformType::Torch: + os << "Torch"; + break; + case TransformType::Vmap: + os << "Vmap"; + break; + case TransformType::Grad: + os << "Grad"; + break; + case TransformType::Jvp: + os << "Jvp"; + break; + case TransformType::Functionalize: + os << "Functionalize"; + break; + default: + TORCH_INTERNAL_ASSERT(false); + } + return os; +} + +void sanityCheckStack(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + auto num_args = op.schema().arguments().size(); + foreachTensorInplace(*stack, static_cast(stack->size() - num_args), static_cast(stack->size()), + [](const Tensor& tensor) { + auto result = unwrapIfDead(tensor); + auto* wrapper = maybeGetTensorWrapper(result); + TORCH_INTERNAL_ASSERT(wrapper == nullptr); + auto* batched = maybeGetBatchedImpl(result); + TORCH_INTERNAL_ASSERT(batched == nullptr); + return tensor; + }); +} + +#define INTERPRETER_DISPATCH(type, method) \ + switch (key()) { \ + case TransformType::Vmap: \ + TORCH_INTERNAL_ASSERT(std::holds_alternative(this->meta()));\ + return VmapInterpreterPtr(this). method; \ + case TransformType::Grad: \ + TORCH_INTERNAL_ASSERT(std::holds_alternative(this->meta()));\ + return GradInterpreterPtr(this). method; \ + case TransformType::Jvp: \ + TORCH_INTERNAL_ASSERT(std::holds_alternative(this->meta()));\ + return JvpInterpreterPtr(this). method; \ + case TransformType::Functionalize: \ + TORCH_INTERNAL_ASSERT(std::holds_alternative(this->meta()));\ + return FunctionalizeInterpreterPtr(this). method; \ + default: \ + TORCH_INTERNAL_ASSERT(false, "Unrecognized transform"); \ + } + +void Interpreter::process(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + INTERPRETER_DISPATCH(key_, SINGLE_ARG(processImpl(op, stack))) +} + +void Interpreter::sendToNextInterpreter(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case) { + INTERPRETER_DISPATCH(key_, SINGLE_ARG(sendToNextInterpreterImpl(op, stack, grad_special_case))) +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/Interpreter.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/Interpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..0aea5c3f8e5a8acdf52fff1fe05ee04dd6714c08 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/Interpreter.h @@ -0,0 +1,361 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::functorch { + +// NOTE: [functorch interpreter stack] +// +// functorch's dispatching system uses a stack of interpreters. +// Historically we've referred to this as the "DynamicLayerStack". +// +// An interpreter is something that reads in the code it is passed +// and then executes it. We have a different interpreter per-transform: +// the "VmapInterpreter" is responsible for reading in operators (like aten::mv) +// and executing the batched version of it (the batching rule for aten::mv). +// +// Concretely, each interpreter is responsible for two things: +// +// 1) process(ophandle, stack) +// Given an operator handle and a stack of arguments, the interpreter is +// responsible for figuring out how to execute the operation under the semantics +// of the interpreter. For e.g. VmapInterpreter, this is figuring out how to call +// the batching rule. +// +// The batching rules are stored as kernels on the FuncTorchBatched key, so the way +// VmapInterpreter calls the batching rule is roughly: (A) exclude all +// dispatch keys aside from the Batched key, (B) redispatch so we get to the +// Batched key. +// +// 2) sendToNextInterpreter(ophandle, stack) +// The VmapInterpreter, when it sees aten::mv, will process it into a call to +// aten::mm. It then needs to send the call to aten::mm to the next interpreter +// in the interpreter stack. +// +// The VmapInterpreter just does this via a call to ophandle.callBoxed(stack) +// and most Interpreters will implement it this way. + +enum class RandomnessType { + Error, // always errors when calling a random function + Same, // randomness appears the same across batches + Different, // randomness appears different across batches + END +}; + +enum class TransformType { + Torch, // Unused + Vmap, + Grad, // reverse-mode AD, aka vjp + Jvp, // forward-mode AD + Functionalize, +}; + +std::ostream& operator<<(std::ostream& os, const TransformType& t); + +// NOTE: [Interpreter "subclassing" design] +// +// How are various Interpreters for different transforms (vmap, grad, ...) +// implemented? +// +// Accessing interpreters is in the hot-path of functorch so we have a constraint +// that this code must be as fast as possible. +// +// As a result, we stay away from virtual methods and this causes our code +// to look a little funny. +// +// `Interpreter` is the struct for Interpreters. It holds ALL of the +// relevant information (what type of interpreter it is and the metadata). +// Metadata for each interpreter is represented as a Union (std::variant) +// of all possible metadata (VmapInterpreterMeta, GradInterpreterMeta, ...). +// +// Given an Interpreter, how do I get a "VmapInterpreter"? You may wish to do this +// if you want to access the metadata fields (like batchSize and randomness). +// +// Each type of interpreter (e.g. Vmap) has a convenience struct +// (e.g. VmapInterpreterPtr) associated with it. +// +// Construct the convenience struct with VmapInterpreterPtr(Interpreter*), +// and then one can access methods on VmapInterpreterPtr like so: +// >>> VmapInterpreterPtr(&interpreter).batchSize() +// +// Finally, Interpreter::process switches on the type of the interpreter +// and calls one of {Transform}Interpreter::processImpl under the hood. +// Same for Interpreter::sendToNextInterpreter :) + +struct VmapInterpreterMeta { + explicit VmapInterpreterMeta(c10::SymInt batchSize, RandomnessType randomness) : + batchSize_(std::move(batchSize)), randomness_(randomness) {} + + c10::SymInt batchSize_; + RandomnessType randomness_; + + VmapInterpreterMeta() = default; + VmapInterpreterMeta(const VmapInterpreterMeta&) = default; + VmapInterpreterMeta(VmapInterpreterMeta&&) = default; + VmapInterpreterMeta& operator=(const VmapInterpreterMeta&) = default; + VmapInterpreterMeta& operator=(VmapInterpreterMeta&&) = default; + ~VmapInterpreterMeta() = default; + + template + friend void to_json(T& json_j, const VmapInterpreterMeta& json_t) { + TORCH_CHECK( + !json_t.batchSize_.is_heap_allocated(), + "Serialization for heap-allocated SymInt is not implemented yet" + ); + json_j["batchSize"] = json_t.batchSize_.as_int_unchecked(); + json_j["randomness"] = static_cast(json_t.randomness_); + } + + template + friend void from_json(const T& json_j, VmapInterpreterMeta& json_t) { + json_t.batchSize_ = c10::SymInt(SymInt::Unchecked::UNCHECKED, json_j["batchSize"]); + json_t.randomness_ = static_cast(json_j["randomness"]); + } +}; + +struct GradInterpreterMeta { + explicit GradInterpreterMeta(bool prevGradMode, bool prevInferenceMode = false) + : prevGradMode_(prevGradMode), prevInferenceMode_(prevInferenceMode) {} + GradInterpreterMeta() = default; + GradInterpreterMeta(const GradInterpreterMeta&) = default; + GradInterpreterMeta(GradInterpreterMeta&&) = default; + GradInterpreterMeta& operator=(const GradInterpreterMeta&) = default; + GradInterpreterMeta& operator=(GradInterpreterMeta&&) = default; + ~GradInterpreterMeta() = default; + + bool prevGradMode_; + bool prevInferenceMode_; + template + friend void to_json(T& json_j, const GradInterpreterMeta& json_t) { + json_j["prevGradMode"] = json_t.prevGradMode_; + json_j["prevInferenceMode"] = json_t.prevInferenceMode_; + } + + template + friend void from_json(const T& json_j, GradInterpreterMeta& json_t) { + json_t.prevGradMode_ = json_j["prevGradMode"]; + json_t.prevInferenceMode_ = json_j.value("prevInferenceMode", false); + } +}; + +struct JvpInterpreterMeta { + explicit JvpInterpreterMeta(bool prevFwdGradMode, bool prevInferenceMode = false) + : prevFwdGradMode_(prevFwdGradMode), prevInferenceMode_(prevInferenceMode) {} + JvpInterpreterMeta() = default; + JvpInterpreterMeta(const JvpInterpreterMeta&) = default; + JvpInterpreterMeta(JvpInterpreterMeta&&) = default; + JvpInterpreterMeta& operator=(const JvpInterpreterMeta&) = default; + JvpInterpreterMeta& operator=(JvpInterpreterMeta&&) = default; + ~JvpInterpreterMeta() = default; + + bool prevFwdGradMode_; + bool prevInferenceMode_; + template + friend void to_json(T& json_j, const JvpInterpreterMeta& json_t) { + json_j["prevFwdGradMode"] = json_t.prevFwdGradMode_; + json_j["prevInferenceMode"] = json_t.prevInferenceMode_; + } + + template + friend void from_json(const T& json_j, JvpInterpreterMeta& json_t) { + json_t.prevFwdGradMode_ = json_j["prevFwdGradMode"]; + json_t.prevInferenceMode_ = json_j.value("prevInferenceMode", false); + } +}; + +struct FunctionalizeInterpreterMeta { + explicit FunctionalizeInterpreterMeta(bool functionalizeAddBackViews) : + functionalizeAddBackViews_(functionalizeAddBackViews) {} + FunctionalizeInterpreterMeta() = default; + FunctionalizeInterpreterMeta(const FunctionalizeInterpreterMeta&) = default; + FunctionalizeInterpreterMeta(FunctionalizeInterpreterMeta&&) = default; + FunctionalizeInterpreterMeta& operator=(const FunctionalizeInterpreterMeta&) = default; + FunctionalizeInterpreterMeta& operator=(FunctionalizeInterpreterMeta&&) = default; + ~FunctionalizeInterpreterMeta() = default; + + bool functionalizeAddBackViews_; + template + friend void to_json(T& json_j, const FunctionalizeInterpreterMeta& json_t) { + json_j["functionalizeAddBackViews"] = json_t.functionalizeAddBackViews_; + } + + template + friend void from_json(const T& json_j, FunctionalizeInterpreterMeta& json_t) { + json_t.functionalizeAddBackViews_ = json_j["functionalizeAddBackViews"]; + } +}; + +typedef std::variant< + int64_t, + GradInterpreterMeta, + JvpInterpreterMeta, + VmapInterpreterMeta, + FunctionalizeInterpreterMeta +> InterpreterMeta; + + +struct Interpreter { + // factory functions + static Interpreter Vmap(int64_t level, c10::SymInt batchSize, RandomnessType randomness) { + return Interpreter(TransformType::Vmap, level, VmapInterpreterMeta(std::move(batchSize), randomness)); + } + static Interpreter Grad(int64_t level, bool prevGradMode, bool prevInferenceMode = false) { + return Interpreter(TransformType::Grad, level, GradInterpreterMeta(prevGradMode, prevInferenceMode)); + } + static Interpreter Jvp(int64_t level, bool prevFwdGradMode, bool prevInferenceMode = false) { + return Interpreter(TransformType::Jvp, level, JvpInterpreterMeta(prevFwdGradMode, prevInferenceMode)); + } + static Interpreter Functionalize(int64_t level, bool functionalizeAddBackViews) { + return Interpreter(TransformType::Functionalize, level, FunctionalizeInterpreterMeta(functionalizeAddBackViews)); + } + + // methods + TransformType key() const { return type_; } + int64_t level() const { return level_; } + const InterpreterMeta& meta() const { return meta_; } + + void process(const c10::OperatorHandle& op, torch::jit::Stack* stack); + void sendToNextInterpreter(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case); + + void saveLocalDispatchKeySet(c10::impl::LocalDispatchKeySet keyset) { + TORCH_INTERNAL_ASSERT(!savedLocalDispatchKeySet_.has_value()); + savedLocalDispatchKeySet_ = keyset; + } + void clearSavedLocalDispatchKeySet() { + TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value()); + savedLocalDispatchKeySet_ = std::nullopt; + } + c10::impl::LocalDispatchKeySet getSavedLocalDispatchKeySet() const { + TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value()); + return *savedLocalDispatchKeySet_; + } + + // An Interpreter is alive if we are currently inside the ongoing transform + // for the interpreter. For example, vmap(f)(x); inside of f, the vmap's + // corresponding Interpreter is alive, even when it is not on the DynamicLayerStack. + bool is_alive() const { + return *is_alive_; + } + const std::shared_ptr& is_alive_ptr() const { + return is_alive_; + } + void set_is_alive(bool alive) { + *is_alive_ = alive; + } + + // Please don't use this + explicit Interpreter() = default; + + template + friend void to_json(T& json_j, const Interpreter& json_t) { + json_j["type"] = static_cast(json_t.type_); + json_j["level"] = json_t.level_; + if (json_t.savedLocalDispatchKeySet_) { + json_j["savedLocalDispatchKeySet"] = { + {"included", json_t.savedLocalDispatchKeySet_->included_.raw_repr()}, + {"excluded", json_t.savedLocalDispatchKeySet_->excluded_.raw_repr()} + }; + } else { + json_j["savedLocalDispatchKeySet"] = nlohmann::json(); + } + json_j["is_alive"] = *json_t.is_alive_; + std::visit([&](auto&& arg) { + using V = std::decay_t; + if constexpr (std::is_same_v) { + json_j["meta"] = {{"Torch", arg}}; + } else if constexpr (std::is_same_v) { + json_j["meta"] = {{"Grad", arg}}; + } else if constexpr (std::is_same_v) { + json_j["meta"] = {{"Jvp", arg}}; + } else if constexpr (std::is_same_v) { + json_j["meta"] = {{"Vmap", arg}}; + } else if constexpr (std::is_same_v) { + json_j["meta"] = {{"Functionalize", arg}}; + } else { + static_assert(false && sizeof(V), "unknown variant case"); + } + }, json_t.meta_); + } + + template + friend void from_json(const T& json_j, Interpreter& json_t) { + json_t.type_ = static_cast(json_j["type"]); + json_t.level_ = json_j["level"]; + auto savedLocalDispatchKeySet = json_j["savedLocalDispatchKeySet"]; + if (savedLocalDispatchKeySet.is_null()) { + json_t.savedLocalDispatchKeySet_ = std::nullopt; + } else { + c10::impl::PODLocalDispatchKeySet pod; + pod.set_included(DispatchKeySet::from_raw_repr(savedLocalDispatchKeySet["included"].template get())); + pod.set_excluded(DispatchKeySet::from_raw_repr(savedLocalDispatchKeySet["excluded"].template get())); + json_t.savedLocalDispatchKeySet_ = c10::impl::LocalDispatchKeySet(pod); + } + json_t.is_alive_ = std::make_shared(json_j["is_alive"]); + auto meta = json_j["meta"]; + if (meta.contains("Torch")) { + json_t.meta_.emplace(meta["Torch"].template get()); + } else if (meta.contains("Grad")) { + json_t.meta_.emplace(meta["Grad"].template get()); + } else if (meta.contains("Jvp")) { + json_t.meta_.emplace(meta["Jvp"].template get()); + } else if (meta.contains("Vmap")) { + json_t.meta_.emplace(meta["Vmap"].template get()); + } else if (meta.contains("Functionalize")) { + json_t.meta_.emplace(meta["Functionalize"].template get()); + } else { + TORCH_CHECK(false, "unknown interpreter metadata type"); + } + } + + std::string serialize() const { + return nlohmann::json(*this).dump(); + } + + static Interpreter deserialize(const std::string& serialized) { + return nlohmann::json::parse(serialized).get(); + } + + private: + explicit Interpreter(TransformType type, int64_t level, InterpreterMeta meta): + type_(type), level_(level), is_alive_(std::make_shared(false)), meta_(std::move(meta)) {} + + // fields + TransformType type_{}; + int64_t level_{}; + std::optional savedLocalDispatchKeySet_; + std::shared_ptr is_alive_; + InterpreterMeta meta_; +}; + +// Applies the following for-loop: +// for i in range(begin, end): +// args[i] = func(args[i]) +void foreachTensorInplace(std::vector& args, int64_t begin, int64_t end, + std::function func); + +// Applies the following for-loop: +// for i in range(begin, end): +// if use_flag_relative[i] == 1: <-- treats use_flag_relative as a bitset +// args[i] = func(args[i], i - begin, true) +// args[i] = func(args[i], i - begin) +void foreachTensorInplaceWithFlag(std::vector& args, int64_t begin, int64_t end, + const std::bitset<64> use_flag_relative, const std::function& func); + +std::vector findUnwrappedInputs(std::vector& args, int64_t begin, int64_t end); + +DispatchKeySet keysToExcludeWhenEnteringDynamicLayer(TransformType key); + +void setup_dispatch_key_tls(TransformType key, DispatchKeySet include); + +void sanityCheckStack(const c10::OperatorHandle& op, torch::jit::Stack* stack); + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyBatchingRegistrations.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyBatchingRegistrations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2a37bb50d18fcaf1919b0103ac4becc5716e3c2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyBatchingRegistrations.cpp @@ -0,0 +1,766 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace at::functorch { + + +// NOTE: [What is a batching rule?] +// +// NB: the following description only applies to this file and is about +// the legacy (deprecated) batching rule API. Please see writing_batch_rules.md +// for how to write new-style batching rules. +// +// This files contains batching rules written with the legacy (now-deprecated) +// batching rule API. +// Please try to use the new-style batching rule API (see writing_batch_rules.md) +// +// A *batching rule* implements the logic of how to call an operator on inputs +// that have zero or more additional batch dimensions. When one does a vmap, the +// dimension(s) being vmap'ed over get recorded as batch dimensions. +// +// For example, vmap(torch.add)(x, y) +// 1. wraps `x` into batched_x = BatchedTensor(x, bdims=[(lvl=1, dim=0)]; +// 2. wraps `y` into batched_y = BatchedTensor(y, bdims=[(lvl=1, dim=0)]; +// 3. and then runs `torch.add(batched_x, batched_y)`. + +// NOTE: [When should I add a batching rule?] +// When you are adding a new operator, you'll need to add a batching rule so +// that vmap can work efficiently with said operator. If you do not, we'll attempt +// to generate a slow fallback for the batching rule. + +// NOTE: [How to write batching rules?] +// The signature of a batching rule should look like exactly like the C++ signature +// of its operator. +// +// First, see NOTE: [Logical vs physical args] in VmapTransforms.h for terminology. +// +// At a high level, what a batching rule does is the following: +// 1. Converts (logical) BatchedTensors to views on physical tensors. +// 2. Converts logical arguments (e.g. dimension indexes, shapes) to physical +// arguments that correspond to the physical tensors. +// 3. Calls at:: operations on the physical tensors and arguments to produce +// some physical results. +// 4. Converts physical results back to BatchedTensors. +// +// Steps 1, 2, and 4 differ for operators with different batching behaviors. When +// writing a new batching rule, please select a VmapTransform that matches the +// batching behavior of your operation. The VmapTransform provides helper functions +// to do steps (1), (2), and (4). +// (see NOTE: [What is an VmapTransform?] in VmapTransforms.h) + +namespace{ +// PyTorch allows operations to specify dim 0 and dim -1 on a scalar tensor. +bool is_allowed_dim_on_scalar_tensor(int64_t dim) { + return dim == 0 || dim == -1; +} + +int64_t get_current_level() { + auto maybe_level = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_level.has_value()); + return maybe_level->layerId(); +} + +// This check should probably go into the dispatcher... +bool participatesInCurrentLevel(const Tensor& self) { + auto current_level = get_current_level(); + auto* maybe_batched_impl = maybeGetBatchedImpl(self); + if (!maybe_batched_impl) { + return false; + } + auto self_level = maybe_batched_impl->level(); + TORCH_INTERNAL_ASSERT(self_level <= current_level); + return self_level == current_level; +} + +bool participatesInCurrentLevel(ITensorListRef self) { + for (const Tensor& tensor : self) { + if (participatesInCurrentLevel(tensor)) { + return true; + } + } + return false; +} + +Tensor& squeeze_dims__batching_rule(Tensor& self, IntArrayRef dims) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return self.squeeze_(dims); + } + auto* batched = maybeGetBatchedImpl(self); + const auto bdim = batched->bdim(); + auto logical_dim = self.dim(); + + if (logical_dim == 0) { + TORCH_CHECK( + dims.empty() || (dims.size() == 1 && dims[0] == 0), + "Dimension is out of range (expected to be in range of [-1, 0], but got ", dims); + return self; + } + + // Adjust any dimensions higher than the batch dimension + DimVector adjusted_dims(dims.begin(), dims.end()); + int64_t updated_batch_idx = bdim; + for (auto &d : adjusted_dims) { + auto actual_dim = c10::maybe_wrap_dim(d, logical_dim); + if (actual_dim < bdim) { + d = actual_dim; + if (batched->value().sym_size(actual_dim) == 1) { + // A column before batch dimension will be dropped so adjust accordingly. + --updated_batch_idx; + } + } else { + // Since dimension to be squeezed is after the batch dimension adjust by one to account + // for the original batch dimension. In this case batch dimension won't move. + d = actual_dim + 1; + } + } + + batched->value().squeeze_(adjusted_dims); + if (updated_batch_idx != bdim) { + batched->unsafe_set_bdim(updated_batch_idx); + } + batched->refreshTensorMetadata(); + return self; +} + +Tensor& squeeze_dim__batching_rule(Tensor& self, int64_t dim) { + return squeeze_dims__batching_rule(self, {dim}); +} + +Tensor& squeeze__batching_rule(Tensor& self) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return self.squeeze_(); + } + auto* batched = maybeGetBatchedImpl(self); + + // Need to find out how many dimensions of size 1 are before the bdim + const auto bdim = batched->bdim(); + const auto physical_shape = batched->value().sizes(); + auto how_many_dims_of_size_1_before_bdim = 0; + for (const auto i : c10::irange(0, physical_shape.size())) { + if (static_cast(i) == bdim) { + break; + } + if (physical_shape[i] == 1) { + how_many_dims_of_size_1_before_bdim++; + } + } + + int64_t new_bdim = bdim - how_many_dims_of_size_1_before_bdim; + if (physical_shape[bdim] != 1) { + // if bdim is not 1, can just call squeeze_() + batched->value().squeeze_(); + } else { + // otherwise, squeeze_() is going to get rid of the bdim too. + // We "fix it up" by calling unsqueeze_. + batched->value().squeeze_(); + batched->value().unsqueeze(new_bdim); + } + + // Refresh metadata + batched->unsafe_set_bdim(new_bdim); + batched->refreshTensorMetadata(); + return self; +} + +Tensor& unsqueeze__batching_rule(Tensor& self, int64_t dim) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return self.unsqueeze_(dim); + } + auto* batched = maybeGetBatchedImpl(self); + auto logical_dim = self.dim(); + int64_t dim_physical = maybe_wrap_dim(dim, logical_dim + 1); + if (dim_physical >= batched->bdim()) { + dim_physical = 1 + dim_physical; + } else { + batched->unsafe_set_bdim(batched->bdim() + 1); + } + batched->value().unsqueeze_(dim_physical); + + // Also need to change some metadata... + batched->refreshTensorMetadata(); + return self; +} + +Tensor& transpose__batching_rule(Tensor& self, int64_t dim0, int64_t dim1) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return self.transpose_(dim0, dim1); + } + auto* batched = maybeGetBatchedImpl(self); + auto logical_dim = self.dim(); + + // PyTorch has a special case where scalar_tensor.transpose(dim0, dim1) works + // for dim0, dim1 in {0, -1} and returns the scalar tensor. If the following happens: + // >>> x = torch.randn(B0) # the per-examples are all scalars + // >>> vmap(lambda x: x.transpose_(0, -1), x) + // then we replicate this behavior. + if (logical_dim == 0 && + is_allowed_dim_on_scalar_tensor(dim0) && + is_allowed_dim_on_scalar_tensor(dim1)) { + // No transposing happened :P + return self; + } + + dim0 = maybe_wrap_dim(dim0, logical_dim); + dim1 = maybe_wrap_dim(dim1, logical_dim); + + dim0 = dim0 >= batched->bdim() ? dim0 + 1 : dim0; + dim1 = dim1 >= batched->bdim() ? dim1 + 1 : dim1; + batched->value().transpose_(dim0, dim1); + + // Also need to change some metadata... + batched->refreshTensorMetadata(); + return self; +} + +std::vector split_batching_rule(const Tensor& self, int64_t split_size, int64_t dim) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::split(self, split_size, dim); + } + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::split(self_physical.tensor(), split_size, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +std::vector split_with_sizes_batching_rule(const Tensor& self, SymIntArrayRef split_sizes, int64_t dim) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return split_with_sizes_symint(self, split_sizes, dim); + } + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = split_with_sizes_symint(self_physical.tensor(), split_sizes, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +std::vector split_with_sizes_copy_batching_rule(const Tensor& self, SymIntArrayRef split_sizes, int64_t dim) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return split_with_sizes_copy_symint(self, split_sizes, dim); + } + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = split_with_sizes_copy_symint(self_physical.tensor(), split_sizes, dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +std::vector unbind_batching_rule(const Tensor& self, int64_t dim) { + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::unbind(self, dim); + } + auto self_physical = MultiBatchVmapTransform::logicalToPhysical(self); + auto dim_physical = self_physical.getPhysicalDim(dim); + auto result = at::unbind(self_physical.tensor(), dim_physical); + self_physical.getPhysicalToLogicalMap().applyInplace(result); + return result; +} + +// given (sizes, strides, storage_offset) returns the maximum location that +// can be indexed (or nullopt if such a location doesn't exist, e.g., tensors +// with zero-size dims). +std::optional maximum_indexable_location( + c10::SymIntArrayRef sizes, c10::SymIntArrayRef strides, const c10::SymInt& storage_offset) { + auto result = native::storage_size_for(sizes, strides); + if (result == 0) { + return std::nullopt; + } + return result + storage_offset; +} + +// Let x be the "first slice" of physical_tensor. +// This checks that the range of possible memory locations accessible by +// x.as_strided(sizes, strides, maybe_storage_offset) +// are within the bounds of possible memory locations accessible by x. +void checkBasicAsStridedValidForSlice( + const Tensor& physical_tensor, + int64_t num_batch_dims, + c10::SymIntArrayRef sizes, + c10::SymIntArrayRef strides, + const std::optional& maybe_storage_offset) { + auto slice_sizes = physical_tensor.sym_sizes().slice(num_batch_dims); + auto slice_strides = physical_tensor.sym_strides().slice(num_batch_dims); + auto base_offset = physical_tensor.sym_storage_offset(); + + auto storage_offset = maybe_storage_offset.value_or(base_offset); + + auto max_as_strided_loc = maximum_indexable_location(sizes, strides, storage_offset); + auto max_slice_loc = maximum_indexable_location(slice_sizes, slice_strides, base_offset); + + if (!max_as_strided_loc.has_value()) { + return; + } + if (!max_slice_loc.has_value()) { + TORCH_CHECK(false, + "result = tensor.as_strided(", sizes, ", ", strides, ", ", storage_offset, ") ", + "can access memory outside of `tensor`. `tensor` has no storage but the ", + "passed-in (size, stride, storage_offset) imply a result with some storage. ", + "This is not supported inside of vmap, please try to rewrite the ", + "`as_strided` call as a sequence of PyTorch view operations"); + } + + TORCH_CHECK( + *max_as_strided_loc <= *max_slice_loc && base_offset <= storage_offset, + "result = tensor.as_strided(", sizes, ", ", strides, ", ", storage_offset, ") ", + "can access memory outside of `tensor`. `result` can access some ", + "memory in range [", storage_offset, ", ", *max_as_strided_loc, "], but ", + "`tensor` can only access some memory in range [", base_offset, ", ", + *max_slice_loc, "]. This is not supported inside of vmap, please try to ", + "rewrite the `as_strided` call as a sequence of PyTorch view operations"); +} + +// What are the semantics of as_strided inside of vmap? +// y = vmap(lambda x: x.as_strided(sizes, strides, offset))(xs) +// This returns a view on `x`, `y`, such that each y[i] has: +// - sizes: `sizes` +// - strides: `strides` +// - storage_offset: offset + i * x.stride(batch_dim) +// +// In other words, it is as if we had treated each x[i] as having storage +// offset equal to xs.offset() and called as_strided(sizes, sizes, offset). +// (that is equivalent to x[i].as_strided( +// sizes, sizes, offset + x[i].storage_offset() - xs.offset()) for all i) +// +// Note that this *may* be different from actually running as_strided +// in a for-loop. This is due to how as_strided takes in `offset` to be +// an *absolute* offset. As an example, consider: +// >>> x = torch.tensor([0., 1., 2., 3., 4.]).as_strided([4], [1], 1) +// >>> z = [x[i].as_strided([1], [1], 1) for i in range(4)] +// Each z[i] is actually the same view on x (z[i] == torch.tensor([1.]))! +// However, we consider the above for-loop comprehension to be a user error: +// a user should have written the following if they wanted to use as_strided +// in a per-sample way: +// >>> z = [x[i].as_strided([1], [1], 1 + x[i].storage_offset() - 1) for i in range(4)] +Tensor as_strided_batching_rule( + const Tensor& tensor, + c10::SymIntArrayRef sizes, + c10::SymIntArrayRef strides, + std::optional storage_offset) { + if (!participatesInCurrentLevel(tensor)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::as_strided_symint(tensor, sizes, strides, std::move(storage_offset)); + } + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(tensor); + auto num_batch_dims = physical_view.numBatchDims(); + auto physical_sizes = physical_view.getPhysicalShape(sizes); + const auto& physical_tensor = physical_view.tensor(); + + // We can't rely on the physical as_strided call to do this for us because + // we do some sanity checks on the size/strides before calling into as_strided. + TORCH_CHECK(sizes.size() == strides.size(), + "Tensor.as_strided(size, stride, ...): size and stride must have the ", + "same length! Got size ", sizes, " and stride ", strides); + + // Sanity checks: + // 1. as_strided(sizes, strides, storage_offset + tensor[i].offset() - tensor.offset()) + // is valid for a slice of the input tensor. + // See Note: [When will the as_strided batching rule fail?] for details. + checkBasicAsStridedValidForSlice( + physical_tensor, num_batch_dims, sizes, strides, storage_offset); + + // physical_strides = physical tensor's batch strides + (logical) strides + auto batch_strides = physical_tensor.strides().slice(0, num_batch_dims); + SymDimVector physical_strides; + physical_strides.reserve(num_batch_dims + strides.size()); + physical_strides.insert( + physical_strides.end(), batch_strides.begin(), batch_strides.end()); + physical_strides.insert( + physical_strides.end(), strides.begin(), strides.end()); + + // If zi = xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) + // is valid for all i, then it turns out that + // xs.as_strided(physical_sizes, physical_strides, offset) always succeeds + // and creates a tensor y such that each y[i] references the same memory + // locations as zi. See NOTE: [When will the as_strided batching rule fail?] + auto result = physical_view.tensor().as_strided_symint( + physical_sizes, physical_strides, std::move(storage_offset)); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +// NOTE: [When will the as_strided batching rule fail?] +// If zi = xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) +// is valid for all i, then it turns out that +// xs.as_strided(physical_sizes, physical_strides, offset) always succeeds and +// creates a tensor y such that each y[i] refers to the same memory as zi. +// +// Let's say we have xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()). +// Furthermore, let's say that as a part of being "valid" this as_strided call +// does not return a result that can index memory not indexable by xs[i]. +// +// WLOG, assume that there's only one batch dim and it is at the front of the +// `xs` tensor. Let B be the batch size and S be the stride of the batch dim. +// - If the batch dim isn't at the front of the tensor, then we can just move it +// to the front with movedim/permute. This is always valid because it just swaps +// some strides around. +// - This proof also works for tensors with multiple batch dims. We just have to +// do a little accounting: +// - instead of [B], we'd have [B0, B1, ..., Bk]. +// - instead of [S], we'd have [S0, S1, ..., Sk]. +// - instead of i, we'd have a list of indices [I0, I1, ..., Ik] +// - instead of S * I, we'd have \sum_{i=0}^k S_i * I_i +// +// [Equation 1] +// xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) has: +// - sizes: sizes +// - strides: strides +// - offset: offset + S * i +// +// x.as_strided itself checks that: +// - (sizes, strides, offset) are in bounds for `x`'s storage. +// - strides are positive +// - offset is positive +// +// Claim 1: if xs[i].as_strided(sizes, strides, offset + xs[i].offset() - xs.offset()) +// is valid, then +// ([B] + sizes, [S] + strides, offset + xs.offset()) are in bounds for `xs`'s storage. +// +// If we have the claim, then xs.as_strided([B] + sizes, [S] + strides, offset) +// won't error out. So all we need to check is that the memory locations are +// what we expected. See [Hand-wavy proof of Claim 1] for proof (it's not very important) +// +// xs.as_strided(physical_sizes, physical_strides, offset) is equivalent to +// xs.as_strided([B] + sizes, [S] + strides, offset) +// +// xs.as_strided([B] + sizes, [S] + strides, offset) has: +// - sizes: [B] + sizes +// - strides: [S] + strides +// - offset: offset +// +// xs.as_strided([B] + sizes, [S] + strides, offset)[i] has: +// - sizes: sizes +// - strides: strides +// - offset: offset + S * i +// These memory locations are exactly the same as what we got for [Equation 1], +// so the xs.as_strided([B] + sizes, [S] + strides, offset) is valid. +// +// [Hand-wavy proof of Claim 1] +// Part of our definition of being valid is that xs[i].as_strided(...) +// must return a tensor that only uses memory indexable by xs[i]. +// This means that (sizes, strides, offset + xs[i].offset() - xs.offset()) satisfies: +// offset + xs[i].offset() - xs.offset() + 1 + \sum_j (sizes[j] - 1) * strides[j] +// <= xs[i].offset() + 1 + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j) +// (the largest-index memory location of xs[i].as_strided(...) must be \leq +// the largest-index memory location of xs[i]) +// +// Fiddling that inequality gives us: +// offset - xs.offset() + 1 + \sum_j (sizes[j] - 1) * strides[j] +// <= 1 + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j) +// +// offset - xs.offset() + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j] +// <= 1 + (B-1)*S + \sum_j (xs[i].size(j) - 1) * xs[i].stride(j) +// +// offset - xs.offset() + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j] +// <= 1 + \sum_j (xs.size(j) - 1) * xs.stride(j) +// +// offset + 1 + (B-1)*S + \sum_j (sizes[j] - 1) * strides[j] +// <= xs.offset() + 1 + \sum_j (xs.size(j) - 1) * xs.stride(j) +// (the largest-index memory location of xs.as_strided(size, stride, offset) +// is \leq than the largest-index memory location of xs) +// Under the assumptions we've made, the lower bound (lowest indexed memory) +// is trivially within the storage. +// +// Therefore ([B] + sizes, [S] + strides, offset) are in bounds for +// `xs`'s storage. + +template +Tensor unwrap_and_call(const Tensor& input, ExtraArgs... args) { + if (!participatesInCurrentLevel(input)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return Func(input, args...); + } + // guard against the user passing in a batch of scalar tensors with batch + auto* input_batched = unsafeGetBatchedImpl(input); + auto output_physical = Func(input_batched->value(), args...); + return makeBatched(output_physical, input_batched->bdim(), input_batched->level()); +} + +template +Tensor unwrap_and_call_method(const Tensor& input, ExtraArgs... extra_args) { + if (!participatesInCurrentLevel(input)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return (input.*Func)(extra_args...); + } + auto* input_batched = unsafeGetBatchedImpl(input); + auto output_physical = (input_batched->value().*Func)(extra_args...); + return makeBatched(output_physical, input_batched->bdim(), input_batched->level()); +} + +Tensor cat_batching_rule(const ITensorListRef& tensors, int64_t dim) { + if (!participatesInCurrentLevel(tensors)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::cat(tensors, dim); + } + + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + + // NB: Probably bad for perf that we're allocating std::vectors for each level, but + // what can you do. + auto materialized = tensors.materialize(); + dim = at::legacy_cat_wrap_dim(dim, materialized); + + // Strategy: + // we're going to unwrap tensors, move their batch dims to the front, + // and put them into `tensors_to_cat`. Tensors that don't have a batch dim + // will get one forced onto them. + // + // Then, we'll do at::cat(tensors_to_cat, ...). + // + // There's a special case where at::cat ignores tensors that have logical shape + // [0]. If we see a Tensor that has logical shape [0] (but physical shape [B, 0]), + // we'll just slice the tensor to get a Tensor of shape [0] to pass to at::cat. + std::vector tensors_to_cat; + tensors_to_cat.reserve(tensors.size()); + std::optional bdim_size = std::nullopt; + + // find the bdim size. Might not exist if all BatchedTensors should be skipped + // by cat's special case. + for (const auto& tensor : tensors) { + if (!participatesInCurrentLevel(tensor)) { + continue; + } + if (at::native::cat_should_skip_tensor(tensor)) { + continue; + } + const auto* batched = unsafeGetBatchedImpl(tensor); + bdim_size = batched->value().size(batched->bdim()); + break; + } + + // unwrap batchedtensors; expand out bdims + for (const auto& tensor : tensors) { + if (!participatesInCurrentLevel(tensor)) { + if (at::native::cat_should_skip_tensor(tensor) || !bdim_size.has_value()) { + tensors_to_cat.emplace_back(tensor); + continue; + } + tensors_to_cat.emplace_back(ensure_has_bdim(tensor, /*has_bdim*/false, *bdim_size)); + continue; + } + const auto* batched = unsafeGetBatchedImpl(tensor); + if (at::native::cat_should_skip_tensor(tensor)) { + // Special case: slice the tensor to get something of shape [0] to pass to cat + // We slice instead of allocate a new tensor to propagate requires_gradness... + tensors_to_cat.emplace_back(batched->value().select(/*dim=*/batched->bdim(), /*index=*/0)); + continue; + } + tensors_to_cat.emplace_back(moveBatchDimToFront(batched->value(), batched->bdim())); + } + + auto new_dim = bdim_size.has_value() ? dim + 1 : dim; + std::optional new_bdim = bdim_size.has_value() ? std::make_optional(static_cast(0)) : std::nullopt; + auto result = at::cat(tensors_to_cat, new_dim); + return makeBatched(result, new_bdim, get_current_level()); +} + +Tensor block_diag_batching_rule(TensorList tensors) { + if (!participatesInCurrentLevel(tensors)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::block_diag(tensors); + } + auto physical_views = MultiBatchVmapTransform::logicalToPhysical(tensors); + auto physical_tensors = fmap( + physical_views, [](const VmapPhysicalView& view) -> Tensor { return view.tensor(); }); + TORCH_INTERNAL_ASSERT( + !tensors.empty(), "The dispatcher should not have dispatched here otherwise."); + // Implementing this as a dummy for loop for now, since I'm not sure how to do it any better. + // I'm probably not accounting for potentially multiple batched dimensions? + auto bdim = physical_tensors[0].size(0); + std::vector batched_outputs; + batched_outputs.reserve(bdim); + for (const auto& i : c10::irange(bdim)) { + std::vector inputs_for_batch; + inputs_for_batch.reserve(physical_tensors.size()); + for (const auto& t : physical_tensors) { + inputs_for_batch.push_back(t[i]); + } + auto out_for_batch = at::block_diag(inputs_for_batch); + batched_outputs.push_back(out_for_batch.unsqueeze(0)); + } + auto result = at::cat(batched_outputs); + return physical_views[0].getPhysicalToLogicalMap().apply(result); +} + +Tensor stack_batching_rule(TensorList tensors, int64_t dim) { + if (!participatesInCurrentLevel(tensors)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return at::stack(tensors, dim); + } + auto physical_views = MultiBatchVmapTransform::logicalToPhysical(tensors); + auto physical_tensors = fmap( + physical_views, [](const VmapPhysicalView& view) -> Tensor { return view.tensor(); }); + TORCH_INTERNAL_ASSERT( + !tensors.empty(), "The dispatcher should not have dispatched here otherwise."); + // NB: stack wraps the dimensionality to (logical dim + 1), so we have to + // manually handle that here. + auto dim_physical = + physical_views[0].numBatchDims() + maybe_wrap_dim(dim, /*logical*/tensors[0].dim() + 1); + auto result = at::stack(physical_tensors, dim_physical); + return physical_views[0].getPhysicalToLogicalMap().apply(result); +} + +Tensor new_empty_strided_batching_rule( + const Tensor& self, + SymIntArrayRef sym_size, + SymIntArrayRef sym_stride, + std::optional dtype, + std::optional layout, + std::optional device, + std::optional pin_memory) { + + auto size = C10_AS_INTARRAYREF_SLOW(sym_size); + auto stride = C10_AS_INTARRAYREF_SLOW(sym_stride); + if (!participatesInCurrentLevel(self)) { + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + return self.new_empty_strided( + size, stride, dtype, layout, device, pin_memory); + } + + auto physical_view = MultiBatchVmapTransform::logicalToPhysical(self); + auto physical_size = physical_view.getPhysicalShape(size); + + // Let [B0, B1, B2] be the shape of the batch dims. We're going to create + // the batch dimensions at the front of the tensor (in memory layout), + // irrespective of whether or not they are actually at the front (in memory layout) + // in the original `self` tensor. This is because when a user calls + // `new_empty_strided` in general, the `strides` they provide are for a new + // tensor and have no relation to the strides of the original tensor. + // + // So, the physical shape of the result should be ([B0, B1, B2] + size), + // but what about the physical strides? + // + // We're actually free to pick whatever stride we want: + // e.g., for size=[5, 3], stride=[0, 1], we could decide to + // use + // - physical size: [B0, B1, B2, 5, 3] + // - physical stride: [9999*B1*B2, 9999*B2, 9999, 0, 1] + // + // Let's select some reasonable strides such that: + // - The batch dims are "contiguous" with respect to each other + // - if empty_strided(size, stride) would have created a contiguous Tensor, + // then this new physical Tensor (with batch dims) is also contiguous + // + // Let S be the size of the storage if one were to construct a tensor + // with `size` and `stride` via empty_strided(size, stride). + // Then the physical sizes/strides should be: + // - physical size: [B0, B1, B2, 5, 3] + // - physical stride: [B1 * B2 * S, B2 * S, S, 0, 1] + auto batch_shape = IntArrayRef( + physical_view.tensor().sizes().begin(), physical_view.numBatchDims()); + + // physical_strides = [B1 * B2 * S, B2 * S, S] + auto physical_strides = at::detail::defaultStrides(batch_shape); + TORCH_CHECK(size.size() == stride.size(), + "new_empty_strided(sizes, strides): dimensionality of sizes (", + size.size(), ") must match dimensionality of strides (", + stride.size(), ")"); + auto storage_size = native::storage_size_for(size, stride); + for (auto& physical_stride : physical_strides) { + physical_stride *= storage_size; + } + + // physical_strides = [B1 * B2 * S, B2 * S, S] + strides + physical_strides.insert(physical_strides.end(), stride.begin(), stride.end()); + + auto result = physical_view.tensor().new_empty_strided( + physical_size, physical_strides, dtype, layout, device, pin_memory); + return physical_view.getPhysicalToLogicalMap().apply(result); +} + +Tensor nested_cat_batching_rule(const ITensorListRef& tensors, int64_t dim) { + TORCH_CHECK(!tensors.empty(), "cat() not supported on empty tensor list"); + + std::vector> unbound; + for (const auto & tensor : tensors) { + auto* maybe_batched_impl = maybeGetBatchedImpl(tensor); + TORCH_CHECK(maybe_batched_impl, "Tried to run batching rule for cat() on a non-batched tensor"); + auto nt = maybe_batched_impl->value(); + TORCH_CHECK(nt.is_nested(), "Tried to run batching rule for cat() on a non-nested tensor"); + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::BatchedNestedTensor); + auto this_unbound = nt.unbind(); + if (!unbound.empty()) { + TORCH_INTERNAL_ASSERT(unbound.front().size() == this_unbound.size(), + "cat() not supported for differently-sized nested arguments"); + } + unbound.push_back(this_unbound); + } + + // Do a cat for each set of zipped unbound components + const auto num_components = unbound.front().size(); + std::vector outputs; + outputs.reserve(num_components); + for (auto i : c10::irange(num_components)) { + std::vector arg_list; + arg_list.reserve(unbound.size()); + for (auto j : c10::irange(unbound.size())) { + arg_list.push_back(unbound[j][i]); + } + outputs.push_back(at::cat(arg_list, dim)); + } + + // NB: NTs only support batching over dim 0 + auto out_nt = at::_nested_tensor_from_tensor_list(outputs); + return makeBatched(out_nt, 0, get_current_level()); +} + +} + +TORCH_LIBRARY_IMPL(_, FuncTorchBatched, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&batchedTensorForLoopFallback>()); +} + +TORCH_LIBRARY_IMPL(aten, FuncTorchBatched, m) { + // still legacy b/c returns multiple tensors + m.impl("split.Tensor", split_batching_rule); + m.impl("split_with_sizes", split_with_sizes_batching_rule); + m.impl("split_with_sizes_copy", split_with_sizes_copy_batching_rule); + m.impl("unbind.int", unbind_batching_rule); + m.impl("cat", cat_batching_rule); + m.impl("block_diag", block_diag_batching_rule); + m.impl("stack", stack_batching_rule); + + // still legacy b/c needs special inplace rules + m.impl("squeeze_", squeeze__batching_rule); + m.impl("squeeze_.dim", squeeze_dim__batching_rule); + m.impl("squeeze_.dims", squeeze_dims__batching_rule); + m.impl("unsqueeze_", unsqueeze__batching_rule); + m.impl("transpose_", transpose__batching_rule); + + // still legacy because these are ridiculously complicated + m.impl("as_strided", as_strided_batching_rule); + m.impl("new_empty_strided", new_empty_strided_batching_rule); + +} + +TORCH_LIBRARY_IMPL(_, BatchedNestedTensor, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&batchedNestedTensorForLoopFallback>()); +} + +// TODO: Move this somewhere better? +TORCH_LIBRARY_IMPL(aten, BatchedNestedTensor, m) { + m.impl("cat", nested_cat_batching_rule); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyVmapTransforms.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyVmapTransforms.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59706981453a206063b8ce86ff8ff9a93003c10c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyVmapTransforms.cpp @@ -0,0 +1,229 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +#include + +namespace at::functorch { + +// Takes a BatchedTensorImpl, permutes all of the batch dims to the front, +// and then returns a physical version of the Tensor. +static Tensor permuteBatchDimsToFront(const BatchedTensorImpl* batched) { + const Tensor& physical_tensor = batched->value(); + if (batched->bdim() == 0) { + return physical_tensor; + } + const auto sizes = physical_tensor.sym_sizes(); + VmapDimVector permutation(sizes.size(), 0); + permutation.reserve(sizes.size()); + const auto is_bdim = createBatchDimBitset(batched->bdim()); + int64_t idx = 0; + permutation[idx++] = batched->bdim(); + for (const auto ptr : c10::irange(0, sizes.size())) { + if (is_bdim[ptr]) { + continue; + } + permutation[idx++] = static_cast(ptr); + } + return physical_tensor.permute(permutation); +} + +VmapPhysicalView MultiBatchVmapTransform::logicalToPhysical(const Tensor& logical_tensor) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + TORCH_INTERNAL_ASSERT( + batched, + "logicalToPhysical(tensor) should only be passed a BatchedTensor"); + return { permuteBatchDimsToFront(batched), createVmapLevelsBitset(batched->level()) }; +} + +int64_t VmapPhysicalView::numBatchDims() const { + return static_cast(levels_.count()); +} + +int64_t VmapPhysicalView::numLogicalDims() const { + return /*physical*/tensor_.dim() - numBatchDims(); +} + +VmapDimVector VmapPhysicalView::getPhysicalDims(IntArrayRef logical_dims) const { + auto logical_ndim = numLogicalDims(); + // NB: fmap doesn't have a SmallVector variant, so we don't use it here. + VmapDimVector result; + result.reserve(logical_ndim); + for (auto dim : logical_dims) { + result.push_back(maybe_wrap_dim(dim, logical_ndim) + numBatchDims()); + } + return result; +} + +int64_t VmapPhysicalView::getPhysicalDim(int64_t logical_dim) const { + auto logical_ndim = numLogicalDims(); + return maybe_wrap_dim(logical_dim, logical_ndim) + numBatchDims(); +} + +VmapDimVector VmapPhysicalView::getPhysicalShape(IntArrayRef logical_shape) const { + VmapDimVector result; + result.reserve(logical_shape.size() + numBatchDims()); + auto tensor_sizes = tensor_.sizes(); + result.insert(result.end(), tensor_sizes.begin(), tensor_sizes.begin() + numBatchDims()); + result.insert(result.end(), logical_shape.begin(), logical_shape.end()); + return result; +} + +SymDimVector VmapPhysicalView::getPhysicalShape(c10::SymIntArrayRef logical_shape) const { + SymDimVector result; + result.reserve(logical_shape.size() + numBatchDims()); + auto tensor_sizes = tensor_.sym_sizes(); + result.insert(result.end(), tensor_sizes.begin(), tensor_sizes.begin() + numBatchDims()); + result.insert(result.end(), logical_shape.begin(), logical_shape.end()); + return result; +} + +static std::tuple computeFrontBatchDimsFromLevels(std::bitset levels_bitset) { + int64_t level = 0; + int64_t dim = 0; + for (; level < kVmapNumLevels; level++) { + if (!levels_bitset[level]) { + continue; + } + break; + } + return std::make_tuple(dim, level); +} + +static Tensor moveDimToFrontAndExpand(Tensor tensor, std::optional dim, c10::SymInt size) { + if (dim) { + tensor = tensor.movedim(*dim, 0); + } else { + tensor = tensor.unsqueeze(0); + auto expanded_sizes = tensor.sym_sizes().vec(); + expanded_sizes[0] = std::move(size); + tensor = tensor.expand_symint(expanded_sizes); + } + return tensor; +} + +// The algorithm is as follows: +// 1. Figure out what all of the collective levels in `logical_tensors` is. +// 2. Move all batch dims to the front of the tensors and add extra dims +// of size 1. At this point, every tensor will have a dimension for +// each of the collective levels. +// 3. Compute the batch_sizes. +// 4. Expand each physical tensor so that they have output batch size equal +// to `batch_sizes` +VmapPhysicalViewVec +MultiBatchVmapTransform::logicalToPhysical(ITensorListRef logical_tensors) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + auto cur_level = maybeCurrentDynamicLayer().value().layerId(); + c10::SymInt bdim_size = -1; + + // Figure out the batch size first + for (const auto& logical_tensor : logical_tensors) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + if (!batched) { + continue; + } + if (batched->level() != cur_level) { + continue; + } + bdim_size = batched->value().sym_size(batched->bdim()); + } + TORCH_INTERNAL_ASSERT(bdim_size != -1); + + std::bitset levels; + levels[cur_level] = true; + + VmapPhysicalViewVec result; + for (const auto& logical_tensor : logical_tensors) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + if (!batched || (batched->level() != cur_level)) { + // Unsqueeze dim 0, expand it to the correct shape + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto value = moveDimToFrontAndExpand(logical_tensor, {}, bdim_size); + result.emplace_back(std::move(value), levels); + continue; + } + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto physical = batched->value(); + auto value = moveDimToFrontAndExpand(physical, batched->bdim(), bdim_size); + result.emplace_back(std::move(value), levels); + } + + return result; +} + +static Tensor moveDimToFrontAndUnsqueeze(Tensor tensor, std::optional dim, int64_t example_ndim) { + if (dim) { + tensor = tensor.movedim(*dim, 0); + } else { + tensor = tensor.unsqueeze(0); + } + auto ndim = tensor.dim() - 1; + for (int64_t i = 0; i < example_ndim - ndim; i++) { + tensor = tensor.unsqueeze(1); + } + return tensor; +} + +VmapPhysicalViewVec BroadcastingVmapTransform::logicalToPhysical(TensorList logical_tensors) { + auto cur_level = maybeCurrentDynamicLayer().value().layerId(); + int64_t bdim_size = -1; + + // Figure out the batch size first + for (const auto& logical_tensor : logical_tensors) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + if (!batched || (batched->level() != cur_level)) { + continue; + } + bdim_size = batched->value().size(batched->bdim()); + } + TORCH_INTERNAL_ASSERT(bdim_size != -1); + + std::bitset levels; + levels[cur_level] = true; + + // figure out the example ndim + int64_t max_example_dim = -1; + for (const auto& logical_tensor : logical_tensors) { + max_example_dim = std::max(logical_tensor.dim(), max_example_dim); + } + + VmapPhysicalViewVec result; + for (const auto& logical_tensor : logical_tensors) { + auto* batched = maybeGetBatchedImpl(logical_tensor); + if (!batched || (batched->level() != cur_level)) { + // Unsqueeze dim 0, expand it to the correct shape + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto value = moveDimToFrontAndUnsqueeze(logical_tensor, {}, max_example_dim); + result.emplace_back(std::move(value), levels); + continue; + } + c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched); + auto physical = batched->value(); + auto value = moveDimToFrontAndUnsqueeze(physical, batched->bdim(), max_example_dim); + result.emplace_back(std::move(value), levels); + } + + return result; +} + +VmapPhysicalToLogicalMap VmapPhysicalView::getPhysicalToLogicalMap() const { + return VmapPhysicalToLogicalMap(levels_); +} + +Tensor VmapPhysicalToLogicalMap::apply(const Tensor& physical_tensor) const { + auto bdim_level = computeFrontBatchDimsFromLevels(levels_); + return makeBatched(physical_tensor, std::get<0>(bdim_level), std::get<1>(bdim_level)); +} + +void VmapPhysicalToLogicalMap::applyInplace(std::vector& physical_tensors) const { + for (const auto idx : c10::irange(0, physical_tensors.size())) { + physical_tensors[idx] = apply(physical_tensors[idx]); + } +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyVmapTransforms.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyVmapTransforms.h new file mode 100644 index 0000000000000000000000000000000000000000..b3a26a614bf4d486e0700f0f91f04363c424c88f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/LegacyVmapTransforms.h @@ -0,0 +1,187 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include + +namespace at::functorch { + +// This files contains the legacy (now-deprecated) batching rule API. +// Please try to use the new-style batching rule API (see writing_batch_rules.md) + +// This file contains abstractions used for transforming *logical* vmap arguments +// into *physical* arguments. (Keep reading for definitions of these terms). + +// NOTE: [Logical vs physical args] +// Consider the following vmap. +// vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4)) +// This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4], +// with batch dims 0 and 2: +// BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)]) +// +// We say the *logical* view of the tensor has size [3] -- tensors inside +// `func` appear to have size [3]. +// However, the *physical* underlying tensor (the one passed to vmap) has size +// [2, 3, 4]. +// +// This notion of logical vs physical also extends to non-tensor arguments. +// Consider the previous tensor; let's assume the user called +// `torch.sum(tensor, dim=0)` inside of `func`. Then the logical +// dimension they are reducing over is dim 0 but the physical dim is dim 1 +// (the first non-batch dimension) + +// Forward declared; see NOTE: [What is a VmapPhysicalView?] +struct VmapPhysicalView; + +// Most PyTorch operators take 4 or fewer inputs. +constexpr int64_t kVmapTransformStaticInputSize = 4; +using VmapPhysicalViewVec = SmallVector; + +// Pytorch generally advertises good performance for <= 5 dims. +// (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap +// dimensions to get 8. Adjust this number as necessary +constexpr int64_t kVmapStaticDimVecSize = 8; +using VmapDimVector = SmallVector; +using VmapSymDimVector = SmallVector; + +// NOTE: [What is an VmapTransform?] +// An *VmapTransform* converts logical views of tensors to physical views. +// +// Batching rules use VmapTransforms to convert logical arguments to +// physical arguments, then call one or more at:: operator that handles the +// physical arguments, and then converts the physical result back to a logical +// argument. + +// VmapTransform for operators that take tensors with multiple batch dims. +// Given one or more logical views on Tensors, `logicalToPhysical` +// permutes all of the batch dims to the front of the tensor, aligns +// and expands the batch dims to match each other (according to their `level`), +// and returns a VmapPhysicalView on the tensor(s). +struct TORCH_API MultiBatchVmapTransform { + static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor); + static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors); +}; + +// VmapTransform for operators that broadcast all inputs. +// Given some logical views on Tensors, `logicalToPhysical`: +// - permutes all of the batch dims to the front of the tensors +// - aligns all the batch dims to the collective levels of all of the tensors. +// If a tensor does not have a batch dim for a vmap level, then it receives +// a size-one dimension for said level. +// - aligns the non-batch dims to have the same dimensionality, adding extra +// size-1 dimensions in between the batch dimensions and the non-batch dimensions +// so that the batch dimensions are lined up from the right. +// +// For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch +// dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap tensors +// of size (B, 1, 2) and (B, 3, 2). +// +// Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns +// VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't +// actually *need* to return a tensor of size (1, 2) for the second tensor +// because the broadcasting operation takes care of that for us, but we do +// it anyways to keep things simple. +struct TORCH_API BroadcastingVmapTransform { + static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors); +}; + +// Forward declared, if you're reading this file head to toe, don't worry about +// it yet. +struct VmapPhysicalToLogicalMap; + +// NOTE: [What is a VmapPhysicalView?] +// VmapPhysicalView represents a physical view on a Tensor. +// +// One can use it to further convert logical dimension indices, logical shapes, +// and more to their physical variants, or convert a new (physical) tensor into +// a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented). +// +// VmapPhysicalView stores a physical tensor with all of its batch dimensions at +// the front and some levels that correspond to said batch dimensions. +// +// The levels bitset specifies which vmap levels correspond to the batch +// dimensions at the front of the tensor. In particular, the number of set bits +// corresponds to the number of batch dimensions on `tensor` and the rightmost +// bit of `levels` specifies the maximum number of nested vmaps we are in at +// this point in time. +// For example, given: +// physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3}) +// +// Rightmost bit of `levels` is 3 indicating the number of nested vmaps less +// than or equal to 3. +// bitset: 010100 +// ^ +// | +// levels: 012345 +struct TORCH_API VmapPhysicalView { + VmapPhysicalView(Tensor&& tensor, std::bitset levels) + : levels_(levels), tensor_(std::move(tensor)) { + // TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor)); + } + + Tensor& tensor() { return tensor_; } + const Tensor& tensor() const { return tensor_; } + + // Maps logical dim indices to physical dim indices. Also does dim wrapping. + // + // For example, given: + // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3}) + // + // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}. + // This is because the size of levels tell us that the first two dimensions + // of `tensor_` are batch dimensions, so a logical dim of `n` is actually + // a physical dim of `n + 2`. + VmapDimVector getPhysicalDims(IntArrayRef logical_dims) const; + int64_t getPhysicalDim(int64_t logical_dim) const; + + // Returns a VmapPhysicalToLogicalMap object. This can be used for + // mapping a physical tensor to a new logical tensor (BatchedTensor) + VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const; + + // Maps a logical shape to a physical shape by prepending the batch + // sizes to the logical shape. + VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const; + SymDimVector getPhysicalShape(c10::SymIntArrayRef logical_shape) const; + + int64_t numBatchDims() const; + + private: + int64_t numLogicalDims() const; + + std::bitset levels_; + Tensor tensor_; +}; + +// Convenience struct used for mapping a physical tensor (a non-BatchedTensor) +// to a logical one (BatchedTensor). It holds some levels that are used to do the +// mapping and assumes that the batch dimensions in the physical tensor all +// occur at the front of the tensor. +struct TORCH_API VmapPhysicalToLogicalMap { + VmapPhysicalToLogicalMap(std::bitset levels): levels_(levels) {} + + // Maps a physical tensor to a new logical tensor (BatchedTensor). + // Assumes that all of the "batch dimensions" are at the front + // of the physical tensor. For example, given: + // - x = rank-4 Tensor with size 2, 3, 5, 7 + // - levels = (2, 4) + // Returns: + // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)]) + Tensor apply(const Tensor& physical_tensor) const; + + // Given a vector of physical tensors, + // 1. maps each tensor to a new logical tensor. Assumes that all of the + // "batch dimensions" are at the front of the physical tensors. + // 2. stores the new logical tensors back into the passed-in vector. This is + // to avoid additional dynamic allocations. + void applyInplace(std::vector& physical_tensors) const; + + std::bitset levels_; +}; + + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/Macros.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/Macros.h new file mode 100644 index 0000000000000000000000000000000000000000..b99be8781c127d5d8c49fdc1b7b80027c9383e48 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/Macros.h @@ -0,0 +1,3 @@ +#pragma once + +#define SINGLE_ARG(...) __VA_ARGS__ diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/PlumbingHelper.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/PlumbingHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b3ecf6584474d07b774548f0e7f64a8b356de5f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/PlumbingHelper.cpp @@ -0,0 +1,94 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +namespace at::functorch { + +void vmap_check_escaped(const std::optional &layer, const char* what) { + TORCH_CHECK( + layer.has_value(), + "Either your tensor may have escaped from inside a function being vmapped and this is a user error ", + "(see https://pytorch.org/functorch/stable/ux_limitations.html), " + "or there is an internal functorch error in `", + what, + "` Please file an issue if it looks like the latter" + ) +} + +Tensor makeBatched(Tensor tensor, std::optional bdim, int64_t level) { + if (bdim.has_value()) { + TORCH_INTERNAL_ASSERT(*bdim >= 0); + TORCH_INTERNAL_ASSERT(*bdim < tensor.dim()); + return makeBatched(std::move(tensor), bdim.value(), level); + } + return tensor; +} + +std::vector makeBatchedVector(std::vector tensors, std::optional bdim, int64_t level) { + std::vector res; + res.reserve(tensors.size()); + for (auto & tensor : tensors) { + res.emplace_back(makeBatched(std::move(tensor), bdim, level)); + } + return res; +} + +std::tuple> unwrapTensorAtLevel(const Tensor& tensor, int64_t level) { + auto* batched = maybeGetBatchedImpl(tensor); + if (!batched) { + return std::make_tuple(tensor, std::nullopt); + } + if (batched->level() == level) { + return std::make_tuple(batched->value(), batched->bdim()); + } + return std::make_tuple(tensor, std::nullopt); +} + +bool isBatchedAtLevel(const Tensor& tensor, int64_t level) { + auto result = unwrapTensorAtLevel(tensor, level); + return std::get<1>(result).has_value(); +} + +bool isBatchedAtLevel(const std::optional& maybe_tensor, int64_t level) { + if (!maybe_tensor.has_value()) { + return false; + } + return isBatchedAtLevel(*maybe_tensor, level); +} + +bool isBatchedAtLevel(ITensorListRef tensors, int64_t level) { + for (const auto& tensor : tensors) { + if (isBatchedAtLevel(tensor, level)) { + return true; + } + } + return false; +} + +bool isBatchedAtLevel(const c10::List>& maybe_tensors, int64_t level) { + for (const auto idx : c10::irange(0, maybe_tensors.size())) { + const auto& maybe_tensor = maybe_tensors.get(idx); + if (isBatchedAtLevel(maybe_tensor, level)) { + return true; + } + } + return false; +} + +bool areAnyBatchedAtLevel(ArrayRef> maybe_tensors, int64_t level) { + for (const auto& maybe_tensor : maybe_tensors) { + if (isBatchedAtLevel(maybe_tensor, level)) { + return true; + } + } + return false; +} + + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/PlumbingHelper.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/PlumbingHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..cd31ffb4553af64b7ab789a9e32d46f95bb8f18e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/PlumbingHelper.h @@ -0,0 +1,63 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. +#pragma once +#include +#include +#include + +// NOTE: [vmap plumbing] +// +// Here's how "batching rules" work. +// - we register kernels to the Batched key +// - these kernels have the same signatures as the original operators. +// For example, at::sin(Tensor self) accepts a Tensor, and the batched kernel +// must also accept a Tensor +// - However, it is more natural for users to write a batching rule like the +// following: sin_batch_rule(Tensor self, std::optional self_bdim) +// - There is some codegenerated layer (the "plumbing") that wraps the user +// defined batching rule (e.g. sin_batch_rule) in a kernel that can be +// registered to the Batched key. +// +// The plumbing is responsible for wrapping a batching rule into a form that may +// be registered as the kernel for the batched key. + +namespace at::functorch { + +void vmap_check_escaped(const std::optional &layer, const char* what); + +// Create a BatchedTensor given a tensor, bdim, and level +TORCH_API Tensor makeBatched(Tensor tensor, std::optional bdim, int64_t level); + +// Given a Tensor that may or may not be a BatchedTensor, unwrap it. +// If `tensor` is not a BatchedTensor, or is a BatchedTensor but the level +// doesn't match, then this returns (tensor, std::nullopt). +// Otherwise, it returns (unwrap(tensor), bdim). +TORCH_API std::tuple> unwrapTensorAtLevel(const Tensor& tensor, int64_t level); + +// Creates a vector of BatchedTensor +TORCH_API std::vector makeBatchedVector(std::vector tensors, std::optional bdim, int64_t level); + +// Returns True if ANY tensor in tensors is batched at level +TORCH_API bool isBatchedAtLevel(ITensorListRef tensors, int64_t level); +TORCH_API bool isBatchedAtLevel(const c10::List>& maybe_tensors, int64_t level); +TORCH_API bool isBatchedAtLevel(const Tensor& tensor, int64_t level); +TORCH_API bool isBatchedAtLevel(const std::optional& maybe_tensor, int64_t level); + +// Convenience helper. Returns true if any tensor is batched at level +TORCH_API bool areAnyBatchedAtLevel(ArrayRef> maybe_tensors, int64_t level); + +inline bool ivalueParticipatesInCurrentLevel(const IValue& ivalue) { + if (ivalue.isTensor()) { + auto maybe_level = maybeCurrentDynamicLayer(); + TORCH_INTERNAL_ASSERT(maybe_level.has_value()); + auto current_level = maybe_level->layerId(); + return isBatchedAtLevel(ivalue.toTensor(), current_level); + } + // TODO: should really check this + return false; +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/PyTorchOperatorHacks.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/PyTorchOperatorHacks.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8805c600e8b8b8da78f61e7604a5f5a63de2461b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/PyTorchOperatorHacks.cpp @@ -0,0 +1,278 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::functorch { + +// NOTE: [functorch's PyTorch Operator Hacks] +// +// This file contains hacks for composite PyTorch operators that are problematic. +// For example, the composite op might have in-place operations, +// or call data_ptr. We have some idea of how to fix these things in the long term +// e.g., upstream the changes to PyTorch. +// +// TODO: all of these should be fixed in a more blessed way. In particular, +// it is bad if any of these go out-of-sync with the implementations in +// pytorch/pytorch. + +// TODO: upstream into core + +namespace { +Tensor index_select_backward_hack( + const Tensor& grad, + c10::SymIntArrayRef self_sizes, + int64_t dim, + const Tensor& index) { + return at::zeros_symint(self_sizes, grad.options()).index_add(dim, index, grad); +} + +// TODO: linear is pretty important for performance, but I'm not sure how to work +// around the in-place. +Tensor linear_hack(const Tensor& input, const Tensor& weight, const std::optional& bias_opt) { + // See [Note: hacky wrapper removal for optional tensor] + auto bias = bias_opt.has_value() + ? c10::MaybeOwned::borrowed(*bias_opt) + : c10::MaybeOwned::owned(std::in_place); + + if (input.is_mkldnn()) { + return at::mkldnn_linear(input, weight, *bias); + } +#if defined(C10_MOBILE) + if (at::native::xnnpack::use_linear(input, weight, *bias)) { + return at::native::xnnpack::linear(input, weight, *bias); + } +#endif + if (input.dim() == 2 && bias->defined()) { + // Fused op is marginally faster. + return at::addmm(*bias, input, weight.t()); + } + if (input.dim() == 3 && bias->defined() && input.is_contiguous()) { + // Also hit the fused path for contiguous 3D input. + const auto input_sizes = input.sizes(); + const auto result = at::addmm(*bias, input.view({input_sizes[0] * input_sizes[1], input_sizes[2]}), weight.t()); + return result.view({input_sizes[0], input_sizes[1], result.size(1)}); + } + auto output = at::matmul(input, weight.t()); + if (bias->defined()) { + const auto& stack = getDynamicLayerStack(); + bool any_vmap_layers = std::any_of( + stack.begin(), stack.end(), + [](const DynamicLayer& dl){ return dl.key() == TransformType::Vmap; }); + if (any_vmap_layers) { + return output.add(*bias); + } + return output.add_(*bias); + } + return output; +} + +inline at::Tensor apply_loss_reduction(const at::Tensor& unreduced, int64_t reduction) { + if (reduction == at::Reduction::Mean) { + return unreduced.mean(); + } else if (reduction == at::Reduction::Sum) { + return unreduced.sum(); + } + return unreduced; +} + +Tensor binary_cross_entropy_with_logits_hack( + const Tensor& input, + const Tensor& target, + const std::optional& weight_opt, + const std::optional& pos_weight_opt, + int64_t reduction) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + const Tensor& pos_weight = pos_weight_opt.value_or(Tensor()); + + Tensor loss; + auto max_val = (-input).clamp_min(0); + if (pos_weight.defined()) { + // pos_weight need to be broadcasted, thus mul(target) is not inplace. + auto log_weight = (pos_weight - 1).mul(target).add_(1); + loss = (1 - target).mul(input).add(log_weight.mul(((-max_val).exp_().add((-input - max_val).exp_())).log_().add_(max_val))); + } else { + loss = (1 - target).mul(input).add_(max_val).add_((-max_val).exp_().add((-input -max_val).exp_()).log_()); + } + + if (weight.defined()) { + loss = loss * weight; + } + + return apply_loss_reduction(loss, reduction); +} + +Tensor trace_backward_decomp(const Tensor& grad, c10::SymIntArrayRef sizes) { + TORCH_CHECK(sizes.size() == 2, "expected matrix input"); + auto grad_input = at::zeros_symint(sizes[0] * sizes[1], grad.options()); + auto diag_size = std::min(sizes[0], sizes[1]); + auto step = sizes[1] + 1; + auto indices = at::arange(0, diag_size * step, step, grad.options().dtype(at::kLong)); + // Workaround using index_put instead of yet unsupported index_fill_ + grad_input = grad_input.index_put({std::move(indices)}, grad); + return grad_input.view_symint(sizes); +} +} + +// dropout hack +// TODO: make the following changes in pytorch/pytorch +namespace dropout_hack { + +namespace { + +template +using Ctype = std::conditional_t; + +Tensor make_feature_noise(const Tensor& input) { + auto input_sizes = input.sizes(); + TORCH_CHECK(input.dim() >= 2, "Feature dropout requires at least 2 dimensions in the input"); + std::vector sizes; + sizes.reserve(input.dim()); + sizes.push_back(input_sizes[0]); + sizes.push_back(input_sizes[1]); + for ([[maybe_unused]] const auto i : c10::irange(2, input.dim())) { + sizes.push_back(1); + } + // NB: THIS WAS CHANGED FROM THE ORIGINAL + return at::empty(sizes, input.options()); +} + +bool is_fused_kernel_acceptable(const Tensor& input, double p) { + return (input.is_cuda() || input.is_xpu() || input.is_lazy() || input.is_privateuseone()) && p > 0 && p < 1 && input.numel() > 0; +} + +// NB: sure, we could have used different overloads here, but I would feel insecure +// knowing that this dispatch depends only on the constness of the references +template +Tensor& multiply(Tensor& input, const Tensor& noise) { + static_assert(inplace, "Wrong multiply overload triggered in Dropout.cpp"); + return input.mul_(noise); +} + +template +Tensor multiply(const Tensor& input, const Tensor& noise) { + static_assert(!inplace, "Wrong multiply overload triggered in Dropout.cpp"); + return input.mul(noise); +} + +template +Ctype _dropout_impl(T& input, double p, bool train) { + TORCH_CHECK(p >= 0 && p <= 1, "dropout probability has to be between 0 and 1, but got ", p); + if (p == 0 || !train || input.numel() == 0) { + return input; + } + + if (p == 1) { + return multiply(input, at::zeros({}, input.options())); + } + + at::Tensor b; // used for alpha_dropout only + + // NB: THIS WAS CHANGED FROM THE ORIGINAL + Tensor noise; + if (feature_dropout) { + auto empty = make_feature_noise(input); + noise = at::bernoulli(empty, 1 - p); + } else { + // NB: it is important that this is at::empty and not at::empty_like + auto empty = at::empty({}, input.options()).expand(input.sizes()); + noise = at::bernoulli(empty, 1 - p); + } + + if (alpha_dropout) { + constexpr double alpha = 1.7580993408473766; + double a = 1. / std::sqrt((alpha * alpha * p + 1) * (1 - p)); + b = noise.add(-1).mul_(alpha * a).add_(alpha * a * p); + noise.mul_(a); + } else { + noise.div_(1 - p); + } + + if (!alpha_dropout) { + return multiply(input, noise); + } else { + return multiply(input, noise).add_(b); + } +} + +#define ALIAS_SPECIALIZATION(ALIAS_NAME, IS_FEATURE, IS_ALPHA) \ +template \ +Ctype ALIAS_NAME(Args&&... args) { \ + return _dropout_impl(std::forward(args)...); \ +} + +ALIAS_SPECIALIZATION(_dropout, false, false) +ALIAS_SPECIALIZATION(_feature_dropout, true, false) +ALIAS_SPECIALIZATION(_alpha_dropout, false, true ) +ALIAS_SPECIALIZATION(_feature_alpha_dropout, true, true ) + +Tensor dropout(const Tensor& input, double p, bool train) { + auto result = [&]() { + if (train && is_fused_kernel_acceptable(input, p)) { + return std::get<0>(at::native_dropout(input, p, train)); + } + return _dropout(input, p, train); + }(); + return result; +} + +Tensor& dropout_(Tensor& input, double p, bool train) { + return _dropout(input, p, train); +} + +Tensor feature_dropout(const Tensor& input, double p, bool train) { + return _feature_dropout(input, p, train); +} + +Tensor& feature_dropout_(Tensor& input, double p, bool train) { + return _feature_dropout(input, p, train); +} + +Tensor alpha_dropout(const Tensor& input, double p, bool train) { + return _alpha_dropout(input, p, train); +} + +Tensor& alpha_dropout_(Tensor& input, double p, bool train) { + return _alpha_dropout(input, p, train); +} + +Tensor feature_alpha_dropout(const Tensor& input, double p, bool train) { + return _feature_alpha_dropout(input, p, train); +} + +Tensor& feature_alpha_dropout_(Tensor& input, double p, bool train) { + return _feature_alpha_dropout(input, p, train); +} + +} +} // dropout_hack + +TORCH_LIBRARY_IMPL(aten, FuncTorchDynamicLayerFrontMode, m) { + m.impl("index_select_backward", index_select_backward_hack); + m.impl("linear", linear_hack); + m.impl("binary_cross_entropy_with_logits", binary_cross_entropy_with_logits_hack); + m.impl("trace_backward", trace_backward_decomp); + + m.impl("dropout", dropout_hack::dropout); + m.impl("feature_dropout", dropout_hack::feature_dropout); + m.impl("alpha_dropout", dropout_hack::alpha_dropout); + m.impl("feature_alpha_dropout", dropout_hack::feature_alpha_dropout); + + m.impl("dropout_", dropout_hack::dropout_); + m.impl("feature_dropout_", dropout_hack::feature_dropout_); + m.impl("alpha_dropout_", dropout_hack::alpha_dropout_); + m.impl("feature_alpha_dropout_", dropout_hack::feature_alpha_dropout_); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/TensorWrapper.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/TensorWrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a71577e5231c8d55b8777e47c0c3e0d26b05d8fc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/TensorWrapper.cpp @@ -0,0 +1,214 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include +#include + +#include +#include + +#include + +namespace at::functorch { + +void dumpTensor(std::ostream& ss, const Tensor& tensor) { + auto* wrapped = maybeGetTensorWrapper(tensor); + if (!wrapped) { + auto* batched = maybeGetBatchedImpl(tensor); + if (batched) { + ss << "Batched[lvl=" << batched->level() << " dim=" << batched->bdim() << ", "; + dumpTensor(ss, batched->value()); + ss << ']'; + return; + } + ss << "Tensor" << tensor.sizes(); + return; + } + ss << "Wrapper["; + auto level = wrapped->level(); + if (level.has_value()) { + ss << "lvl=" << level.value() << ", "; + } else { + ss << "dead, "; + } + dumpTensor(ss, wrapped->value()); + ss << ']'; +} + +void TensorWrapper::refreshMetadata() { + // update size, strides and storage_offset + set_sizes_and_strides( + value_.sym_sizes(), value_.sym_strides(), value_.sym_storage_offset()); + + refresh_numel(); + refresh_contiguous(); +} + +void dumpTensorCout(const Tensor& tensor) { + dumpTensor(std::cout, tensor); + + std::cout << '\n'; +} + +static c10::intrusive_ptr makeTensorWrapperPtr(const Tensor& tensor, int64_t level, const std::shared_ptr& life_handle) { + auto keys_to_propagate = kKeysToPropagateToWrapper | DispatchKeySet({ + DispatchKey::AutogradCPU, DispatchKey::AutogradCUDA, DispatchKey::AutogradXLA, + DispatchKey::AutogradPrivateUse1}); + auto key_set = getKeysToPropagateToWrapper(tensor, keys_to_propagate); + key_set = key_set.add(DispatchKey::FuncTorchGradWrapper); + return c10::make_intrusive(key_set, tensor, level, life_handle); +} + +// use makeTensorWrapper instead to avoid potential footguns: +// unsafeMakeTensorWrapper doesn't check that level and life_handle +// refer to the same interpreter +static Tensor unsafeMakeTensorWrapper( + const Tensor& tensor, + int64_t level, + bool is_immutable, + const std::shared_ptr& life_handle) { + auto wrapped = maybeGetTensorWrapper(tensor); + if (wrapped) { + TORCH_INTERNAL_ASSERT(wrapped->level() < level); + } + + auto keys_to_propagate = kKeysToPropagateToWrapper | DispatchKeySet({ + DispatchKey::AutogradCPU, DispatchKey::AutogradCUDA, DispatchKey::AutogradXLA, + DispatchKey::AutogradPrivateUse1}); + auto key_set = getKeysToPropagateToWrapper(tensor, keys_to_propagate); + key_set = key_set.add(DispatchKey::FuncTorchGradWrapper); + auto result = at::detail::make_tensor( + key_set, tensor, level, life_handle, is_immutable); + TORCH_INTERNAL_ASSERT(result.key_set().has(DispatchKey::FuncTorchGradWrapper)); + + if (tensor.unsafeGetTensorImpl()->is_wrapped_number()) { + result.unsafeGetTensorImpl()->set_wrapped_number(true); + } + + return result; +} + +Tensor makeTensorWrapper(const Tensor& tensor, int64_t level, bool is_immutable) { + auto life_handle = getLifeHandleForLevel(level); + return unsafeMakeTensorWrapper( + tensor, + level, + is_immutable, + getLifeHandleForLevel(level)); +} + +Tensor makeTensorWrapper(const Tensor& tensor, const Interpreter& interpreter, bool is_immutable) { + return unsafeMakeTensorWrapper( + tensor, + interpreter.level(), + is_immutable, + interpreter.is_alive_ptr()); +} + + +bool TensorWrapper::is_alive() const { + return *is_alive_; +} + +c10::intrusive_ptr TensorWrapper::shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const { + auto dest_impl = makeTensorWrapperPtr(value(), level_, is_alive_); + dest_impl->set_version_counter(version_counter); + + // TODO: is this even right? + dest_impl->set_allow_tensor_metadata_change(allow_tensor_metadata_change); + return dest_impl; +} + +c10::intrusive_ptr TensorWrapper::shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const { + auto dest_impl = makeTensorWrapperPtr(value(), level_, is_alive_); + dest_impl->set_version_counter(std::move(version_counter)); + + // TODO: is this even right? + dest_impl->set_allow_tensor_metadata_change(allow_tensor_metadata_change); + return dest_impl; +} + +void TensorWrapper::shallow_copy_from(const c10::intrusive_ptr& impl) { + TORCH_CHECK(false, "mutating directly with `.data` inside functorch transform is not allowed."); +} + +TensorWrapper::TensorWrapper( + c10::DispatchKeySet key_set, + Tensor value, + int64_t level, + std::shared_ptr is_alive, + bool is_immutable, + bool use_value_sizes_strides) + : TensorImpl(key_set, value.dtype(), value.device()) + , value_(std::move(value)) + , level_(level) + , is_immutable_(is_immutable) + , is_alive_(std::move(is_alive)) +{ + TORCH_INTERNAL_ASSERT(value_.defined()); + + // TODO: need to reset sizes/strides on mutation + TORCH_INTERNAL_ASSERT(use_value_sizes_strides); + refreshMetadata(); + + set_storage_access_should_throw(); +} + +const char* TensorWrapper::tensorimpl_type_name() const { + return "TensorWrapper"; +} + + +TensorWrapper* maybeGetTensorWrapper(const Tensor& tensor) { + if (!tensor.key_set().has(DispatchKey::FuncTorchGradWrapper)) { + return nullptr; + } + return (TensorWrapper*)(tensor.unsafeGetTensorImpl()); +} + +static void dead_tensor_wrapper_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + auto args_size = op.schema().arguments().size(); + int64_t unwrapped_count = 0; + auto unwrapIfDeadAndIncrement = [&](const Tensor& tensor) { + auto* wrapped = maybeGetTensorWrapper(tensor); + if (!wrapped) { + return tensor; + } + + // NOTE: We need to test for both is_alive and functorch mode dispatch keys + // being active because certain ops may disable the keys but not set + // the relevant tensor's state to dead. + // Example: torch.tensor([x, y, z]) - variant which accepts list of scalars + // leads to the above case. + constexpr auto functorch_mode_ks = DispatchKeySet( + {DispatchKey::FuncTorchDynamicLayerFrontMode, + DispatchKey::FuncTorchDynamicLayerBackMode}); + if (wrapped->is_alive() && wrapped->key_set().has_any(functorch_mode_ks)) { + return tensor; + } + unwrapped_count++; + return wrapped->value(); + }; + + foreachTensorInplace(*stack, static_cast(stack->size() - args_size), static_cast(stack->size()), unwrapIfDeadAndIncrement); + TORCH_INTERNAL_ASSERT(unwrapped_count > 0, "Should have at least one dead wrapper"); + + // re-dispatch + op.callBoxed(stack); +} + +// TensorWrapper backend fallback: Unwrap and fallthrough. + +TORCH_LIBRARY_IMPL(_, FuncTorchGradWrapper, m) { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&dead_tensor_wrapper_fallback>()); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/TensorWrapper.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/TensorWrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..30b8c6343aed84208e215c1daaf2e68a1c9d8336 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/TensorWrapper.h @@ -0,0 +1,103 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#pragma once + +#include +#include +#include + +namespace at::functorch { + +// NOTE: [functorch's TensorWrapper] +// +// Taking better suggestions for a name. TensorWrapper is the wrapper Tensor +// Subclass for functorch's grad-based transforms (grad, vjp, jvp). It is +// analogous to how vmap uses BatchedTensor as the wrapper Tensor subclass. +// +// If you're familiar with the Tensor-Variable merge, TensorWrapper is effectively +// another Variable. +// +// Consider grad(grad(torch.sin))(x). This wraps `x` as TensorWrapper(TensorWrapper(x)). +// The reason why is so that each TensorWrapper can hold its own AutogradMeta and +// participate in a **separate** autograd graph. +// +// There are alternative designs we could have chosen (e.g. each grad transform +// stores a weak map of Tensor -> AutogradMeta); the benefit of the TensorWrapper +// design is that we can reuse existing VariableType kernels (i.e. Autograd kernels) +// without much modification. Since a TensorWrapper looks like a regular Tensor, +// the VariableType kernel can pull out the AutogradMeta struct from where it +// expects and extend the autograd graph + +struct TORCH_API TensorWrapper : public c10::TensorImpl { + explicit TensorWrapper( + c10::DispatchKeySet key_set, + Tensor value, + int64_t level, + std::shared_ptr is_alive, + bool is_immutable = false, // if true, this came from an operation that aliases an immutable tensor + bool use_value_sizes_strides = true); + + void refreshMetadata(); + + const Tensor& value() const { + return value_; + } + std::optional level() const { + if (is_alive()) { + return level_; + } + return {}; + } + bool is_immutable() const { + return is_immutable_; + } + bool is_alive() const; + + // Overrides necessary for autograd + c10::intrusive_ptr shallow_copy_and_detach( + const c10::VariableVersion& version_counter, + bool allow_tensor_metadata_change) const override; + c10::intrusive_ptr shallow_copy_and_detach( + c10::VariableVersion&& version_counter, + bool allow_tensor_metadata_change) const override; + void shallow_copy_from(const c10::intrusive_ptr& impl) override; + + private: + const char* tensorimpl_type_name() const override; + Tensor value_; + int64_t level_; + bool is_immutable_; + + // TensorWrapper receives a boolean flag on whether or not the Grad Interpreter + // that created it is still alive or not. + // If the Grad Interpreter is no longer alive then it attempts to behave like + // a regular Tensor. + // + // When we exit the level, this wrapper may be marked as "not alive". + // Wrappers that are not alive: + // 1) May still have autograd metadata on them + // 2) Forward dispatches to the underlying value() + std::shared_ptr is_alive_; +}; + +// There are two variants of makeTensorWrapper: one that accepts a level +// and one that accepts an Interpreter. +// +// The one that accepts a level tries to automatically get the life handle from the +// interpreter on the DynamicLayerStack. +// It needs to be used with caution: if the interpreter is not on the +// DynamicLayerStack, then we won't be able to find the life handle. +// +// In practice this isn't a problem: when we're constructing TensorWrapper in +// Python, the corresponding interpreter is on the stack. +TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, int64_t level, bool is_immutable=false); +TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, const Interpreter& interpreter, bool is_immutable=false); +TORCH_API TensorWrapper* maybeGetTensorWrapper(const Tensor& tensor); +TORCH_API void dumpTensor(std::ostream & ss, const Tensor& tensor); +TORCH_API void dumpTensorCout(const Tensor& tensor); + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapInterpreter.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapInterpreter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf696a19db92a118aec1fefe8f50709481fc7e9c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapInterpreter.cpp @@ -0,0 +1,24 @@ +#include +#include + +namespace at::functorch { + +void VmapInterpreterPtr::processImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack) { + setup_dispatch_key_tls(TransformType::Vmap, DispatchKeySet(DispatchKey::FuncTorchVmapMode)); + op.callBoxed(stack); +} + +void VmapInterpreterPtr::sendToNextInterpreterImpl( + const c10::OperatorHandle& op, + torch::jit::Stack* stack, + bool grad_special_case) { + // Re-dispatch + if (getDynamicLayerStack().empty()) { + sanityCheckStack(op, stack); + } + op.callBoxed(stack); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapInterpreter.h b/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapInterpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..8a2539e24faeae1308dc8376bfc3a2b15d438179 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapInterpreter.h @@ -0,0 +1,25 @@ +#pragma once +#include + +namespace at::functorch { + +// This is the interpreter that handles the functionalize() transform. +// See NOTE: [functorch interpreter stack] for more details. + +struct VmapInterpreterPtr { + explicit VmapInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Vmap); } + TransformType key() const { return base_->key(); } + int64_t level() const { return base_->level(); } + void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack); + void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case); + c10::SymInt batchSize() const { + return std::get(base_->meta()).batchSize_; + } + RandomnessType randomness() const { + return std::get(base_->meta()).randomness_; + } + private: + const Interpreter* base_; +}; + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapModeRegistrations.cpp b/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapModeRegistrations.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d22c1079a8e77f1961051789d82f7c1190d0074 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/functorch/VmapModeRegistrations.cpp @@ -0,0 +1,65 @@ +// Copyright (c) Facebook, Inc. and its affiliates. +// All rights reserved. +// +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. + +#include +#include + +// functorch's vmap has two Dispatch Keys that implement it: +// FuncTorchBatched and FuncTorchVmapMode. This file contains registrations for +// FuncTorchVmapMode -- these registrations are to error out on operations +// that we don't support on regular Tensors. + +namespace at::functorch { + +static void unsupportedRandomOp(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, "vmap: We do not support calling out variants of random operations inside of vmap. ", + "Please use non-out variants as a workaround"); +} + +TORCH_LIBRARY_IMPL(_, FuncTorchVmapMode, m) { + m.fallback(torch::CppFunction::makeFallthrough()); +} + +static void nyiRandomOp(const c10::OperatorHandle& op, torch::jit::Stack* stack) { + TORCH_CHECK(false, "vmap: we do not yet support ", op.schema().operator_name(), + ". Please file an issue"); +} + +#define UNSUPPORTED_RANDOM(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction<&unsupportedRandomOp>()); + +#define UNSUPPORTED_RANDOM2(op, overload) \ + m.impl(#op"."#overload, torch::CppFunction::makeFromBoxedFunction<&unsupportedRandomOp>()); + +#define NYI_RANDOM(op) \ + m.impl(#op, torch::CppFunction::makeFromBoxedFunction<&nyiRandomOp>()); + +#define NYI_RANDOM2(op, overload) \ + m.impl(#op"."#overload, torch::CppFunction::makeFromBoxedFunction<&nyiRandomOp>()); + +TORCH_LIBRARY_IMPL(aten, FuncTorchVmapMode, m) { + UNSUPPORTED_RANDOM2(bernoulli, out); + UNSUPPORTED_RANDOM2(rand, generator_out); + UNSUPPORTED_RANDOM2(rand, out); + UNSUPPORTED_RANDOM2(randint, generator_out); + UNSUPPORTED_RANDOM2(randint, out); + UNSUPPORTED_RANDOM2(randn, generator_out); + UNSUPPORTED_RANDOM2(randn, out); + UNSUPPORTED_RANDOM2(randperm, generator_out); + UNSUPPORTED_RANDOM2(randperm, out); + UNSUPPORTED_RANDOM2(multinomial, out); + UNSUPPORTED_RANDOM2(normal, float_Tensor_out); + UNSUPPORTED_RANDOM2(normal, Tensor_Tensor_out); + UNSUPPORTED_RANDOM2(normal, float_float_out); + UNSUPPORTED_RANDOM2(rrelu_with_noise, out); + + NYI_RANDOM(rrelu_with_noise); + NYI_RANDOM(rrelu_with_noise_); + NYI_RANDOM(rrelu_); + NYI_RANDOM(rrelu); +} + +} // namespace at::functorch diff --git a/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h new file mode 100644 index 0000000000000000000000000000000000000000..ed30ad966b01f9f1ec580a5507a47b1822392df0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h @@ -0,0 +1,242 @@ +#pragma once + +#include + +// Use of c10::hip namespace here makes hipification easier, because +// I don't have to also fix namespaces. Sorry! +namespace c10::hip { + +// NB: THIS SHOULD NOT BE USED +// I couldn't find anywhere it was used in public pytorch sources or downstream projects. +// But to avoid risk in removing it, it's still here. + +// Takes a valid HIPAllocator (of any sort) and turns it into +// an allocator pretending to be a CUDA allocator. See +// Note [Masquerading as CUDA] +class HIPAllocatorMasqueradingAsCUDA final : public HIPCachingAllocator::HIPAllocator { + HIPCachingAllocator::HIPAllocator* allocator_; +public: + explicit HIPAllocatorMasqueradingAsCUDA(HIPCachingAllocator::HIPAllocator* allocator) + : allocator_(allocator) {} + + virtual ~HIPAllocatorMasqueradingAsCUDA() = default; + + // From c10::Allocator + + DataPtr allocate(size_t size) override { + return allocator_->allocate(size); + } + + bool is_simple_data_ptr(const DataPtr& data_ptr) const override { + return allocator_->is_simple_data_ptr(data_ptr); + } + + DeleterFnPtr raw_deleter() const override { + return allocator_->raw_deleter(); + } + + void copy_data(void* dest, const void* src, std::size_t count) const final { + allocator_->copy_data(dest, src, count); + } + + // From DeviceAllocator + + bool initialized() override { + return allocator_->initialized(); + } + + void emptyCache(MempoolId_t mempool_id = {0, 0}) override { + allocator_->emptyCache(mempool_id); + } + + void recordStream(const DataPtr& ptr, c10::Stream stream) override { + HIPStream hip_stream = HIPStream(stream); + recordStream(ptr, hip_stream); + } + + CachingDeviceAllocator::DeviceStats getDeviceStats(c10::DeviceIndex device) override { + return allocator_->getDeviceStats(device); + } + + void resetAccumulatedStats(c10::DeviceIndex device) override { + allocator_->resetAccumulatedStats(device); + } + + void resetPeakStats(c10::DeviceIndex device) override { + allocator_->resetPeakStats(device); + } + + // From CUDAAllocator + + void* raw_alloc(size_t nbytes) override { + return allocator_->raw_alloc(nbytes); + } + + void* raw_alloc_with_stream(size_t nbytes, hipStream_t stream) override { + return allocator_->raw_alloc_with_stream(nbytes, stream); + } + + void raw_delete(void* ptr) override { + allocator_->raw_delete(ptr); + } + + void init(int device_count) override { + allocator_->init(device_count); + } + + double getMemoryFraction(c10::DeviceIndex device) override { + return allocator_->getMemoryFraction(device); + } + + void setMemoryFraction(double fraction, c10::DeviceIndex device) override { + allocator_->setMemoryFraction(fraction, device); + } + + std::vector getExpandableSegmentSizes(c10::DeviceIndex device) override { + return allocator_->getExpandableSegmentSizes(device); + } + + void enable(bool value) override { + allocator_->enable(value); + } + + bool isEnabled() const override { + return allocator_->isEnabled(); + } + + void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) override { + allocator_->cacheInfo(device, largestBlock); + } + + void* getBaseAllocation(void* ptr, size_t* size) override { + return allocator_->getBaseAllocation(ptr, size); + } + + void recordStream(const DataPtr& ptr, HIPStream stream) override { + allocator_->recordStream(ptr, stream); + } + + HIPCachingAllocator::SnapshotInfo snapshot(MempoolId_t mempool_id = {0, 0}, bool include_traces = true) override { + return allocator_->snapshot(mempool_id, include_traces); + } + + void beginAllocateToPool( + c10::DeviceIndex device, + MempoolId_t mempool_id, + std::function filter) override { + allocator_->beginAllocateToPool(device, mempool_id, filter); + } + + void endAllocateToPool( + c10::DeviceIndex device, + MempoolId_t mempool_id) override { + allocator_->endAllocateToPool(device, mempool_id); + } + + void releasePool(c10::DeviceIndex device, MempoolId_t mempool_id) override { + allocator_->releasePool(device, mempool_id); + } + + int getPoolUseCount(c10::DeviceIndex device, MempoolId_t mempool_id) override { + return allocator_->getPoolUseCount(device, mempool_id); + } + + void createOrIncrefPool( + c10::DeviceIndex device, + MempoolId_t mempool_id, + std::shared_ptr allocator = nullptr) override { + allocator_->createOrIncrefPool(device, mempool_id, std::move(allocator)); + } + + void setUseOnOOM(c10::DeviceIndex device, MempoolId_t mempool_id, bool use_on_oom) override { + allocator_->setUseOnOOM(device, mempool_id, use_on_oom); + } + + void setNoSplit(c10::DeviceIndex device, MempoolId_t mempool_id) override { + allocator_->setNoSplit(device, mempool_id); + } + + bool checkPoolLiveAllocations( + c10::DeviceIndex device, + MempoolId_t mempool_id, + const std::unordered_set& expected_live_allocations) override { + return allocator_->checkPoolLiveAllocations(device, mempool_id, expected_live_allocations); + } + + HIPCachingAllocator::ShareableHandle shareIpcHandle(void* ptr) override { + return allocator_->shareIpcHandle(ptr); + } + + std::shared_ptr getIpcDevPtr(std::string handle) override { + return allocator_->getIpcDevPtr(handle); + } + + bool isHistoryEnabled() override { + return allocator_->isHistoryEnabled(); + } + + void recordHistory( + bool enabled, + HIPCachingAllocator::CreateContextFn context_recorder, + size_t alloc_trace_max_entries, + HIPCachingAllocator::RecordContext when, + bool clearHistory, + const std::vector& skip_actions) override { + allocator_->recordHistory(enabled, context_recorder, alloc_trace_max_entries, when, clearHistory, skip_actions); + } + + void recordAnnotation( + const std::vector>& md) override { + allocator_->recordAnnotation(md); + } + + void pushCompileContext(std::string& md) override { + allocator_->pushCompileContext(md); + } + + void popCompileContext() override { + allocator_->popCompileContext(); + } + + void attachOutOfMemoryObserver(HIPCachingAllocator::OutOfMemoryObserver observer) override { + allocator_->attachOutOfMemoryObserver(observer); + } + + void attachAllocatorTraceTracker(HIPCachingAllocator::AllocatorTraceTracker tracker) override { + allocator_->attachAllocatorTraceTracker(tracker); + } + + void enablePeerAccess(c10::DeviceIndex dev, c10::DeviceIndex dev_to_access) override { + allocator_->enablePeerAccess(dev, dev_to_access); + } + + hipError_t memcpyAsync( + void* dst, + int dstDevice, + const void* src, + int srcDevice, + size_t count, + hipStream_t stream, + bool p2p_enabled) override { + return allocator_->memcpyAsync(dst, dstDevice, src, srcDevice, count, stream, p2p_enabled); + } + + std::shared_ptr getCheckpointState( + c10::DeviceIndex device, + MempoolId_t id) override { + return allocator_->getCheckpointState(device, id); + } + + HIPCachingAllocator::CheckpointDelta setCheckpointPoolState( + c10::DeviceIndex device, + std::shared_ptr pps) override { + return allocator_->setCheckpointPoolState(device, pps); + } + + std::string name() override { + return allocator_->name(); + } + +}; + +} // namespace c10::hip diff --git a/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.cpp b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a0f1d4af3da5354e0e7286192113186f4ef5797 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.cpp @@ -0,0 +1,16 @@ +#include +#include + +namespace c10 { namespace hip { +namespace HIPCachingAllocatorMasqueradingAsCUDA { + +c10::cuda::CUDACachingAllocator::CUDAAllocator* get() { + return c10::cuda::CUDACachingAllocator::get(); +} + +void recordStreamMasqueradingAsCUDA(const DataPtr& ptr, HIPStreamMasqueradingAsCUDA stream) { + c10::cuda::CUDACachingAllocator::recordStream(ptr, stream); +} + +} // namespace HIPCachingAllocatorMasqueradingAsCUDA +}} // namespace c10::hip diff --git a/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h new file mode 100644 index 0000000000000000000000000000000000000000..1280b3da5789e8ee1a2e6d25b4fb2db989da261c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include + +namespace c10 { +// forward declaration +class DataPtr; +namespace hip { +namespace HIPCachingAllocatorMasqueradingAsCUDA { + +TORCH_CUDA_CPP_API c10::cuda::CUDACachingAllocator::CUDAAllocator* get(); +TORCH_CUDA_CPP_API void recordStreamMasqueradingAsCUDA(const DataPtr& ptr, HIPStreamMasqueradingAsCUDA stream); + +using c10::cuda::CUDACachingAllocator::raw_alloc; +using c10::cuda::CUDACachingAllocator::raw_alloc_with_stream; +using c10::cuda::CUDACachingAllocator::raw_delete; +using c10::cuda::CUDACachingAllocator::init; +using c10::cuda::CUDACachingAllocator::getMemoryFraction; +using c10::cuda::CUDACachingAllocator::setMemoryFraction; +using c10::cuda::CUDACachingAllocator::emptyCache; +using c10::cuda::CUDACachingAllocator::enable; +using c10::cuda::CUDACachingAllocator::isEnabled; +using c10::cuda::CUDACachingAllocator::cacheInfo; +using c10::cuda::CUDACachingAllocator::getBaseAllocation; +using c10::cuda::CUDACachingAllocator::getDeviceStats; +using c10::cuda::CUDACachingAllocator::resetAccumulatedStats; +using c10::cuda::CUDACachingAllocator::resetPeakStats; +using c10::cuda::CUDACachingAllocator::snapshot; +using c10::cuda::CUDACachingAllocator::getCheckpointState; +using c10::cuda::CUDACachingAllocator::setCheckpointPoolState; +using c10::cuda::CUDACachingAllocator::beginAllocateToPool; +using c10::cuda::CUDACachingAllocator::endAllocateToPool; +using c10::cuda::CUDACachingAllocator::recordHistory; +using c10::cuda::CUDACachingAllocator::recordAnnotation; +using c10::cuda::CUDACachingAllocator::pushCompileContext; +using c10::cuda::CUDACachingAllocator::popCompileContext; +using c10::cuda::CUDACachingAllocator::isHistoryEnabled; +using c10::cuda::CUDACachingAllocator::checkPoolLiveAllocations; +using c10::cuda::CUDACachingAllocator::attachOutOfMemoryObserver; +using c10::cuda::CUDACachingAllocator::attachAllocatorTraceTracker; +using c10::cuda::CUDACachingAllocator::releasePool; +using c10::cuda::CUDACachingAllocator::createOrIncrefPool; +using c10::cuda::CUDACachingAllocator::setUseOnOOM; +using c10::cuda::CUDACachingAllocator::setNoSplit; +using c10::cuda::CUDACachingAllocator::getPoolUseCount; +using c10::cuda::CUDACachingAllocator::getIpcDevPtr; +using c10::cuda::CUDACachingAllocator::shareIpcHandle; +using c10::cuda::CUDACachingAllocator::name; +using c10::cuda::CUDACachingAllocator::memcpyAsync; +using c10::cuda::CUDACachingAllocator::enablePeerAccess; +} // namespace HIPCachingAllocatorMasqueradingAsCUDA +} // namespace hip +} // namespace c10 diff --git a/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h new file mode 100644 index 0000000000000000000000000000000000000000..e393b40ea6597a8edaf8348f994114972f30b3bd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include +#include + +// Use of c10::hip namespace here makes hipification easier, because +// I don't have to also fix namespaces. Sorry! +namespace c10 { namespace hip { + +// Note [Masquerading as CUDA] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// How it was before caffe2 was removed from public repos. hipify v1. +// ================================================================== +// +// c10_hip is very easy to understand: it is HIPified from c10_cuda, +// and anywhere you said CUDA, the source code now says HIP. HIPified +// PyTorch is much harder to understand: it is HIPified from regular +// PyTorch, yes, but NO source-to-source translation from CUDA to +// HIP occurs; instead, anywhere we see "CUDA", it actually means "HIP". +// For example, when you use HIPified PyTorch, you say x.cuda() to +// move a tensor onto ROCm device. We call this situation "HIP +// masquerading as CUDA". +// +// This leads to a very awkward situation when we want to call c10_hip +// code from PyTorch, since c10_hip is expecting things to be called +// HIP, but PyTorch is calling them CUDA (masquerading as HIP). To +// fix this impedance mismatch, we have MasqueradingAsCUDA variants +// for all c10_hip classes. These translate between the "HIP" and "CUDA +// masquerading as HIP" worlds. For example, +// HIPGuardImplMasqueradingAsCUDA (this file) provides something like a +// HIPGuardImpl, but it reports its DeviceType as CUDA (e.g., type() +// returns CUDA, getDevice() reports the current HIP device as a CUDA +// device.) +// +// We should be able to delete all of these classes entirely once +// we switch PyTorch to calling a HIP a HIP. +// +// When you add a new MasqueradingAsCUDA class/function, you need to +// also update the rewrite rules in torch/utils/hipify/cuda_to_hip_mappings.py +// +// By the way, note that the cpp file associated with this also +// *overwrites* the entry in the DeviceGuardImpl registry for CUDA with +// this HIP implementation. +// +// How it is now. caffe2 is removed from public repos. hipify v2. +// ============================================================== +// +// c10_hip is very easy to understand: it is HIPified from c10_cuda, +// and anywhere you used a CUDA API, the source now calls a HIP API. +// Classes and namespaces are not renamed from CUDA to HIP et al. +// Filenames do get renamed from CUDA to HIP. This is the same as how PyTorch +// sources are hipified. It is simpler, better. +// +// However, this leads to a challenge that many downstream projects explicitly +// use these v1 Masquerading headers, classes, and symbols. For the purpose of +// backwards-compatible transitions, we maintain these Masquerading +// implementations but they no longer coerce a HIP device to a CUDA device. New +// code should not use Masquerading implementations but instead use the regular +// CUDA classes, for example the CUDAStream class inside c10/hip/HIPStream.h. +// + +struct HIPGuardMasqueradingAsCUDA final : public c10::cuda::CUDAGuard { + using c10::cuda::CUDAGuard::CUDAGuard; +}; + +struct OptionalHIPGuardMasqueradingAsCUDA final : public c10::cuda::OptionalCUDAGuard { + using c10::cuda::OptionalCUDAGuard::OptionalCUDAGuard; +}; + +struct HIPStreamGuardMasqueradingAsCUDA final : public c10::cuda::CUDAStreamGuard { + using c10::cuda::CUDAStreamGuard::CUDAStreamGuard; +}; + +struct OptionalHIPStreamGuardMasqueradingAsCUDA final : public c10::cuda::OptionalCUDAStreamGuard { + using c10::cuda::OptionalCUDAStreamGuard::OptionalCUDAStreamGuard; +}; + +struct HIPMultiStreamGuardMasqueradingAsCUDA final : public c10::cuda::CUDAMultiStreamGuard { + using c10::cuda::CUDAMultiStreamGuard::CUDAMultiStreamGuard; +}; + +}} // namespace c10::hip diff --git a/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h new file mode 100644 index 0000000000000000000000000000000000000000..dce1184c251cdf4fe16f21796808cfc19ccfe063 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h @@ -0,0 +1,41 @@ +#pragma once + +#include + +// Use of c10::hip namespace here makes hipification easier, because +// I don't have to also fix namespaces. Sorry! +namespace c10 { namespace hip { + +// See Note [Masquerading as CUDA] for motivation + +class HIPStreamMasqueradingAsCUDA final : public c10::cuda::CUDAStream { +public: + using c10::cuda::CUDAStream::CUDAStream; + + static HIPStreamMasqueradingAsCUDA unpack3(StreamId stream_id, + DeviceIndex device_index, + c10::DeviceType device_type) { + // NB: constructor manages CUDA->HIP translation for us + return HIPStreamMasqueradingAsCUDA(Stream::unpack3( + stream_id, device_index, device_type)); + } + + // New method, gets the underlying "HIPStream" [CUDAStream] + c10::cuda::CUDAStream hip_stream() const { return *this; } +}; + +inline std::ostream& operator<<(std::ostream& stream, const HIPStreamMasqueradingAsCUDA& s) { + stream << s.hip_stream() << " (masquerading as CUDA)"; + return stream; +} + +}} // namespace c10::hip + +namespace std { + template <> + struct hash { + size_t operator()(c10::hip::HIPStreamMasqueradingAsCUDA s) const noexcept { + return std::hash{}(s.unwrap()); + } + }; +} // namespace std diff --git a/western_ai/usa/pytorch/aten/src/ATen/jit_macros.h b/western_ai/usa/pytorch/aten/src/ATen/jit_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..ce77188ddf0226840810292e226342e70ef80c1f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/jit_macros.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include + +// AT_USE_JITERATOR(), controls whether we jit some elementwise kernels. +// AT_DISABLE_JITERATOR is set by CMake when jiterator should be off. +// Currently set under USE_ROCM + USE_ASAN, because jiterator JITs kernels +// through hiprtc and we haven't set up an ASAN-aware hiprtc runtime. +#ifdef AT_DISABLE_JITERATOR +#define AT_USE_JITERATOR() false +#else +#define AT_USE_JITERATOR() true +#endif +#define jiterator_stringify(...) std::string(#__VA_ARGS__); diff --git a/western_ai/usa/pytorch/aten/src/ATen/jiterator_macros.h b/western_ai/usa/pytorch/aten/src/ATen/jiterator_macros.h new file mode 100644 index 0000000000000000000000000000000000000000..ccde91c67237707108eb61cc0eea38d0768aa2b5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/jiterator_macros.h @@ -0,0 +1,38 @@ +#pragma once +#include +#include + +#define JITERATOR_HOST_DEVICE C10_HOST_DEVICE +#if defined(_MSC_VER) && defined(__CUDACC__) +// NVRTC on Windows errors if __host__ __device__ attribute is +// present on kernel. +// error: attribute "__host__" does not apply here +// error: attribute "__device__" does not apply here +#define JITERATOR_HOST_DEVICE +#endif + +// jiterator_also_stringify_as macro is used to define code (for CPU/ROCm) +// and generate code string for `jiterator` (only when compiling for CUDA). +// Usage : +// jiterator_also_stringify_as( +// jiterator_code(template T identity(T x) { return x; }), +// identity_string); +// This will define the template `identity` as present in code and +// also define `std::string identity_string` with the code as the string +// if this is being compiled for CUDA. + +// `jiterator_code` macro is to deal with `,` in the kernel code. +// These `,`s confuse the preprocessor into thinking we are passing +// multiple arguments to the macro. +#define jiterator_code(...) __VA_ARGS__ +#if defined(__CUDACC__) || defined(__HIPCC__) +// CPU and CUDA and ROCm case +#define stringify_code(...) #__VA_ARGS__ +#define jiterator_also_stringify_as(code, str_name) \ + code /* define the function */ \ + const std::string str_name = std::string(stringify_code(code)); +#else +// CPU only or CPU and ROCm case +// Only needs the function +#define jiterator_also_stringify_as(code, str_name) code +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/metal/Context.cpp b/western_ai/usa/pytorch/aten/src/ATen/metal/Context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f89b9f611eca72ffc38eef4c8edb5ec740880e03 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/metal/Context.cpp @@ -0,0 +1,28 @@ +#include + +#include + +namespace at::metal { + +std::atomic g_metal_impl_registry; + +MetalImplRegistrar::MetalImplRegistrar(MetalInterface* impl) { + g_metal_impl_registry.store(impl); +} + +at::Tensor& metal_copy_(at::Tensor& self, const at::Tensor& src) { + auto p = at::metal::g_metal_impl_registry.load(); + if (p) { + return p->metal_copy_(self, src); + } + TORCH_CHECK(false, "Metal backend was not linked to the build"); +} +} // namespace at::metal + +namespace at::native { +bool is_metal_available() { + auto p = at::metal::g_metal_impl_registry.load(); + return p ? p->is_metal_available() : false; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/metal/Context.h b/western_ai/usa/pytorch/aten/src/ATen/metal/Context.h new file mode 100644 index 0000000000000000000000000000000000000000..2809d15c056cd92ddd4f6ecef5df2a3e58351827 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/metal/Context.h @@ -0,0 +1,32 @@ +#ifndef MetalContext_h +#define MetalContext_h + +#include + +#include + +namespace at::metal { + +struct MetalInterface { + virtual ~MetalInterface() = default; + virtual bool is_metal_available() const = 0; + virtual at::Tensor& metal_copy_(at::Tensor& self, const at::Tensor& src) + const = 0; +}; + +extern std::atomic g_metal_impl_registry; + +class MetalImplRegistrar { + public: + explicit MetalImplRegistrar(MetalInterface* /*impl*/); +}; + +at::Tensor& metal_copy_(at::Tensor& self, const at::Tensor& src); + +} // namespace at::metal + +namespace at::native { +bool is_metal_available(); +} // namespace at::native + +#endif /* MetalContext_h */ diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/AutocastRNN.cpp b/western_ai/usa/pytorch/aten/src/ATen/miopen/AutocastRNN.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9875618381776c59a9807d318d31635e42f38dd8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/AutocastRNN.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +namespace at { +namespace autocast { + +/********************************************************************** +Autocast wrapper for MIOpen RNNs +**********************************************************************/ +std::tuple +miopen_rnn(const Tensor & input_r, + TensorList weight, + int64_t weight_stride0, + const Tensor & hx, + const std::optional& cx_opt, + int64_t fn_mode, + int64_t fn_hidden_size, + int64_t fn_num_layers, + bool batch_first, + double fn_dropout, + bool fn_train, + bool fn_bidirectional, + IntArrayRef fn_batch_sizes, + const std::optional& fn_dropout_state_opt) { + +#if AT_ROCM_ENABLED() + + c10::impl::ExcludeDispatchKeyGuard no_autocast(DispatchKey::Autocast); + + return at::miopen_rnn( + cached_cast(at::kHalf, input_r), + cached_cast(at::kHalf, weight), + weight_stride0, + cached_cast(at::kHalf, hx), + cached_cast(at::kHalf, cx_opt), + fn_mode, + fn_hidden_size, + fn_num_layers, + batch_first, + fn_dropout, + fn_train, + fn_bidirectional, + fn_batch_sizes, + fn_dropout_state_opt); + +#else + TORCH_CHECK(false, "autocast::miopen_rnn: ATen not compiled with ROCm enabled"); + return {Tensor{}, Tensor{}, Tensor{}, Tensor{}, Tensor{}}; // placate the compiler +#endif + +} + +// Register Autocast dispatch +namespace { +TORCH_LIBRARY_IMPL(aten, Autocast, m) { + m.impl("miopen_rnn", + TORCH_FN((&at::autocast::miopen_rnn))); +} +} // anonymous namespace + +} // namespace autocast +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Descriptors.cpp b/western_ai/usa/pytorch/aten/src/ATen/miopen/Descriptors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..104b01020fa159498cc1a8347a79c8f717284798 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Descriptors.cpp @@ -0,0 +1,146 @@ +#include +#include +#include + +#include + +namespace at { namespace native { + +namespace { + +inline miopenDataType_t getDataType(const at::Tensor& t) { + auto scalar_type = t.scalar_type(); + if (scalar_type == at::kFloat) { + return miopenFloat; + } else if (scalar_type == at::kHalf) { + return miopenHalf; + } else if (scalar_type == at::kBFloat16) { + return miopenBFloat16; + } else { + TORCH_CHECK( + false, + "TensorDescriptor does not support ", scalar_type); + } +} + +} // anonymous namespace + +constexpr size_t MIOPEN_DIM_MAX = 5; + +void TensorDescriptor::set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad) { + set(getDataType(t), t.sizes(), t.strides(), pad, + memory_format == at::MemoryFormat::ChannelsLast || + memory_format == at::MemoryFormat::ChannelsLast3d); +} + +void TensorDescriptor::set(const at::Tensor &t, size_t pad) { + auto memory_format = t.suggest_memory_format(); + set(getDataType(t), t.sizes(), t.strides(), pad, + memory_format == at::MemoryFormat::ChannelsLast || + memory_format == at::MemoryFormat::ChannelsLast3d); +} + +void TensorDescriptor::set(miopenDataType_t datatype, IntArrayRef t_sizes, IntArrayRef t_strides, size_t pad) { + set(datatype, t_sizes, t_strides, pad, + is_channels_last_strides_2d(t_sizes, t_strides) || + is_channels_last_strides_3d(t_sizes, t_strides)); +} + +void TensorDescriptor::set(miopenDataType_t datatype, IntArrayRef t_sizes, IntArrayRef t_strides, size_t pad, bool nhwc) { + size_t dim = t_sizes.size(); + if (dim > MIOPEN_DIM_MAX || pad > MIOPEN_DIM_MAX) + TORCH_CHECK(false, "MIOpen supports only up to ", MIOPEN_DIM_MAX, " dimensions"); + // Use size_t (64-bit) to support large tensors with numel > int32_max + size_t size[MIOPEN_DIM_MAX]; + size_t stride[MIOPEN_DIM_MAX]; + for (const auto i : c10::irange(dim)) { + size[i] = static_cast(t_sizes[i]); + stride[i] = static_cast(t_strides[i]); + } + for (const auto i : c10::irange(dim, pad)) { + size[i] = 1; + stride[i] = 1; + } + set(datatype, static_cast(std::max(dim, pad)), size, stride, nhwc); +} + +std::string miopenTypeToString(miopenDataType_t dtype) { + switch (dtype) { + case miopenFloat: + return "miopenFloat"; + case miopenHalf: + return "miopenHalf"; + case miopenBFloat16: + return "miopenBFloat16"; + default: + std::ostringstream oss; + oss << "(unknown data-type " << static_cast(dtype) << ')'; + return oss.str(); + } +} + +std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d) { + out << "TensorDescriptor " << static_cast(d.desc()) << '\n'; + int nbDims = 0; + int dimA[MIOPEN_DIM_MAX]; + int strideA[MIOPEN_DIM_MAX]; + miopenDataType_t dtype; + miopenGetTensorDescriptorSize(d.desc(), &nbDims); + miopenGetTensorDescriptor(d.desc(), &dtype, dimA, strideA); + out << " type = " << miopenTypeToString(dtype) << '\n'; + out << " nbDims = " << nbDims << '\n'; + // Read out only nbDims of the arrays! + out << " dimA = "; + for (auto i : ArrayRef{dimA, static_cast(nbDims)}) { + out << i << ", "; + } + out << '\n'; + out << " strideA = "; + for (auto i : ArrayRef{strideA, static_cast(nbDims)}) { + out << i << ", "; + } + out << '\n'; + return out; +} + +void TensorDescriptor::print() { std::cout << *this; } + +void FilterDescriptor::set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad) { + auto dim = t.ndimension(); + if (dim > MIOPEN_DIM_MAX || pad > MIOPEN_DIM_MAX) + TORCH_CHECK(false, "MIOpen supports only up to ", MIOPEN_DIM_MAX, " dimensions"); + // NB: It is possible for this test to be insufficient, because the + // Tensor passed in to set the filter descriptor may not be the actual + // Tensor whose data pointer is passed to cuDNN. Nevertheless, + // that is the common case, so we can catch most client errors with this test. + TORCH_CHECK(t.is_contiguous(memory_format), + "MIOpen filters (a.k.a. weights) must be contiguous in desired memory_format\n", + "Weight sizes: ", t.sizes(), '\n', + "Weight strides: ", t.strides(), '\n', + "cuDNN suggested memory_format: ", memory_format); + + // Use size_t (64-bit) to support large tensors + size_t size[MIOPEN_DIM_MAX]; + size_t stride[MIOPEN_DIM_MAX]; + for (const auto i : c10::irange(dim)) { + size[i] = static_cast(t.size(i)); + } + for (const auto i : c10::irange(dim, pad)) { + size[i] = 1; + } + + for (int i = pad; i >= dim; --i ) { + stride[i] = 1; + } + for (int i = dim-1 ; i >=0; --i ) { + // Pass-through + stride[i] = static_cast(t.stride(i)); + } + + dim = std::max(dim, pad); + set(getDataType(t), static_cast(dim), size, stride, + memory_format == at::MemoryFormat::ChannelsLast || + memory_format == at::MemoryFormat::ChannelsLast3d); +} + +}} diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Descriptors.h b/western_ai/usa/pytorch/aten/src/ATen/miopen/Descriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..198a27d12480d674efc1dd8093cfe987cf31aa13 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Descriptors.h @@ -0,0 +1,207 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace at { namespace native { + +std::string miopenTypeToString(miopenDataType_t dtype); + +inline int dataSize(miopenDataType_t dataType) +{ + switch (dataType) { + case miopenHalf: return 2; + case miopenFloat: return 4; + case miopenBFloat16: return 2; + default: return 8; + } +} + +// See NOTE [ cudnn fixSizeOneDimStride ] in aten/src/ATen/cudnn/Descriptors.h +template +static inline void fixSizeOneDimStride(int dim, const T *size, T *stride, bool nhwc) { + int64_t z = 1; + int index = 0; + std::vector permutation(dim); + + if (nhwc) { + permutation[index++] = 1; + } + for (int d = dim-1; d > 1; d--) { + permutation[index++] = d; + } + if (!nhwc) { + permutation[index++] = 1; + } + permutation[index++] = 0; + for (int d : permutation) { + if (size[d] == 1) { + stride[d] = z; + } else { + z *= size[d]; + } + } +} + +template +struct DescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + MIOPEN_CHECK(dtor(x)); + } + } +}; + +// A generic class for wrapping MIOpen descriptor types. All you need +// is to give the underlying type the Descriptor_t points to (usually, +// if it's miopenTensorDescriptor_t it points to miopenTensorStruct), +// the constructor and the destructor. Subclasses are responsible +// for defining a set() function to actually set the descriptor. +// +// Descriptors default construct to a nullptr, and have a descriptor +// initialized the first time you call set() or any other initializing +// function. +template +// NOLINTNEXTLINE(bugprone-exception-escape) +class TORCH_CUDA_CPP_API Descriptor { + public: + // Use desc() to access the underlying descriptor pointer in + // a read-only fashion. Most client code should use this. + // If the descriptor was never initialized, this will return + // nullptr. + T* desc() const { return desc_.get(); } + T* desc() { return desc_.get(); } + + // Use mut_desc() to access the underlying descriptor pointer + // if you intend to modify what it points to (e.g., using + // miopenSetFooDescriptor). This will ensure that the descriptor + // is initialized. Code in this file will use this function. + T* mut_desc() { init(); return desc_.get(); } +protected: + void init() { + if (desc_ == nullptr) { + T* raw_desc = nullptr; + MIOPEN_CHECK(ctor(&raw_desc)); + desc_.reset(raw_desc); + } + } +private: + std::unique_ptr> desc_; +}; + +class TORCH_CUDA_CPP_API TensorDescriptor : public Descriptor< + miopenTensorDescriptor, + &miopenCreateTensorDescriptor, + &miopenDestroyTensorDescriptor> { + public: + TensorDescriptor() = default; + explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) { + set(t, pad); + } + + // See Note [CuDNN broadcast padding] + void set(const at::Tensor &t, size_t pad = 0); + void set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad = 0); + void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0); + + void print(); + +private: + void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad, bool nhwc); + + void set(miopenDataType_t dataType, int dim, size_t* size, size_t* stride, bool nhwc) { + std::vector strides_copy(stride, stride + dim); + fixSizeOneDimStride(dim, size, strides_copy.data(), nhwc); + // Use V2 API which supports 64-bit size/stride for large tensors + MIOPEN_CHECK(miopenSetTensorDescriptorV2(mut_desc(), dataType, dim, size, strides_copy.data())); + } +}; + +std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d); + +class TORCH_CUDA_CPP_API FilterDescriptor : public Descriptor< + miopenTensorDescriptor, + &miopenCreateTensorDescriptor, + &miopenDestroyTensorDescriptor> { + public: + void set(const at::Tensor &t, int64_t pad = 0) { + set(t, at::MemoryFormat::Contiguous, pad); + } + + void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0); + +private: + void set(miopenDataType_t dataType, int dim, size_t* size, size_t* stride, bool nhwc) { + std::vector strides_copy(stride, stride + dim); + fixSizeOneDimStride(dim, size, strides_copy.data(), nhwc); + // Use V2 API which supports 64-bit size/stride for large tensors + MIOPEN_CHECK(miopenSetTensorDescriptorV2(mut_desc(), dataType, dim, size, strides_copy.data())); + } +}; + +struct TORCH_CUDA_CPP_API ConvolutionDescriptor + : public Descriptor< + miopenConvolutionDescriptor, + &miopenCreateConvolutionDescriptor, + &miopenDestroyConvolutionDescriptor> { + void set(miopenDataType_t dataType, miopenConvolutionMode_t c_mode, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool benchmark, bool deterministic) { + MIOPEN_CHECK(miopenInitConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, c_mode)); + MIOPEN_CHECK(miopenSetConvolutionGroupCount(mut_desc(), groups)); + MIOPEN_CHECK(miopenSetConvolutionAttribute(mut_desc(), MIOPEN_CONVOLUTION_ATTRIB_DETERMINISTIC, deterministic ? 1 : 0)); + if (benchmark) { + MIOPEN_CHECK(miopenSetConvolutionFindMode(mut_desc(), miopenConvolutionFindModeNormal)); + } + } +}; + +// NOLINTNEXTLINE(bugprone-exception-escape) +struct TORCH_CUDA_CPP_API DropoutDescriptor + : public Descriptor< + miopenDropoutDescriptor, + &miopenCreateDropoutDescriptor, + &miopenDestroyDropoutDescriptor> { + void set(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes, + unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) { + MIOPEN_CHECK(miopenSetDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode)); + } + + void restore(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes, + unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) { + MIOPEN_CHECK(miopenRestoreDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode)); + } +}; + +struct TORCH_CUDA_CPP_API RNNDescriptor + : public Descriptor +{ + void set(int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction, miopenRNNMode_t rnn_mode, + miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) { + MIOPEN_CHECK(miopenSetRNNDescriptor(mut_desc(), hidden_size, num_layers, input_mode, direction, rnn_mode, bias_mode, algorithm, datatype)); + } + + void setWithDropout(DropoutDescriptor& dropout_desc, int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction, + miopenRNNMode_t rnn_mode, miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) { + MIOPEN_CHECK(miopenSetRNNDescriptor_V2(mut_desc(), hidden_size, num_layers, dropout_desc.mut_desc(), input_mode, direction, rnn_mode, bias_mode, algorithm, datatype)); + } +}; + +union Constant +{ + float f; + double d; + Constant(miopenDataType_t dataType, double value) { + if (dataType == miopenHalf || dataType == miopenFloat || dataType == miopenBFloat16) { + f = static_cast(value); + } else { + d = value; + } + } +}; + +}} // namespace diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Exceptions.h b/western_ai/usa/pytorch/aten/src/ATen/miopen/Exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..b8a6faa18ab0be68df1e1c45bb0919fac0997625 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Exceptions.h @@ -0,0 +1,42 @@ +// @allow-raw-throw +#pragma once + +#include +#include +#include +#include + +namespace at { namespace native { + +class miopen_exception : public std::runtime_error { +public: + miopenStatus_t status; + miopen_exception(miopenStatus_t status, const char* msg) + : std::runtime_error(msg) + , status(status) {} + miopen_exception(miopenStatus_t status, const std::string& msg) + : std::runtime_error(msg) + , status(status) {} +}; + +inline void MIOPEN_CHECK(miopenStatus_t status) +{ + if (status != miopenStatusSuccess) { + if (status == miopenStatusNotImplemented) { + throw miopen_exception(status, std::string(miopenGetErrorString(status)) + + ". This error may appear if you passed in a non-contiguous input."); + } + throw miopen_exception(status, miopenGetErrorString(status)); + } +} + +inline void HIP_CHECK(hipError_t error) +{ + if (error != hipSuccess) { + std::string msg("HIP error: "); + msg += hipGetErrorString(error); + throw std::runtime_error(msg); + } +} + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Handle.cpp b/western_ai/usa/pytorch/aten/src/ATen/miopen/Handle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d935bb797fe18545e616246b231c4ebfe603b6c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Handle.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +#include +#include + +namespace at::native { +namespace { + +void createMIOpenHandle(miopenHandle_t *handle) { + MIOPEN_CHECK(miopenCreate(handle)); +} + +void destroyMIOpenHandle(miopenHandle_t handle) { + // this is because of something dumb in the ordering of + // destruction. Sometimes atexit, the cuda context (or something) + // would already be destroyed by the time this gets destroyed. It + // happens in fbcode setting. @colesbury and I decided to not destroy + // the handle as a workaround. + // - @soumith + // + // Further note: this is now disabled globally, because we are seeing + // the same issue as mentioned above in CUDA 11 CI. + // - @zasdfgbnm + // + // #ifdef NO_MIOPEN_DESTROY_HANDLE + // #else + // miopenDestroy(handle); + // #endif +} + +using MIOpenPoolType = at::cuda::DeviceThreadHandlePool< + miopenHandle_t, + createMIOpenHandle, + destroyMIOpenHandle>; + +} // namespace + +miopenHandle_t getMiopenHandle() { + c10::DeviceIndex device = 0; + AT_CUDA_CHECK(at::cuda::GetDevice(&device)); + + // Thread local PoolWindows are lazily-initialized + // to avoid initialization issues that caused hangs on Windows. + // See: https://github.com/pytorch/pytorch/pull/22405 + // This thread local unique_ptrs will be destroyed when the thread terminates, + // releasing its reserved handles back to the pool. + static auto pool = std::make_shared(); + thread_local std::unique_ptr myPoolWindow( + pool->newPoolWindow()); + + auto handle = myPoolWindow->reserve(device); + MIOPEN_CHECK(miopenSetStream(handle, at::cuda::getCurrentCUDAStream())); + return handle; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Handle.h b/western_ai/usa/pytorch/aten/src/ATen/miopen/Handle.h new file mode 100644 index 0000000000000000000000000000000000000000..6ee016afbb6a1ca9c6201633ebd8368e2ceceb6c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Handle.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +namespace at::native { + +TORCH_CUDA_CPP_API miopenHandle_t getMiopenHandle(); +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Types.cpp b/western_ai/usa/pytorch/aten/src/ATen/miopen/Types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53a2524e9881551a522c0e8dbefeeeadaa3edb4a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Types.cpp @@ -0,0 +1,25 @@ +#include + +#include +#include + +namespace at { namespace native { + +miopenDataType_t getMiopenDataType(const at::Tensor& tensor) { + if (tensor.scalar_type() == at::kFloat) { + return miopenFloat; + } else if (tensor.scalar_type() == at::kHalf) { + return miopenHalf; + } else if (tensor.scalar_type() == at::kBFloat16) { + return miopenBFloat16; + } + std::string msg("getMiopenDataType() not supported for "); + msg += toString(tensor.scalar_type()); + throw std::runtime_error(msg); +} + +int64_t miopen_version() { + return (MIOPEN_VERSION_MAJOR<<8) + (MIOPEN_VERSION_MINOR<<4) + MIOPEN_VERSION_PATCH; +} + +}} // namespace at::miopen diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Types.h b/western_ai/usa/pytorch/aten/src/ATen/miopen/Types.h new file mode 100644 index 0000000000000000000000000000000000000000..31e33cda39e64d8cb07c38474434e0f543d46837 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Types.h @@ -0,0 +1,13 @@ +#pragma once + +#include +#include +#include + +namespace at::native { + +TORCH_CUDA_CPP_API miopenDataType_t getMiopenDataType(const at::Tensor& tensor); + +int64_t miopen_version(); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/Utils.h b/western_ai/usa/pytorch/aten/src/ATen/miopen/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..30f8e228165664c6e358838df3c26d4074ccd173 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/Utils.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include + +namespace at { namespace native { + +// This function makes tensors which have zero stride contiguous, by +// setting the strides to 1. +inline Tensor contiguousIfZeroInStrides(const Tensor& t) { + for (auto s : t.strides()) { + if (s == 0) return t.contiguous(); + } + return t; +} + +}} diff --git a/western_ai/usa/pytorch/aten/src/ATen/miopen/miopen-wrapper.h b/western_ai/usa/pytorch/aten/src/ATen/miopen/miopen-wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..4aeebf2a12ff6b5bb11c93d6152055dffbb09e59 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/miopen/miopen-wrapper.h @@ -0,0 +1,28 @@ +#pragma once + +// Enable MIOpen Beta APIs including miopenSetTensorDescriptorV2 which supports +// 64-bit tensor dimensions/strides for large tensors (numel > INT32_MAX). +// Reference: https://github.com/ROCm/MIOpen/pull/2838 +#ifndef MIOPEN_BETA_API +#define MIOPEN_BETA_API 1 +#endif + +#include +#include + +#if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4) +// miopen 3.4 moved find mode from private header to public header +#else +// from miopen_internal.h +extern "C" { + +typedef enum +{ + miopenConvolutionFindModeNormal = 1, /*!< Normal mode */ +} miopenConvolutionFindMode_t; + +miopenStatus_t miopenSetConvolutionFindMode( + miopenConvolutionDescriptor_t convDesc, + miopenConvolutionFindMode_t findMode); +} +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/Descriptors.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/Descriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..5b64dbc7d3360f766d7de33114480aab97332f64 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/Descriptors.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include + +namespace at::native { + +struct DftiDescriptorDeleter { + void operator()(DFTI_DESCRIPTOR* desc) { + if (desc != nullptr) { + MKL_DFTI_CHECK(DftiFreeDescriptor(&desc)); + } + } +}; + +class DftiDescriptor { +public: + void init(DFTI_CONFIG_VALUE precision, DFTI_CONFIG_VALUE signal_type, MKL_LONG signal_ndim, MKL_LONG* sizes) { + TORCH_CHECK( + desc_ == nullptr, "DFTI DESCRIPTOR can only be initialized once"); + DFTI_DESCRIPTOR *raw_desc; + if (signal_ndim == 1) { + MKL_DFTI_CHECK(DftiCreateDescriptor(&raw_desc, precision, signal_type, 1, sizes[0])); + } else { + MKL_DFTI_CHECK(DftiCreateDescriptor(&raw_desc, precision, signal_type, signal_ndim, sizes)); + } + desc_.reset(raw_desc); + } + + DFTI_DESCRIPTOR *get() const { + TORCH_CHECK( + desc_ != nullptr, "DFTI DESCRIPTOR has not been initialized"); + return desc_.get(); + } + +private: + std::unique_ptr desc_; +}; + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/Exceptions.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/Exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..cc4c0e05882705dd36e9789c18e776d12beb5840 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/Exceptions.h @@ -0,0 +1,65 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +static inline void MKL_DFTI_CHECK(MKL_INT status) +{ + TORCH_CHECK(!status || DftiErrorClass(status, DFTI_NO_ERROR), "MKL FFT error: ", DftiErrorMessage(status)); +} + +} // namespace at::native + +namespace at::mkl::sparse { +static inline const char* _mklGetErrorString(sparse_status_t status) { + if (status == SPARSE_STATUS_SUCCESS) { + return "SPARSE_STATUS_SUCCESS"; + } + if (status == SPARSE_STATUS_NOT_INITIALIZED) { + return "SPARSE_STATUS_NOT_INITIALIZED"; + } + if (status == SPARSE_STATUS_ALLOC_FAILED) { + return "SPARSE_STATUS_ALLOC_FAILED"; + } + if (status == SPARSE_STATUS_INVALID_VALUE) { + return "SPARSE_STATUS_INVALID_VALUE"; + } + if (status == SPARSE_STATUS_EXECUTION_FAILED) { + return "SPARSE_STATUS_EXECUTION_FAILED"; + } + if (status == SPARSE_STATUS_INTERNAL_ERROR) { + return "SPARSE_STATUS_INTERNAL_ERROR"; + } + if (status == SPARSE_STATUS_NOT_SUPPORTED) { + return "SPARSE_STATUS_NOT_SUPPORTED"; + } + return ""; +} +} // namespace at::mkl::sparse + +#define TORCH_MKLSPARSE_CHECK(EXPR) \ + do { \ + sparse_status_t __err = EXPR; \ + TORCH_CHECK( \ + __err == SPARSE_STATUS_SUCCESS, \ + "MKL error: ", \ + at::mkl::sparse::_mklGetErrorString(__err), \ + " when calling `" #EXPR "`"); \ + } while (0) + +#define TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, function_name) \ + do { \ + sparse_status_t __status = (status); \ + TORCH_CHECK( \ + __status == SPARSE_STATUS_SUCCESS || \ + __status == SPARSE_STATUS_INVALID_VALUE, \ + "MKL error: ", \ + at::mkl::sparse::_mklGetErrorString(__status), \ + " when calling `" function_name "`"); \ + } while (0) diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/Limits.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/Limits.h new file mode 100644 index 0000000000000000000000000000000000000000..20ac21b56bb8974ec0364679633a92380627ba56 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/Limits.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace at::native { + + // Since size of MKL_LONG varies on different platforms (linux 64 bit, windows + // 32 bit), we need to programmatically calculate the max. + constexpr int64_t MKL_LONG_MAX = ((1LL << (sizeof(MKL_LONG) * 8 - 2)) - 1) * 2 + 1; + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/README.md b/western_ai/usa/pytorch/aten/src/ATen/mkl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c1e736cfa6ef7768d0241647f886b10ddb1a7356 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/README.md @@ -0,0 +1,4 @@ +All files living in this directory are written with the assumption that MKL is available, +which means that these code are not guarded by `#if AT_MKL_ENABLED()`. Therefore, whenever +you need to use definitions from here, please guard the `#include` and +definition usages with `#if AT_MKL_ENABLED()` macro, e.g. [SpectralOps.cpp](../native/mkl/SpectralOps.cpp). diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/Sparse.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/Sparse.h new file mode 100644 index 0000000000000000000000000000000000000000..c6f4a5e5c2e13df32981f2d2b264fc10c410f727 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/Sparse.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +#if AT_MKL_ENABLED() +#define AT_USE_MKL_SPARSE() 1 +#else +#define AT_USE_MKL_SPARSE() 0 +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseBlas.cpp b/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseBlas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aaeff5b9a0c3acc9419756ddab2a10e7fcfffd99 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseBlas.cpp @@ -0,0 +1,370 @@ +/* + Provides the implementations of MKL Sparse BLAS function templates. +*/ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#if AT_USE_MKL_SPARSE() +#include +#include + +namespace at::mkl::sparse { + +namespace { + +template +MKL_Complex to_mkl_complex(c10::complex scalar) { + MKL_Complex mkl_scalar; + mkl_scalar.real = scalar.real(); + mkl_scalar.imag = scalar.imag(); + return mkl_scalar; +} + +} // namespace + + +template <> +void create_csr(MKL_SPARSE_CREATE_CSR_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_s_create_csr( + A, indexing, rows, cols, rows_start, rows_end, col_indx, values)); +} +template <> +void create_csr(MKL_SPARSE_CREATE_CSR_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_d_create_csr( + A, indexing, rows, cols, rows_start, rows_end, col_indx, values)); +} +template <> +void create_csr>( + MKL_SPARSE_CREATE_CSR_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_create_csr( + A, + indexing, + rows, + cols, + rows_start, + rows_end, + col_indx, + reinterpret_cast(values))); +} +template <> +void create_csr>( + MKL_SPARSE_CREATE_CSR_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_create_csr( + A, + indexing, + rows, + cols, + rows_start, + rows_end, + col_indx, + reinterpret_cast(values))); +} + +template <> +void create_bsr(MKL_SPARSE_CREATE_BSR_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_s_create_bsr( + A, + indexing, + block_layout, + rows, + cols, + block_size, + rows_start, + rows_end, + col_indx, + values)); +} +template <> +void create_bsr(MKL_SPARSE_CREATE_BSR_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_d_create_bsr( + A, + indexing, + block_layout, + rows, + cols, + block_size, + rows_start, + rows_end, + col_indx, + values)); +} +template <> +void create_bsr>( + MKL_SPARSE_CREATE_BSR_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_create_bsr( + A, + indexing, + block_layout, + rows, + cols, + block_size, + rows_start, + rows_end, + col_indx, + reinterpret_cast(values))); +} +template <> +void create_bsr>( + MKL_SPARSE_CREATE_BSR_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_create_bsr( + A, + indexing, + block_layout, + rows, + cols, + block_size, + rows_start, + rows_end, + col_indx, + reinterpret_cast(values))); +} + +template <> +void mv(MKL_SPARSE_MV_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK( + mkl_sparse_s_mv(operation, alpha, A, descr, x, beta, y)); +} +template <> +void mv(MKL_SPARSE_MV_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK( + mkl_sparse_d_mv(operation, alpha, A, descr, x, beta, y)); +} +template <> +void mv>(MKL_SPARSE_MV_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_mv( + operation, + to_mkl_complex(alpha), + A, + descr, + reinterpret_cast(x), + to_mkl_complex(beta), + reinterpret_cast(y))); +} +template <> +void mv>(MKL_SPARSE_MV_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_mv( + operation, + to_mkl_complex(alpha), + A, + descr, + reinterpret_cast(x), + to_mkl_complex(beta), + reinterpret_cast(y))); +} + +template <> +void add(MKL_SPARSE_ADD_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_s_add(operation, A, alpha, B, C)); +} +template <> +void add(MKL_SPARSE_ADD_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_d_add(operation, A, alpha, B, C)); +} +template <> +void add>(MKL_SPARSE_ADD_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_add( + operation, A, to_mkl_complex(alpha), B, C)); +} +template <> +void add>(MKL_SPARSE_ADD_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_add( + operation, A, to_mkl_complex(alpha), B, C)); +} + +template <> +void export_csr(MKL_SPARSE_EXPORT_CSR_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_s_export_csr( + source, indexing, rows, cols, rows_start, rows_end, col_indx, values)); +} +template <> +void export_csr(MKL_SPARSE_EXPORT_CSR_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_d_export_csr( + source, indexing, rows, cols, rows_start, rows_end, col_indx, values)); +} +template <> +void export_csr>( + MKL_SPARSE_EXPORT_CSR_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_export_csr( + source, + indexing, + rows, + cols, + rows_start, + rows_end, + col_indx, + reinterpret_cast(values))); +} +template <> +void export_csr>( + MKL_SPARSE_EXPORT_CSR_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_export_csr( + source, + indexing, + rows, + cols, + rows_start, + rows_end, + col_indx, + reinterpret_cast(values))); +} + +template <> +void mm(MKL_SPARSE_MM_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_s_mm( + operation, alpha, A, descr, layout, B, columns, ldb, beta, C, ldc)); +} +template <> +void mm(MKL_SPARSE_MM_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_d_mm( + operation, alpha, A, descr, layout, B, columns, ldb, beta, C, ldc)); +} +template <> +void mm>(MKL_SPARSE_MM_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_mm( + operation, + to_mkl_complex(alpha), + A, + descr, + layout, + reinterpret_cast(B), + columns, + ldb, + to_mkl_complex(beta), + reinterpret_cast(C), + ldc)); +} +template <> +void mm>(MKL_SPARSE_MM_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_mm( + operation, + to_mkl_complex(alpha), + A, + descr, + layout, + reinterpret_cast(B), + columns, + ldb, + to_mkl_complex(beta), + reinterpret_cast(C), + ldc)); +} + +template <> +void spmmd(MKL_SPARSE_SPMMD_ARGTYPES(float)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_s_spmmd( + operation, A, B, layout, C, ldc)); +} +template <> +void spmmd(MKL_SPARSE_SPMMD_ARGTYPES(double)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_d_spmmd( + operation, A, B, layout, C, ldc)); +} +template <> +void spmmd>(MKL_SPARSE_SPMMD_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_c_spmmd( + operation, + A, + B, + layout, + reinterpret_cast(C), + ldc)); +} +template <> +void spmmd>(MKL_SPARSE_SPMMD_ARGTYPES(c10::complex)) { + TORCH_MKLSPARSE_CHECK(mkl_sparse_z_spmmd( + operation, + A, + B, + layout, + reinterpret_cast(C), + ldc)); +} + +template <> +sparse_status_t trsv(MKL_SPARSE_TRSV_ARGTYPES(float)) { + sparse_status_t status = mkl_sparse_s_trsv(operation, alpha, A, descr, x, y); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_s_trsv"); + return status; +} +template <> +sparse_status_t trsv(MKL_SPARSE_TRSV_ARGTYPES(double)) { + sparse_status_t status = mkl_sparse_d_trsv(operation, alpha, A, descr, x, y); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_d_trsv"); + return status; +} +template <> +sparse_status_t trsv>(MKL_SPARSE_TRSV_ARGTYPES(c10::complex)) { + sparse_status_t status = mkl_sparse_c_trsv( + operation, + to_mkl_complex(alpha), + A, + descr, + reinterpret_cast(x), + reinterpret_cast(y)); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_c_trsv"); + return status; +} +template <> +sparse_status_t trsv>( + MKL_SPARSE_TRSV_ARGTYPES(c10::complex)) { + sparse_status_t status = mkl_sparse_z_trsv( + operation, + to_mkl_complex(alpha), + A, + descr, + reinterpret_cast(x), + reinterpret_cast(y)); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_z_trsv"); + return status; +} + +template <> +sparse_status_t trsm(MKL_SPARSE_TRSM_ARGTYPES(float)) { + sparse_status_t status = mkl_sparse_s_trsm( + operation, alpha, A, descr, layout, x, columns, ldx, y, ldy); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_s_trsm"); + return status; +} +template <> +sparse_status_t trsm(MKL_SPARSE_TRSM_ARGTYPES(double)) { + sparse_status_t status = mkl_sparse_d_trsm( + operation, alpha, A, descr, layout, x, columns, ldx, y, ldy); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_d_trsm"); + return status; +} +template <> +sparse_status_t trsm>(MKL_SPARSE_TRSM_ARGTYPES(c10::complex)) { + sparse_status_t status = mkl_sparse_c_trsm( + operation, + to_mkl_complex(alpha), + A, + descr, + layout, + reinterpret_cast(x), + columns, + ldx, + reinterpret_cast(y), + ldy); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_c_trsm"); + return status; +} +template <> +sparse_status_t trsm>( + MKL_SPARSE_TRSM_ARGTYPES(c10::complex)) { + sparse_status_t status = mkl_sparse_z_trsm( + operation, + to_mkl_complex(alpha), + A, + descr, + layout, + reinterpret_cast(x), + columns, + ldx, + reinterpret_cast(y), + ldy); + TORCH_MKLSPARSE_CHECK_SUCCESS_OR_INVALID(status, "mkl_sparse_z_trsm"); + return status; +} + +} // namespace at::mkl::sparse +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseBlas.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseBlas.h new file mode 100644 index 0000000000000000000000000000000000000000..fe67adf9b2e120de1abaa96700e110c4a20e151f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseBlas.h @@ -0,0 +1,226 @@ +#pragma once + +/* + Provides a subset of MKL Sparse BLAS functions as templates: + + mv(operation, alpha, A, descr, x, beta, y) + + where scalar_t is double, float, c10::complex or c10::complex. + The functions are available in at::mkl::sparse namespace. +*/ + +#include +#include + +#include + +namespace at::mkl::sparse { + +#define MKL_SPARSE_CREATE_CSR_ARGTYPES(scalar_t) \ + sparse_matrix_t *A, const sparse_index_base_t indexing, const MKL_INT rows, \ + const MKL_INT cols, MKL_INT *rows_start, MKL_INT *rows_end, \ + MKL_INT *col_indx, scalar_t *values + +template +inline void create_csr(MKL_SPARSE_CREATE_CSR_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::create_csr: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void create_csr(MKL_SPARSE_CREATE_CSR_ARGTYPES(float)); +template <> +void create_csr(MKL_SPARSE_CREATE_CSR_ARGTYPES(double)); +template <> +void create_csr>( + MKL_SPARSE_CREATE_CSR_ARGTYPES(c10::complex)); +template <> +void create_csr>( + MKL_SPARSE_CREATE_CSR_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_CREATE_BSR_ARGTYPES(scalar_t) \ + sparse_matrix_t *A, const sparse_index_base_t indexing, \ + const sparse_layout_t block_layout, const MKL_INT rows, \ + const MKL_INT cols, MKL_INT block_size, MKL_INT *rows_start, \ + MKL_INT *rows_end, MKL_INT *col_indx, scalar_t *values + +template +inline void create_bsr(MKL_SPARSE_CREATE_BSR_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::create_bsr: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void create_bsr(MKL_SPARSE_CREATE_BSR_ARGTYPES(float)); +template <> +void create_bsr(MKL_SPARSE_CREATE_BSR_ARGTYPES(double)); +template <> +void create_bsr>( + MKL_SPARSE_CREATE_BSR_ARGTYPES(c10::complex)); +template <> +void create_bsr>( + MKL_SPARSE_CREATE_BSR_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_MV_ARGTYPES(scalar_t) \ + const sparse_operation_t operation, const scalar_t alpha, \ + const sparse_matrix_t A, const struct matrix_descr descr, \ + const scalar_t *x, const scalar_t beta, scalar_t *y + +template +inline void mv(MKL_SPARSE_MV_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::mv: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void mv(MKL_SPARSE_MV_ARGTYPES(float)); +template <> +void mv(MKL_SPARSE_MV_ARGTYPES(double)); +template <> +void mv>(MKL_SPARSE_MV_ARGTYPES(c10::complex)); +template <> +void mv>(MKL_SPARSE_MV_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_ADD_ARGTYPES(scalar_t) \ + const sparse_operation_t operation, const sparse_matrix_t A, \ + const scalar_t alpha, const sparse_matrix_t B, sparse_matrix_t *C + +template +inline void add(MKL_SPARSE_ADD_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::add: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void add(MKL_SPARSE_ADD_ARGTYPES(float)); +template <> +void add(MKL_SPARSE_ADD_ARGTYPES(double)); +template <> +void add>(MKL_SPARSE_ADD_ARGTYPES(c10::complex)); +template <> +void add>(MKL_SPARSE_ADD_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_EXPORT_CSR_ARGTYPES(scalar_t) \ + const sparse_matrix_t source, sparse_index_base_t *indexing, MKL_INT *rows, \ + MKL_INT *cols, MKL_INT **rows_start, MKL_INT **rows_end, \ + MKL_INT **col_indx, scalar_t **values + +template +inline void export_csr(MKL_SPARSE_EXPORT_CSR_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::export_csr: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void export_csr(MKL_SPARSE_EXPORT_CSR_ARGTYPES(float)); +template <> +void export_csr(MKL_SPARSE_EXPORT_CSR_ARGTYPES(double)); +template <> +void export_csr>( + MKL_SPARSE_EXPORT_CSR_ARGTYPES(c10::complex)); +template <> +void export_csr>( + MKL_SPARSE_EXPORT_CSR_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_MM_ARGTYPES(scalar_t) \ + const sparse_operation_t operation, const scalar_t alpha, \ + const sparse_matrix_t A, const struct matrix_descr descr, \ + const sparse_layout_t layout, const scalar_t *B, const MKL_INT columns, \ + const MKL_INT ldb, const scalar_t beta, scalar_t *C, const MKL_INT ldc + +template +inline void mm(MKL_SPARSE_MM_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::mm: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void mm(MKL_SPARSE_MM_ARGTYPES(float)); +template <> +void mm(MKL_SPARSE_MM_ARGTYPES(double)); +template <> +void mm>(MKL_SPARSE_MM_ARGTYPES(c10::complex)); +template <> +void mm>(MKL_SPARSE_MM_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_SPMMD_ARGTYPES(scalar_t) \ + const sparse_operation_t operation, const sparse_matrix_t A, \ + const sparse_matrix_t B, const sparse_layout_t layout, scalar_t *C, \ + const MKL_INT ldc + +template +inline void spmmd(MKL_SPARSE_SPMMD_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::spmmd: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +void spmmd(MKL_SPARSE_SPMMD_ARGTYPES(float)); +template <> +void spmmd(MKL_SPARSE_SPMMD_ARGTYPES(double)); +template <> +void spmmd>(MKL_SPARSE_SPMMD_ARGTYPES(c10::complex)); +template <> +void spmmd>( + MKL_SPARSE_SPMMD_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_TRSV_ARGTYPES(scalar_t) \ + const sparse_operation_t operation, const scalar_t alpha, \ + const sparse_matrix_t A, const struct matrix_descr descr, \ + const scalar_t *x, scalar_t *y + +template +inline sparse_status_t trsv(MKL_SPARSE_TRSV_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::trsv: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +sparse_status_t trsv(MKL_SPARSE_TRSV_ARGTYPES(float)); +template <> +sparse_status_t trsv(MKL_SPARSE_TRSV_ARGTYPES(double)); +template <> +sparse_status_t trsv>(MKL_SPARSE_TRSV_ARGTYPES(c10::complex)); +template <> +sparse_status_t trsv>(MKL_SPARSE_TRSV_ARGTYPES(c10::complex)); + +#define MKL_SPARSE_TRSM_ARGTYPES(scalar_t) \ + const sparse_operation_t operation, const scalar_t alpha, \ + const sparse_matrix_t A, const struct matrix_descr descr, \ + const sparse_layout_t layout, const scalar_t *x, const MKL_INT columns, \ + const MKL_INT ldx, scalar_t *y, const MKL_INT ldy + +template +inline sparse_status_t trsm(MKL_SPARSE_TRSM_ARGTYPES(scalar_t)) { + TORCH_INTERNAL_ASSERT( + false, + "at::mkl::sparse::trsm: not implemented for ", + typeid(scalar_t).name()); +} + +template <> +sparse_status_t trsm(MKL_SPARSE_TRSM_ARGTYPES(float)); +template <> +sparse_status_t trsm(MKL_SPARSE_TRSM_ARGTYPES(double)); +template <> +sparse_status_t trsm>(MKL_SPARSE_TRSM_ARGTYPES(c10::complex)); +template <> +sparse_status_t trsm>(MKL_SPARSE_TRSM_ARGTYPES(c10::complex)); + +} // namespace at::mkl::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseDescriptors.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseDescriptors.h new file mode 100644 index 0000000000000000000000000000000000000000..b4e8404f693fdb773ad93b716d40eb579e5cd046 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/SparseDescriptors.h @@ -0,0 +1,146 @@ +#pragma once + +/* + Provides templated descriptor wrappers of MKL Sparse BLAS sparse matrices: + + MklSparseCsrDescriptor(sparse_csr_tensor) + + where scalar_t is double, float, c10::complex or c10::complex. + The descriptors are available in at::mkl::sparse namespace. +*/ + +#include +#include +#include + +#include +#include + +#include + +namespace at::mkl::sparse { + +template +struct MklSparseDescriptorDeleter { + void operator()(T* x) { + if (x != nullptr) { + TORCH_MKLSPARSE_CHECK(destructor(x)); + } + } +}; + +template +class MklSparseDescriptor { + public: + T* descriptor() const { + return descriptor_.get(); + } + T* descriptor() { + return descriptor_.get(); + } + + protected: + std::unique_ptr> descriptor_; +}; + +namespace { + +c10::MaybeOwned inline prepare_indices_for_mkl(const Tensor& indices) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + isIntegralType(indices.scalar_type(), /*includeBool=*/false)); +#ifdef MKL_ILP64 + // ILP64 is a 64-bit API version of MKL + // Indices tensor must have ScalarType::Long type + if (indices.scalar_type() == ScalarType::Long) { + return c10::MaybeOwned::borrowed(indices); + } else { + return c10::MaybeOwned::owned(indices.to(ScalarType::Long)); + } +#else + // LP64 is a 32-bit API version of MKL + // Indices tensor must have ScalarType::Int type + if (indices.scalar_type() == ScalarType::Int) { + return c10::MaybeOwned::borrowed(indices); + } else { + return c10::MaybeOwned::owned(indices.to(ScalarType::Int)); + } +#endif +} + +} // anonymous namespace + +template +class MklSparseCsrDescriptor + : public MklSparseDescriptor { + public: + MklSparseCsrDescriptor(const Tensor& input) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY((input.layout() == kSparseCsr || input.layout() == kSparseBsr)); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.dim() == 2); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + input._nnz() > 0, "MKL doesn't work with empty CSR matrices"); + + IntArrayRef input_sizes = input.sizes(); + auto rows = mkl_int_cast(input_sizes[0], "rows"); + auto cols = mkl_int_cast(input_sizes[1], "cols"); + + auto crow_indices = input.crow_indices(); + auto col_indices = input.col_indices(); + auto values = input.values(); + + crow_indices_ = prepare_indices_for_mkl(crow_indices); + col_indices_ = prepare_indices_for_mkl(col_indices); + values_ = values.expect_contiguous(); + + auto values_ptr = values_->data_ptr(); + auto crow_indices_ptr = crow_indices_->data_ptr(); + auto col_indices_ptr = col_indices_->data_ptr(); + + sparse_matrix_t raw_descriptor; + + if (input.layout() == kSparseBsr) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + values.dim() == 3 && crow_indices.dim() == 1 && + col_indices.dim() == 1); + TORCH_CHECK( + values.size(-1) == values.size(-2), + "MKL Sparse doesn't support matrices with non-square blocks."); + auto block_size = mkl_int_cast(values.size(-1), "block_size"); + create_bsr( + &raw_descriptor, + SPARSE_INDEX_BASE_ZERO, + SPARSE_LAYOUT_ROW_MAJOR, + rows / block_size, + cols / block_size, + block_size, + crow_indices_ptr, + crow_indices_ptr + 1, + col_indices_ptr, + values_ptr); + } else { + create_csr( + &raw_descriptor, + SPARSE_INDEX_BASE_ZERO, + rows, + cols, + crow_indices_ptr, + crow_indices_ptr + 1, + col_indices_ptr, + values_ptr); + } + + descriptor_.reset(raw_descriptor); + } + + MklSparseCsrDescriptor() { + sparse_matrix_t raw_descriptor = nullptr; + descriptor_.reset(raw_descriptor); + } + + private: + c10::MaybeOwned crow_indices_; + c10::MaybeOwned col_indices_; + c10::MaybeOwned values_; +}; + +} // namespace at::mkl::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/mkl/Utils.h b/western_ai/usa/pytorch/aten/src/ATen/mkl/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6b3837afe90fcfcb992a68d02bf8652957a8e058 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mkl/Utils.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +static inline MKL_INT mkl_int_cast(int64_t value, const char* varname) { + auto result = static_cast(value); + TORCH_CHECK( + static_cast(result) == value, + "mkl_int_cast: The value of ", + varname, + "(", + (long long)value, + ") is too large to fit into a MKL_INT (", + sizeof(MKL_INT), + " bytes)"); + return result; +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/EmptyTensor.cpp b/western_ai/usa/pytorch/aten/src/ATen/mps/EmptyTensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8aa56dc23a923a65042745570f9754d920d6e8f0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/EmptyTensor.cpp @@ -0,0 +1,138 @@ +// Copyright © 2022 Apple Inc. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MPS_ERROR_NOT_COMPILED "PyTorch code is not compiled with MPS enabled" +#define MPS_ERROR_RUNTIME_TOO_LOW \ + "The MPS backend is supported on macOS 14.0+. ", \ + "Current OS version can be queried using `sw_vers`" +#define MPS_ERROR_DOUBLE_NOT_SUPPORTED "Cannot convert a MPS Tensor to float64 dtype " \ + "as the MPS framework doesn't support float64. Please use float32 instead." + +namespace at::detail { +TensorBase empty_mps( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt) { +#if defined(__APPLE__) +#if __is_target_os(macOS) + if (at::hasMPS()) { + auto device = device_or_default(device_opt); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(device.type() == DeviceType::MPS); + + TORCH_CHECK_NOT_IMPLEMENTED( + layout_or_default(layout_opt) == Layout::Strided, + "only strided tensors are supported on MPS"); + + TORCH_CHECK(size.size() <= c10::metal::max_ndim, "MPS supports tensors with dimensions <= ", c10::metal::max_ndim, ", but got ", size.size(), "."); + + check_size_nonnegative(size); + + auto* allocator = at::mps::GetMPSAllocator(); + int64_t nelements = c10::multiply_integers(size); + auto dtype = dtype_or_default(dtype_opt); + TORCH_CHECK_TYPE(dtype != kDouble && dtype != kComplexDouble, MPS_ERROR_DOUBLE_NOT_SUPPORTED); + + + auto dtype_meta = scalarTypeToTypeMeta(dtype); + int64_t size_bytes = nelements * dtype_meta.itemsize(); + auto storage_impl = c10::make_intrusive( + c10::StorageImpl::use_byte_size_t(), + size_bytes, + allocator->allocate(size_bytes), + allocator, + /*resizeable=*/true); + + auto tensor = + detail::make_tensor(storage_impl, DispatchKey::MPS, dtype_meta); + // Default TensorImpl has size [0] + if (size.size() != 1 || size[0] != 0) { + tensor.unsafeGetTensorImpl()->set_sizes_contiguous(size); + } + + auto memory_format = memory_format_opt.value_or(MemoryFormat::Contiguous); + tensor.unsafeGetTensorImpl()->empty_tensor_restride(memory_format); + // See Note [Enabling Deterministic Operations] + if (C10_UNLIKELY(at::globalContext().deterministicAlgorithms() && at::globalContext().deterministicFillUninitializedMemory())) { + at::native::fill_empty_deterministic_(tensor); + } + return tensor; + } else { + TORCH_CHECK(false, MPS_ERROR_RUNTIME_TOO_LOW) + } +#else + TORCH_CHECK(false, MPS_ERROR_NOT_COMPILED) +#endif +#else + TORCH_CHECK(false, MPS_ERROR_NOT_COMPILED) +#endif +} + +TensorBase empty_mps( + IntArrayRef size, const TensorOptions &options) { + return at::detail::empty_mps( + size, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt(), + options.memory_format_opt()); +} + +TensorBase empty_strided_mps( + IntArrayRef size, + IntArrayRef stride, + ScalarType dtype, + std::optional device_opt) { +#if defined(__APPLE__) +#if __is_target_os(macOS) + if (at::hasMPS()) { + auto device = device_or_default(device_opt); + TORCH_INTERNAL_ASSERT(device.is_mps()); + TORCH_CHECK_TYPE(dtype != ScalarType::Double, MPS_ERROR_DOUBLE_NOT_SUPPORTED); + const DeviceGuard device_guard(device); + auto* allocator = at::mps::GetMPSAllocator(); + constexpr c10::DispatchKeySet mps_dks(c10::DispatchKey::MPS); + Tensor result = at::detail::empty_strided_generic( + size, stride, allocator, mps_dks, dtype); + // See Note [Enabling Deterministic Operations] + if (C10_UNLIKELY(at::globalContext().deterministicAlgorithms() && at::globalContext().deterministicFillUninitializedMemory())) { + at::native::fill_empty_deterministic_(result); + } + return result; + } else { + TORCH_CHECK(false, MPS_ERROR_RUNTIME_TOO_LOW) + } +#else + TORCH_CHECK(false, MPS_ERROR_NOT_COMPILED) +#endif +#else + TORCH_CHECK(false, MPS_ERROR_NOT_COMPILED) +#endif +} + +TensorBase empty_strided_mps( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions &options) { + return at::native::empty_strided_mps( + size, + stride, + optTypeMetaToScalarType(options.dtype_opt()), + options.layout_opt(), + options.device_opt(), + options.pinned_memory_opt()); +} + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/EmptyTensor.h b/western_ai/usa/pytorch/aten/src/ATen/mps/EmptyTensor.h new file mode 100644 index 0000000000000000000000000000000000000000..2d0bcc09013132f3d3eb262d1e77bbdcc1ceb85f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/EmptyTensor.h @@ -0,0 +1,28 @@ +// Copyright © 2022 Apple Inc. + +#pragma once +#include + +namespace at::detail { + +C10_EXPORT TensorBase empty_mps( + IntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt); +C10_EXPORT TensorBase empty_mps(IntArrayRef size, const TensorOptions& options); + +C10_EXPORT TensorBase empty_strided_mps( + IntArrayRef size, + IntArrayRef stride, + ScalarType dtype, + std::optional device_opt); + +C10_EXPORT TensorBase empty_strided_mps( + IntArrayRef size, + IntArrayRef stride, + const TensorOptions& options); + +} // namespace at::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocator.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..68a0608ed9ddc0d8ab439270f106fa064d7d1c72 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocator.h @@ -0,0 +1,457 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +// this implementation is based on CUDACachingAllocator. +// It utilizes Metal Heaps to improve the performance with buffer allocation. +// Do not include this header. Use MPSAllocatorInterface.h instead. +// TODO: Unify the logic with CUDACachingAllocator and remove redundant code. +namespace at::mps::HeapAllocator { + +static const size_t kMaxSmallAlloc = MB(1); // largest "small" allocation is 1 MiB +static const size_t kMinLargeAlloc = MB(10); // allocations between 1 and 10 MiB may use kLargeHeap +static const size_t kRoundLarge = MB(2); // round up large allocations to 2 MiB +static const size_t kSmallHeap = MB(8); // "small" allocations are packed in 8 MiB heaps +static const size_t kLargeHeap = MB(32); // "large" allocations may be packed in 32 MiB heaps +static const size_t kXLargeHeap = MB(1024); // "extra large" allocations may be packed in 1 GiB heaps +static const size_t kMaxScalarAlloc = (sizeof(int64_t)); // largest "scalar" allocation + +enum class HeapTier { SMALL, LARGE, XLARGE, OVERSIZE }; + +inline HeapTier getHeapTier(size_t size, bool has_memory_pressure) { + if (size <= kMaxSmallAlloc) { + return HeapTier::SMALL; + } else if (size < kMinLargeAlloc) { + return HeapTier::LARGE; + } else if (size < kXLargeHeap / 2 && !has_memory_pressure) { + return HeapTier::XLARGE; + } + return HeapTier::OVERSIZE; +} + +// buffer pools could be customized with a combination of usage flags +enum UsageFlags : uint32_t { + PRIVATE = 0, + SMALL = (1 << 0), // small heaps have sizes of kSmallHeap, and large ones kLargeHeap + SHARED = (1 << 1), // shared pools allocated on devices with unified memory; otherwise, private between host/device + MANAGED = (1 << 2), // managed storage mode + HAZARD = (1 << 3), // enables Automatic Hazard Tracking for the resources allocated on the pool + SCALAR = (1 << 4), // used to import CPU scalar values to GPU and use them in MPS Stream +}; +// debug verbosity flags +enum DebugVerbosity : uint32_t { + SILENT = 0, + PROFILING = (1 << 0), // print generic profiling data for total system memory usage + ALLOCATIONS = (1 << 1), // print buffer allocations + RECYCLES = (1 << 2), // print buffer recycling + RELEASES = (1 << 3), // print buffer releases + LARGE_ONLY = (1 << 4), // only log large buffer pool transactions +}; + +struct HeapBlock; + +struct BufferBlock { + id buffer; + void* cpu_ptr = nullptr; // stores the pointer to CPU mapping of a Shared MTLBuffer + size_t size; // size after alignment + size_t requested_size; // requested size (before alignment) + // buffer shape is used for retrieving base of views in cached graphs + std::vector shape; + bool in_use = false; + HeapBlock* heap; + id_t buf_id; + // counter to candidate least recently used buffers for garbage collection + uint32_t gc_count = 0; + uint32_t use_count = 0; + // counter to assign unique ids to buffer blocks + static uint64_t buffer_counter; + // Metal events used to sync GPU/CPU operations on the shared-storage buffers + MPSEventPtr event; + + BufferBlock(size_t Size, size_t RequestedSize = 0, const id Buffer = nullptr, HeapBlock* Heap = nullptr) + : buffer(Buffer), size(Size), requested_size(RequestedSize), heap(Heap), buf_id(Buffer ? ++buffer_counter : 0) {} + + static bool Comparator(const BufferBlock* a, const BufferBlock* b) { + return (a->size != b->size) ? a->size < b->size : (uintptr_t)a->buffer < (uintptr_t)b->buffer; + } + static size_t alignUp(size_t Size, size_t Alignment) { + assert(((Alignment - 1) & Alignment) == 0); + return ((Size + Alignment - 1) & ~(Alignment - 1)); + } + uint32_t retainCount() const { + return [buffer retainCount]; + } +}; +typedef bool (*BufferComparison)(const BufferBlock*, const BufferBlock*); + +struct BufferPool; +struct AllocParams { + AllocParams(size_t Alloc_Size, size_t Requested_Size, BufferPool* Pool) + : search_key(Alloc_Size), pool(Pool), requested_size(Requested_Size) {} + size_t size() const { + return search_key.size; + } + + BufferBlock search_key; + BufferPool* pool; + BufferBlock* buffer_block = nullptr; + size_t requested_size; + // true if we exceed the low watermark limit. In this case + // we apply strategies to relieve the pressure before allocation. + bool has_memory_pressure = false; +}; + +struct HeapBlock { + id heap; + struct { + size_t total, available; + } size; + BufferPool* pool; + unsigned int n_buffers = 0; + id_t heap_id; + // indicates if we split this heap to sub-allocate 'several' buffers (otherwise single buffer) + bool is_split; + // counter to assign unique ids to heap blocks + static uint64_t heap_counter; + + HeapBlock(size_t Size, const id Heap = nullptr, BufferPool* Pool = nullptr) + : heap(Heap), + size({.total = Size, .available = Size}), + pool(Pool), + heap_id(Heap ? ++heap_counter : 0), + is_split(true) {} + + static MTLResourceOptions getOptions(uint32_t usage) { + // TODO: check the caching performance of write-combined mode + MTLResourceOptions options = MTLResourceCPUCacheModeDefaultCache; + + if (usage & UsageFlags::MANAGED) + options |= MTLResourceStorageModeManaged; + else if (usage & UsageFlags::SHARED) + options |= MTLResourceStorageModeShared; + else + options |= MTLResourceStorageModePrivate; + + options |= + (usage & UsageFlags::HAZARD) ? MTLResourceHazardTrackingModeTracked : MTLResourceHazardTrackingModeUntracked; + + return options; + } + + static HeapBlock* createHeapBlock(AllocParams& params, id device, uint32_t usage) { + HeapBlock* heapBlock = nullptr; + bool is_split = true; + const size_t size = params.size(); + MTLHeapDescriptor* d = [MTLHeapDescriptor new]; + if (d) { + switch (getHeapTier(size, params.has_memory_pressure)) { + case HeapTier::SMALL: + d.size = kSmallHeap; + break; + case HeapTier::LARGE: + d.size = kLargeHeap; + break; + case HeapTier::XLARGE: + d.size = kXLargeHeap; + break; + case HeapTier::OVERSIZE: + d.size = kRoundLarge * ((size + kRoundLarge - 1) / kRoundLarge); + is_split = false; + break; + } + d.storageMode = (usage & UsageFlags::SHARED) ? MTLStorageModeShared : MTLStorageModePrivate; + d.cpuCacheMode = MTLCPUCacheModeDefaultCache; + // this automatically handles Metal buffer access synchronizations at the + // cost of slightly lower performance. + d.hazardTrackingMode = + (usage & UsageFlags::HAZARD) ? MTLHazardTrackingModeTracked : MTLHazardTrackingModeUntracked; + d.resourceOptions = getOptions(usage); + d.type = MTLHeapTypeAutomatic; + id heap = [device newHeapWithDescriptor:d]; + if (heap) { + [heap setPurgeableState:MTLPurgeableStateNonVolatile]; + const size_t heap_size = heapAvailableSize(heap); + heapBlock = new HeapBlock(heap_size, heap, params.pool); + if (heapBlock) { + heapBlock->is_split = is_split; + } + } + [d release]; + } + return heapBlock; + } + static bool Comparator(const HeapBlock* a, const HeapBlock* b) { + return (a->size.available != b->size.available) ? a->size.available < b->size.available + : (uintptr_t)a->heap < (uintptr_t)b->heap; + } + static NSUInteger heapAvailableSize(id heap, size_t Alignment = vm_page_size) { + return [heap maxAvailableSizeWithAlignment:Alignment]; + } + NSUInteger Size() { + return [heap size]; + } + id newMTLBuffer(size_t length, uint32_t usage) { + id buf = [heap newBufferWithLength:length options:getOptions(usage)]; + if (buf) { + updateAvailableSize(); + n_buffers++; + } + return buf; + } + // returns the retainCount before releasing the buffer + uint32_t releaseMTLBuffer(id& buffer) { + const uint32_t retainCount = [buffer retainCount]; + [buffer release]; + buffer = nil; + updateAvailableSize(); + n_buffers--; + return retainCount; + } + // returns the retainCount before releasing the heap + uint32_t releaseMTLHeap() { + const uint32_t retainCount = [heap retainCount]; + TORCH_INTERNAL_ASSERT(!n_buffers); // assert if heap isn't empty + [heap setPurgeableState:MTLPurgeableStateEmpty]; + [heap release]; + heap = nil; + size.available = 0; + return retainCount; + } + uint32_t retainCount() const { + return [heap retainCount]; + } + void updateAvailableSize() { + size.available = heapAvailableSize(heap); + } +}; +typedef bool (*HeapComparison)(const HeapBlock*, const HeapBlock*); + +struct BufferPool { + enum class Kind { + SHARED_SMALL, + SHARED_LARGE, + SCALAR, + }; + + BufferPool(const id Device, uint32_t Usage) + : device(Device), usage(Usage), heaps(HeapBlock::Comparator), available_buffers(BufferBlock::Comparator) {} + + const id device; + // usage flags to customize the pool for various purposes (see UsageFlags enum) + const uint32_t usage; + // total number of buffers in the pool + uint32_t n_buffers = 0; + // total allocations size on this pool + size_t allocated_size = 0; + // total memory available in the pool + size_t available_size = 0; + // list of heaps ordered by their "available" (not total) memory size + std::set heaps; + // list of only "available" buffers in the pool (i.e., buffers not in-use) + std::set available_buffers; + // list of buffers that are in a state of "limbo" where they've already been freed + // from PyTorch-side, but were not returned to pool due to still being + // in-use by command buffers with retainCount > 1. In this state, the buffer is + // neither ready to be recycled, nor could be returned to pool as available. + // These buffers will be returned to pool once the command buffer's + // completionHandler callbacks are called. + std::unordered_set buffers_pending_free; + // list of heaps pending size update + std::unordered_set heaps_pending_update; +}; + +class MPSHeapAllocatorImpl { + public: + explicit MPSHeapAllocatorImpl() + : m_device(at::mps::MPSDevice::getInstance()->device()), + m_max_buffer_size([m_device maxBufferLength]), + m_stream(getDefaultMPSStream()), + m_event_pool(getMPSEventPool()) { + init_allocator(); + } + ~MPSHeapAllocatorImpl() { + emptyCache(); + } + // interface exposed to at::Allocator + id malloc(size_t size, uint32_t usage); + // frees a buffer and returns it into buffer pool + void free(void* ptr); + // releases all the cached buffers and their associated heaps + void emptyCache(); + // free inactive buffers that are pending to be freed + void freeInactiveBuffers(); + // returns true if buffer was allocated from the shared pool + bool isSharedBuffer(const void* ptr); + // get the requested unaligned size of an MTLBuffer + ssize_t getUnalignedBufferSize(const void* ptr); + // set the shape of a base tensor from a view tensor + void setBufferShape(const void* ptr, const IntArrayRef& shape); + // retrieve the shape of a base tensor from a view tensor + IntArrayRef getBufferShape(const void* ptr); + // get the unique ID of the buffer + id_t getBufferId(const void* ptr); + // allocate a buffer from a specialized pool to import CPU scalars into GPU + id allocScalarBufferWithValue(void* value, size_t size); + // returns a CPU-mapping of the input buffer and its retainCount, + // if only it has Shared storage-mode and allocated on MPSAllocator + std::pair getSharedBufferPtr(const void* buffer); + // returns a CPU-device c10::Storage aliasing the host-visible contents of + // the MTLBuffer backing `mps_storage`. The returned storage keeps the + // source MPS storage alive for its lifetime. Raises if `mps_storage` is + // not MPS-allocated or not shared-storage. + c10::Storage getHostAliasStorage(const c10::Storage& mps_storage); + // records events for a list of MTLBuffers (list is used to lock the mutex once) + // returns true if records any event (given if passed buffers exist and are shared-storage) + bool recordEvents(c10::ArrayRef buffers); + // waits for the event to signal the completion of GPU execution + // on the passed shared buffers (list is used to lock the mutex once) + // returns true if actually waited on any event + bool waitForEvents(c10::ArrayRef buffers); + // this indicates how far (in Megabytes) the current total allocations are from the + // low watermark limit which is used to detect if we're under memory pressure + // This returns zero if we've reached the low watermark limit + ssize_t getLowWatermarkValue(); + // (see m_low_watermark_ratio for description) + void setLowWatermarkRatio(double ratio); + // (see m_high_watermark_ratio for description) + void setHighWatermarkRatio(double ratio); + // (see m_low_watermark_limit for description) + size_t getLowWatermarkLimit() const { + return m_low_watermark_limit; + } + // (see m_max_total_allowed_size for description) + size_t getHighWatermarkLimit() const { + return m_max_total_allowed_size; + } + // (see m_total_allocated_memory for description) + size_t getTotalAllocatedMemory() const { + return m_total_allocated_memory.current; + } + // (see m_current_allocated_memory for description) + size_t getCurrentAllocatedMemory() const { + return m_current_allocated_memory.current; + } + // snapshot of memory stats for the generic torch.accelerator memory APIs + c10::CachingDeviceAllocator::DeviceStats getDeviceStats(); + void resetAccumulatedStats(); + void resetPeakStats(); + // total GPU memory allocated in the process by Metal driver; including + // implicit allocations from MPS/MPSGraph frameworks and MPSHeapAllocatorImpl. + size_t getDriverAllocatedMemory() const { + return current_allocated_size(); + } + // recommended Max memory for Metal + size_t getRecommendedMaxMemory() const { + return max_device_size(); + } + // (see enum DebugVerbosity for description) + uint32_t getDebugVerbosity() const { + return m_debug_verbosity; + } + // returns the device that we allocate from + inline id Device() const { + return m_device; + } + + inline std::string format_size(uint64_t size) const; + + private: + // (see m_high_watermark_ratio for description) + constexpr static double default_high_watermark_ratio = 1.7; + // we set the allowed upper bound to twice the size of recommendedMaxWorkingSetSize. + constexpr static double default_high_watermark_upper_bound = 2.0; + // (see m_low_watermark_ratio for description) + // on unified memory, we could allocate beyond the recommendedMaxWorkingSetSize + constexpr static double default_low_watermark_ratio = 1.4; + + const id m_device; + std::recursive_mutex m_mutex; + // allocated buffers by device pointer + ska::flat_hash_map m_allocated_buffers; + // using a container for pools to simplify iterating them + ska::flat_hash_map> m_pools; + // total memory allocated by HeapAllocator (including blocks in pools); + // tracked as a Stat to expose current/peak/accumulated reserved bytes + c10::CachingAllocator::Stat m_total_allocated_memory; + // currently active memory allocations in use (i.e., blocks not in pools); + // tracked as a Stat to expose current/peak/accumulated allocated bytes + c10::CachingAllocator::Stat m_current_allocated_memory; + // max buffer size allowed by Metal + size_t m_max_buffer_size = 0; + // maximum total size allowed to be allocated + size_t m_max_total_allowed_size = 0; + // high watermark ratio is a hard limit for the total allowed allocations + // 0. : disables high watermark limit (may cause system failure if system-wide OOM occurs) + // 1. : recommended maximum allocation size (i.e., device.recommendedMaxWorkingSetSize) + // >1.: allows limits beyond the device.recommendedMaxWorkingSetSize + // e.g., value 0.95 means we allocate up to 95% of recommended maximum + // allocation size; beyond that, the allocations would fail with OOM error. + double m_high_watermark_ratio; + // low watermark ratio is a soft limit to attempt limiting memory allocations up to the lower watermark + // level by garbage collection or committing command buffers more frequently (a.k.a, adaptive commit). + // Value between 0 to m_high_watermark_ratio (setting 0.0 disables adaptive commit and garbage collection) + // e.g., value 0.9 means we 'attempt' to limit allocations up to 90% of recommended maximum + // allocation size. + double m_low_watermark_ratio; + // low watermark size limit (in Bytes) at the time we initialize the allocator + size_t m_low_watermark_limit; + // use "PYTORCH_DEBUG_MPS_ALLOCATOR" env-var to set debug verbosity + uint32_t m_debug_verbosity; + // default MPS stream + MPSStream* m_stream; + // we hold a reference to MPSEventPool so it could get destroyed after MPSAllocator + std::shared_ptr m_event_pool; + + void init_allocator(); + void init_buffer_pools(); + HeapBlock* get_free_heap(AllocParams& params); + bool get_free_buffer(AllocParams& params); + BufferBlock* get_allocated_buffer_block(const void* ptr); + BufferBlock* alloc_buffer_block(size_t size, uint32_t usage); + bool alloc_buffer(AllocParams& params); + void free_buffer(BufferBlock* buffer_block); + // returns true if the container heap is also released + bool release_buffer(BufferBlock* buffer_block, bool remove_empty_heap = true); + void release_buffers(BufferPool& pool); + bool release_available_cached_buffers(AllocParams& params); + bool release_cached_buffers(); + // free unused cached blocks to reclaim GPU memory if memory pressure is high + void garbage_collect_cached_buffers(AllocParams& params); + // returns the suitable buffer pool type for the usage or + // requested/allocated sizes + BufferPool& get_pool(size_t requested_size, size_t aligned_size, uint32_t usage); + // returns the aligned allocation size that is optimized + // for the buffers to get reused frequently + size_t get_allocation_size(size_t size, uint32_t usage) const; + // maximum size of device memory available for allocation in current process + // Note: the recommendedMaxWorkingSetSize is typically 75% of the total system memory. + size_t max_device_size() const { + return [m_device recommendedMaxWorkingSetSize]; + } + // there are implicit allocations from MPS backend, so we need to query the 'device' for + // total allocated size instead of manually tracking in MPSAllocator + size_t current_allocated_size() const { + return [m_device currentAllocatedSize]; + } + + bool trigger_memory_callbacks(BufferBlock* buffer_block, IMpsAllocatorCallback::EventType event) const { + for (const auto& name : MPSAllocatorCallbacksRegistry()->Keys()) { + MPSAllocatorCallbacksRegistry()->Create(name)->executeMPSAllocatorCallback( + buffer_block ? buffer_block->buffer : nullptr, event); + } + return true; + } +}; + +} // namespace at::mps::HeapAllocator diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocator.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocator.mm new file mode 100644 index 0000000000000000000000000000000000000000..eda159a43af0b52231f4968f206706f4b7cd9663 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocator.mm @@ -0,0 +1,977 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::mps { + +C10_DEFINE_REGISTRY(MPSAllocatorCallbacksRegistry, IMpsAllocatorCallback) + +namespace HeapAllocator { + +uint64_t BufferBlock::buffer_counter = 0; +uint64_t HeapBlock::heap_counter = 0; + +// Set once the heap allocator singleton has been constructed (i.e. MPS/Metal is +// actually in use). Lets the registered c10 allocator report readiness via +// DeviceAllocator::initialized() without forcing Metal initialization. +static std::atomic s_mps_allocator_initialized{false}; + +void MPSHeapAllocatorImpl::init_allocator() { + TORCH_CHECK(m_device.hasUnifiedMemory, "MPS backend is only supported on devices with unified memory"); + init_buffer_pools(); + + // debug verbosity flags (see DebugVerbosity enum) + static const auto verbosity_str = c10::utils::get_env("PYTORCH_DEBUG_MPS_ALLOCATOR"); + m_debug_verbosity = verbosity_str ? strtol(verbosity_str->c_str(), nullptr, 0) : DebugVerbosity::SILENT; + + static const auto high_watermark_ratio_str = c10::utils::get_env("PYTORCH_MPS_HIGH_WATERMARK_RATIO"); + const double high_watermark_ratio = + high_watermark_ratio_str ? strtod(high_watermark_ratio_str->c_str(), nullptr) : default_high_watermark_ratio; + setHighWatermarkRatio(high_watermark_ratio); + + static const auto low_watermark_ratio_str = c10::utils::get_env("PYTORCH_MPS_LOW_WATERMARK_RATIO"); + const double low_watermark_ratio = + low_watermark_ratio_str ? strtod(low_watermark_ratio_str->c_str(), nullptr) : default_low_watermark_ratio; + setLowWatermarkRatio(low_watermark_ratio); + + if (m_debug_verbosity & DebugVerbosity::PROFILING) { + LOG(INFO) << "Initializing heap allocator on unified device memory of size " << format_size(max_device_size()); + } + + s_mps_allocator_initialized.store(true); +} + +void MPSHeapAllocatorImpl::init_buffer_pools() { + // using a container for pools to simplify iterating over them + // Pool of large buffers with shared storage mode + m_pools.emplace(BufferPool::Kind::SHARED_LARGE, + std::make_unique(m_device, UsageFlags::SHARED | UsageFlags::HAZARD)); + // Pool of small buffers with shared storage mode + m_pools.emplace(BufferPool::Kind::SHARED_SMALL, + std::make_unique(m_device, UsageFlags::SMALL | UsageFlags::SHARED | UsageFlags::HAZARD)); + // Pool of small buffers with shared storage mode used to allocate and copy Scalars + // from CPU to Metal buffers (see allocScalarBufferWithValue()). + // no Hazard Tracking required for the Scalar pool (synchronized manually). + m_pools.emplace(BufferPool::Kind::SCALAR, + std::make_unique(m_device, UsageFlags::SMALL | UsageFlags::SHARED | UsageFlags::SCALAR)); +} + +BufferPool& MPSHeapAllocatorImpl::get_pool(size_t requested_size, size_t aligned_size, uint32_t usage) { + BufferPool::Kind poolKind; + + if (usage & UsageFlags::SCALAR) { + poolKind = BufferPool::Kind::SCALAR; + } else if (aligned_size <= kMaxSmallAlloc) { + poolKind = BufferPool::Kind::SHARED_SMALL; + } else { + poolKind = BufferPool::Kind::SHARED_LARGE; + } + return *m_pools[poolKind]; +} + +size_t MPSHeapAllocatorImpl::get_allocation_size(size_t size, uint32_t usage) const { + MTLSizeAndAlign sizeAlign = [m_device heapBufferSizeAndAlignWithLength:size options:HeapBlock::getOptions(usage)]; + const size_t aligned = BufferBlock::alignUp(sizeAlign.size, sizeAlign.align); + + // Round large allocations up into coarse buckets so a slowly growing allocation + // (e.g. a KV cache reallocated at size+epsilon each decode step) reuses the + // previous step's freed buffer instead of stranding a new heap. + if ((usage & UsageFlags::SCALAR) || aligned <= kMaxSmallAlloc) { + return aligned; + } + constexpr int kLargeBucketShift = 5; // 32 buckets per power-of-two magnitude + // The early return above guarantees aligned > kMaxSmallAlloc > 0, so the clz + // below never operates on 0 (which would be undefined behavior). + size_t granule = (size_t(1) << (63 - __builtin_clzll(aligned))) >> kLargeBucketShift; + if (granule < vm_page_size) { + granule = vm_page_size; + } + const size_t bucketed = BufferBlock::alignUp(aligned, granule); + // Keep the request in its original heap-size class (see getHeapTier): never let + // rounding cross into a larger class, which would reserve a much larger backing + // heap, nor push it past Metal's per-buffer limit. + if (bucketed >= m_max_buffer_size || + getHeapTier(bucketed, /*has_memory_pressure=*/false) != getHeapTier(aligned, /*has_memory_pressure=*/false)) { + return aligned; + } + return bucketed; +} + +void MPSHeapAllocatorImpl::setHighWatermarkRatio(double ratio) { + TORCH_CHECK(ratio >= 0.0 && ratio <= default_high_watermark_upper_bound, "invalid high watermark ratio ", ratio); + m_max_total_allowed_size = + (ratio == 0.0) ? std::numeric_limits::max() : static_cast(ratio * (double)max_device_size()); + if (m_debug_verbosity & DebugVerbosity::PROFILING) { + LOG(INFO) << "High watermark memory allocation limit: " + << (ratio == 0.0 ? "unlimited" : format_size(m_max_total_allowed_size)); + } + m_high_watermark_ratio = ratio; +} + +void MPSHeapAllocatorImpl::setLowWatermarkRatio(double ratio) { + // used for comparison with lower_watermark_ratio + const double high_watermark_limit = + m_high_watermark_ratio == 0.0 ? default_high_watermark_upper_bound : m_high_watermark_ratio; + TORCH_CHECK(ratio >= 0.0 && ratio <= high_watermark_limit, "invalid low watermark ratio ", ratio); + // we use this to detect if there's memory pressure + m_low_watermark_limit = + (ratio == 0.0) ? std::numeric_limits::max() : static_cast(ratio * (double)max_device_size()); + if (m_debug_verbosity & DebugVerbosity::PROFILING) { + LOG(INFO) << "Low watermark memory allocation limit: " + << (ratio == 0.0 ? "unlimited" : format_size(m_low_watermark_limit)); + } + m_low_watermark_ratio = ratio; +} + +HeapBlock* MPSHeapAllocatorImpl::get_free_heap(AllocParams& params) { + BufferPool& pool = *params.pool; + HeapBlock* heap_block = nullptr; + HeapBlock search_key(params.size()); + + auto it = pool.heaps.lower_bound(&search_key); + if (it == pool.heaps.end()) { + heap_block = HeapBlock::createHeapBlock(params, pool.device, pool.usage); + if (heap_block) { + m_total_allocated_memory.increase(heap_block->size.total); + if (m_debug_verbosity & DebugVerbosity::ALLOCATIONS) { + LOG(INFO) << "Allocated " << ((pool.usage & UsageFlags::SHARED) ? "shared" : "private") << " heap #" + << heap_block->heap_id << " of size " << format_size(heap_block->size.total) + << " (#heaps: " << (pool.heaps.size() + 1) + << ", current allocated: " << format_size(current_allocated_size()) << ")"; + } + } + } else { + heap_block = *it; + // remove and re-insert heap in the set later after a buffer is created. + // this ensures updating the order of heaps based on their new available sizes + pool.heaps.erase(it); + } + return heap_block; +} + +bool MPSHeapAllocatorImpl::alloc_buffer(AllocParams& params) { + if (m_max_total_allowed_size != std::numeric_limits::max() && + current_allocated_size() + params.size() > m_max_total_allowed_size) { + return false; + } + HeapBlock* heap = get_free_heap(params); + if (!heap) { + return false; // this will cause releasing pool buffers to free up memory + } + BufferPool& pool = *params.pool; + + id buffer = heap->newMTLBuffer(params.size(), pool.usage); + // this should never happen as the backing memory (i.e., heap) was allocated successfully. + TORCH_INTERNAL_ASSERT(buffer); + // insert heap after a buffer was created on it to update the order of heap's set + pool.heaps.insert(heap); + params.buffer_block = new BufferBlock(params.size(), params.requested_size, buffer, heap); + m_allocated_buffers[params.buffer_block->buffer] = params.buffer_block; + pool.allocated_size += params.size(); + pool.n_buffers++; + + if ((m_debug_verbosity & DebugVerbosity::ALLOCATIONS) && + (!(m_debug_verbosity & DebugVerbosity::LARGE_ONLY) || !(pool.usage & UsageFlags::SMALL))) { + LOG(INFO) << "Allocated " << ((params.pool->usage & UsageFlags::SHARED) ? "shared" : "private") + << ((params.pool->usage & UsageFlags::SCALAR) ? " scalar" : "") << " buffer #" + << params.buffer_block->buf_id << " of size " << format_size(params.size()) << " at " + << params.buffer_block->buffer << " from heap #" << heap->heap_id + << " (requested: " << format_size(params.requested_size) + << ", heap: " << format_size(heap->size.available) + << ", total: " << format_size(m_total_allocated_memory.current) << ")"; + } + return true; +} + +bool MPSHeapAllocatorImpl::get_free_buffer(AllocParams& params) { + // this helps to monitor "implicit" allocations from MPS backend and to prevent OOM and system failure. + if (m_high_watermark_ratio > 0.0 && current_allocated_size() + params.size() > m_max_total_allowed_size) { + return false; + } + BufferPool& pool = *params.pool; + // track buffer reuse intervals only on large pool when low watermark limit is enabled. + if (m_low_watermark_ratio > 0.0 && !(pool.usage & UsageFlags::SMALL)) { + for (auto& b : pool.available_buffers) { + ++b->gc_count; + } + } + auto it = pool.available_buffers.lower_bound(¶ms.search_key); + // No cached buffer is >= the request size when this is true; used below to + // detect a buffer that grows by a small amount on every step. + const bool no_larger_buffer = (it == pool.available_buffers.end()); + if (it != pool.available_buffers.end()) { + BufferBlock* buffer_block = *it; + + // the logic in here is simple: keep reusing existing heaps capacity as long as possible (by splitting + // or releasing oversize buffers, if required), and avoid 'new' heap allocations as much as possible. + if (buffer_block->size <= params.size() + kLargeHeap) { + // return the existing buffer if it already fits the requested size (i.e., not oversize) + params.buffer_block = buffer_block; + } else { + HeapBlock search_key(params.size()); + // if there's an 'existing' heap with enough capacity, then don't + // return the oversize buffer and sub-allocate from that existing heap. + if (pool.heaps.lower_bound(&search_key) != pool.heaps.end()) { + params.buffer_block = nullptr; + } else if (buffer_block->retainCount() <= 1) { + // otherwise if buffer is releasable immediately, we make room by releasing the + // buffer and reuse the new space within its heap container for the new smaller buffer allocation + release_buffer(buffer_block, false); + // this will skip unnecessary garbage collection as we'll reuse the newly released space + params.has_memory_pressure = false; + } else if (params.has_memory_pressure) { + // the oversized buffer is busy and not reusable at the moment. So release it (and potentially its heap + // container) in allocator, and ARC will later free up its backing memory when the busy command buffer finishes. + release_buffer(buffer_block, true); + } else { + // only if there's no memory pressure, we'll reuse the oversized buffer + params.buffer_block = buffer_block; + } + } + } + + if (!params.buffer_block) { + // A bucketed allocation that crossed into a larger bucket (see + // get_allocation_size) can no longer reuse the previous bucket's cached + // buffers. Release the largest one within kNearFitReuseDenom (1/8) of the + // request to free its heap. The tolerance is kept wider than a bucket so the + // stranded near-fit is caught anywhere in the power-of-two band. + if (no_larger_buffer && !(pool.usage & UsageFlags::SMALL) && !pool.available_buffers.empty()) { + constexpr size_t kNearFitReuseDenom = 8; + BufferBlock* nearest = *pool.available_buffers.rbegin(); + if (nearest->size >= params.size() - params.size() / kNearFitReuseDenom && nearest->retainCount() <= 1) { + release_buffer(nearest, /*remove_empty_heap=*/true); + } + } + return false; // this will make allocator to allocate a new buffer + } + pool.available_buffers.erase(params.buffer_block); + params.buffer_block->requested_size = params.requested_size; + params.buffer_block->gc_count = 0; + pool.available_size -= params.buffer_block->size; + + if ((m_debug_verbosity & DebugVerbosity::RECYCLES) && + (!(m_debug_verbosity & DebugVerbosity::LARGE_ONLY) || !(pool.usage & UsageFlags::SMALL))) { + LOG(INFO) << "Reusing " << ((params.pool->usage & UsageFlags::SHARED) ? "shared" : "private") + << ((params.pool->usage & UsageFlags::SCALAR) ? " scalar" : "") << " buffer #" + << params.buffer_block->buf_id << " of size " << format_size(params.buffer_block->size) << " at " + << params.buffer_block->buffer << " (requested: " << format_size(params.requested_size) + << ", use#: " << params.buffer_block->use_count + 1 << ", retain#: " << params.buffer_block->retainCount() + << ")"; + } + return true; +} + +BufferBlock* MPSHeapAllocatorImpl::alloc_buffer_block(size_t size, uint32_t usage) { + TORCH_CHECK(size < m_max_buffer_size, "Invalid buffer size: ", format_size(size)); + + size_t alloc_size = get_allocation_size(size, usage); + auto& pool = get_pool(size, alloc_size, usage); + AllocParams params(alloc_size, size, &pool); + // we care about memory pressure if only we're allocating large buffers when the + // low watermark limit has been reached + params.has_memory_pressure = !(pool.usage & UsageFlags::SMALL) && getLowWatermarkValue() <= 0; + + // first, try to get a block from the existing pool. + bool block_found = get_free_buffer(params); + if (!block_found) { + // do garbage collection if memory pressure is high and there's enough memory in pool + if (params.has_memory_pressure && alloc_size < pool.available_size) { + garbage_collect_cached_buffers(params); + } + + block_found = + // Attempt allocate + alloc_buffer(params) || + // Callbacks might release more memory (eg. by forcing a GC in the host language) thus + // we can retry getting a free buffer in the pool, before trying to alloc again. + (trigger_memory_callbacks(nullptr, IMpsAllocatorCallback::EventType::ALLOCATION_FAILED) && + get_free_buffer(params)) || + // Free enough available cached blocks to satisfy alloc and retry alloc. + (release_available_cached_buffers(params) && alloc_buffer(params)) || + // Free all cached buffers and retry alloc. + (release_cached_buffers() && alloc_buffer(params)); + } + + BufferBlock* buffer_block = params.buffer_block; + + // the OOM could be triggered if: + // 1- the High Watermark limit has been reached (if enabled) + // 2- ran out of device memory, or the memory fragmentation is so high that a contiguous + // chunk of requested size couldn't be found. + if (!block_found || !buffer_block) { + if (m_high_watermark_ratio > 0.0) { + TORCH_CHECK( + false, + "MPS backend out of memory (MPS allocated: ", + format_size(m_total_allocated_memory.current), + ", other allocations: ", + format_size(current_allocated_size() - m_total_allocated_memory.current), + ", max allowed: ", + format_size(m_max_total_allowed_size), + "). Tried to allocate ", + format_size(alloc_size), + " on ", + ((pool.usage & UsageFlags::SHARED) ? "shared" : "private"), + " pool. Use PYTORCH_MPS_HIGH_WATERMARK_RATIO=0.0 to disable upper limit for memory allocations (may cause system failure)."); + } else { + TORCH_CHECK(false, + "MPS backend out of memory (MPS allocated: ", + format_size(m_total_allocated_memory.current), + ", other allocations: ", + format_size(current_allocated_size() - m_total_allocated_memory.current), + "). Tried to allocate ", + format_size(alloc_size), + " on ", + ((pool.usage & UsageFlags::SHARED) ? "shared" : "private"), + " pool."); + } + } + buffer_block->in_use = true; + buffer_block->use_count++; + m_current_allocated_memory.increase(buffer_block->size); + + return buffer_block; +} + +void MPSHeapAllocatorImpl::free_buffer(BufferBlock* buffer_block) { + TORCH_INTERNAL_ASSERT(buffer_block->in_use); + + BufferPool& pool = *buffer_block->heap->pool; + // Makes sure the BufferBlock* isn't already present in the pool we're freeing it back into. + TORCH_INTERNAL_ASSERT(pool.available_buffers.insert(buffer_block).second); + pool.available_size += buffer_block->size; + buffer_block->shape.clear(); // reset shape + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(m_current_allocated_memory.current >= static_cast(buffer_block->size)); + m_current_allocated_memory.decrease(buffer_block->size); + if (buffer_block->event) { + // returns the MPSEvent back to MPSEventPool + buffer_block->event.reset(nullptr); + } + buffer_block->in_use = false; +} + +BufferBlock* MPSHeapAllocatorImpl::get_allocated_buffer_block(const void* ptr) { + auto it = m_allocated_buffers.find(ptr); + if (it == m_allocated_buffers.end()) { + return nullptr; + } + return it->second; +} + +bool MPSHeapAllocatorImpl::release_buffer(BufferBlock* buffer_block, bool remove_empty_heap) { + HeapBlock* heap_block = buffer_block->heap; + BufferPool& pool = *heap_block->pool; + pool.allocated_size -= buffer_block->size; + pool.available_size -= buffer_block->size; + m_allocated_buffers.erase(buffer_block->buffer); + pool.available_buffers.erase(buffer_block); + pool.n_buffers--; + // will re-insert later to keep the heaps list sorted based on heap's new available size (if heap not empty) + pool.heaps.erase(heap_block); + uint32_t retainCount = heap_block->releaseMTLBuffer(buffer_block->buffer); + + if ((m_debug_verbosity & DebugVerbosity::RELEASES) && + (!(m_debug_verbosity & DebugVerbosity::LARGE_ONLY) || !(pool.usage & UsageFlags::SMALL))) { + LOG(INFO) << "Released buffer #" << buffer_block->buf_id << " of size " << format_size(buffer_block->size) + << " from heap #" << heap_block->heap_id << " (heap size: " << format_size(heap_block->size.available) + << ", use#: " << buffer_block->use_count << ", retain#: " << retainCount + << ", gc#: " << buffer_block->gc_count << ")"; + } + delete buffer_block; + + if (remove_empty_heap && heap_block->n_buffers == 0) { + pool.heaps_pending_update.erase(heap_block); + m_total_allocated_memory.decrease(heap_block->size.total); + retainCount = heap_block->releaseMTLHeap(); + if (m_debug_verbosity & DebugVerbosity::RELEASES) { + LOG(INFO) << "Released heap #" << heap_block->heap_id << " of size " << format_size(heap_block->size.total) + << " (current allocated: " << format_size(current_allocated_size()) << ", retain#: " << retainCount + << ")"; + } + delete heap_block; + return true; + } else { + pool.heaps.insert(heap_block); + // if heap wasn't released and its released buffer is still busy in command buffer, the available + // size of the heap cannot be updated and we should defer updating until command buffer finishes. + if (retainCount > 1) { + pool.heaps_pending_update.insert(heap_block); + m_mutex.unlock(); + m_stream->addCompletedHandler(^(id) { + std::lock_guard lock(m_mutex); + // check if the heap block still exists + if (pool.heaps_pending_update.find(heap_block) != pool.heaps_pending_update.end()) { + pool.heaps_pending_update.erase(heap_block); + pool.heaps.erase(heap_block); + heap_block->updateAvailableSize(); + pool.heaps.insert(heap_block); + } + }); + m_mutex.lock(); + } + } + return false; +} + +void MPSHeapAllocatorImpl::release_buffers(BufferPool& pool) { + if (pool.available_buffers.empty()) { + return; + } + if ((m_debug_verbosity & DebugVerbosity::RELEASES)) { + LOG(INFO) << "Releasing " << pool.available_buffers.size() << " buffers from " + << ((pool.usage & UsageFlags::SMALL) ? "small " : "large ") + << ((pool.usage & UsageFlags::SHARED) ? "shared" : "private") + << ((pool.usage & UsageFlags::SCALAR) ? " scalar" : "") + << " pool (total size: " << format_size(pool.allocated_size) << ", #buffers: " << pool.n_buffers << ")"; + } + auto it = pool.available_buffers.begin(); + while (it != pool.available_buffers.end()) { + BufferBlock* buffer_block = *it; + ++it; + release_buffer(buffer_block); + } +} + +bool MPSHeapAllocatorImpl::release_available_cached_buffers(AllocParams& params) { + BufferPool& pool = *params.pool; + + if (pool.available_buffers.empty()) { + return false; + } + auto it = pool.available_buffers.lower_bound(¶ms.search_key); + if (it == pool.available_buffers.end()) { + size_t totalReleased = 0; + --it; + while (totalReleased < params.search_key.size) { + auto cur = it; + totalReleased += (*it)->size; + if (it != pool.available_buffers.begin()) { + --it; + release_buffer(*cur); + } else { + release_buffer(*cur); + break; + } + } + if (totalReleased < params.search_key.size) { + return false; + } + } else { + release_buffer(*it); + } + return true; +} + +bool MPSHeapAllocatorImpl::release_cached_buffers() { + if (m_debug_verbosity >= DebugVerbosity::PROFILING) { + LOG(INFO) << "Attempting to release cached buffers (MPS allocated: " + << format_size(m_total_allocated_memory.current) + << ", other allocations: " << format_size(current_allocated_size() - m_total_allocated_memory.current) + << ")"; + } + // before releasing the buffers make sure the command buffer has finished. + // we need to release the lock temporarily as synchronizing may cause deadlock with completion handlers. + m_mutex.unlock(); + auto stream = getDefaultMPSStream(); + dispatch_sync_with_rethrow(stream->queue(), ^() { + stream->synchronize(SyncType::COMMIT_AND_WAIT); + }); + m_mutex.lock(); + // Free all cached blocks to system allocator + for (const auto& poolIt : m_pools) { + BufferPool& pool = *poolIt.second; + release_buffers(pool); + } + return true; +} + +void MPSHeapAllocatorImpl::garbage_collect_cached_buffers(AllocParams& params) { + // skip garbage collection if memory pressure has already relieved + if (current_allocated_size() < m_low_watermark_limit) { + return; + } + // attempt to collect garbage until we reach below low watermark limit + const auto target_size = current_allocated_size() - m_low_watermark_limit; + const BufferPool& pool = *params.pool; + // calculate the total age of the free-able blocks. We'll use it later to get the average age threshold. + double total_age = 0.0; + unsigned int freeable_block_count = 0, freed_count = 0; + size_t gc_reclaimed = 0; + + for (auto& b : pool.available_buffers) { + if (b->retainCount() <= 1) { + total_age += b->gc_count; + ++freeable_block_count; + } + } + if (freeable_block_count == 0) { + return; + } + // repeat GC until we reach reclaim > target size. + bool block_freed = true; + while (gc_reclaimed < target_size && block_freed && freeable_block_count > 0) { + // free blocks exceeding this age threshold first. + double age_threshold = total_age / freeable_block_count; + // stop iteration if we can no longer free a block. + block_freed = false; + // free blocks of > avg age. Stop garbage collection if we reach below the + // low watermark limit since re-allocation or fragmentation could be costly. + auto it = pool.available_buffers.begin(); + while (it != pool.available_buffers.end() && gc_reclaimed < target_size) { + BufferBlock* buffer_block = *it++; + if (buffer_block->gc_count >= age_threshold && buffer_block->retainCount() <= 1) { + block_freed = true; + gc_reclaimed += buffer_block->size; + total_age -= buffer_block->gc_count; + freeable_block_count--; + freed_count++; + release_buffer(buffer_block, !buffer_block->heap->is_split); + } + } + } + if (m_debug_verbosity & DebugVerbosity::RELEASES) { + LOG(INFO) << "Garbage collected " << freed_count << " buffers from large " + << ((pool.usage & UsageFlags::SHARED) ? "shared" : "private") + << " pool (total reclaimed: " << format_size(gc_reclaimed) + << ", #buffers: " << pool.available_buffers.size() << ")"; + } +} + +// public interface to MPSAllocator +id MPSHeapAllocatorImpl::malloc(size_t size, uint32_t usage) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = alloc_buffer_block(size, usage); + return buffer_block ? buffer_block->buffer : nullptr; +} + +bool MPSHeapAllocatorImpl::isSharedBuffer(const void* ptr) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = get_allocated_buffer_block(ptr); + // it's OK for the buffer_block to not exist yet + return buffer_block && (buffer_block->heap->pool->usage & UsageFlags::SHARED); +} + +id MPSHeapAllocatorImpl::allocScalarBufferWithValue(void* value, size_t size) { + BufferBlock* buffer_block = nullptr; + { + std::lock_guard lock(m_mutex); + + buffer_block = alloc_buffer_block(size, UsageFlags::SCALAR); + if (!buffer_block) { + return nullptr; + } + if (!buffer_block->cpu_ptr) { + buffer_block->cpu_ptr = [buffer_block->buffer contents]; + } + } + // buffer is out of the pool, so no mutex lock is needed + memcpy(buffer_block->cpu_ptr, value, size); + return buffer_block->buffer; +} + +std::pair MPSHeapAllocatorImpl::getSharedBufferPtr(const void* ptr) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = get_allocated_buffer_block(ptr); + // return if buffer was not allocated on MPSAllocator or isn't a Shared buffer + if (!buffer_block || !(buffer_block->heap->pool->usage & UsageFlags::SHARED)) { + return {nullptr, 0}; + } + if (!buffer_block->cpu_ptr) { + buffer_block->cpu_ptr = [buffer_block->buffer contents]; + } + return {buffer_block->cpu_ptr, buffer_block->retainCount()}; +} + +namespace { +// Deleter for the CPU-device DataPtr produced by getHostAliasStorage. +// The context is a heap-allocated c10::Storage holding a refcount on the +// source MPS storage; destroying it releases that refcount, which in turn +// lets the MPSAllocator recycle the underlying MTLBuffer. +void hostAliasDeleter(void* ctx) { + delete static_cast(ctx); +} +} // namespace + +c10::Storage MPSHeapAllocatorImpl::getHostAliasStorage(const c10::Storage& mps_storage) { + TORCH_CHECK_VALUE(mps_storage.device().type() == c10::DeviceType::MPS, + "getHostAliasStorage: expected an MPS storage, got device=", + mps_storage.device()); + + std::lock_guard lock(m_mutex); + BufferBlock* buffer_block = get_allocated_buffer_block(mps_storage.data()); + TORCH_CHECK(buffer_block, "getHostAliasStorage: storage was not allocated by the MPSAllocator"); + TORCH_CHECK(buffer_block->heap->pool->usage & UsageFlags::SHARED, + "getHostAliasStorage: storage is not backed by a shared (unified) MTLBuffer"); + + if (!buffer_block->cpu_ptr) { + buffer_block->cpu_ptr = [buffer_block->buffer contents]; + } + + // Retain the source MPS storage through the DataPtr's context so the + // MTLBuffer cannot be recycled while the host alias is in use. + auto* ctx = new c10::Storage(mps_storage); + c10::DataPtr data_ptr(buffer_block->cpu_ptr, ctx, &hostAliasDeleter, c10::Device(c10::DeviceType::CPU)); + + return c10::Storage(c10::Storage::use_byte_size_t(), + mps_storage.nbytes(), + std::move(data_ptr), + /*allocator=*/nullptr, + /*resizable=*/false); +} + +bool MPSHeapAllocatorImpl::recordEvents(c10::ArrayRef buffers) { + bool recordedEvent = false; + std::lock_guard lock(m_mutex); + + for (const auto& buffer : buffers) { + BufferBlock* buffer_block = get_allocated_buffer_block(buffer); + // return if buffer was not allocated on MPSAllocator or isn't a Shared buffer + if (buffer_block && (buffer_block->heap->pool->usage & UsageFlags::SHARED)) { + if (!buffer_block->event) { + buffer_block->event = m_event_pool->acquireEvent(false, nullptr); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer_block->event); + } + buffer_block->event->record(/*needsLock*/ false); + recordedEvent = true; + } + } + return recordedEvent; +} + +bool MPSHeapAllocatorImpl::waitForEvents(c10::ArrayRef buffers) { + std::vector buffer_blocks; + { + std::lock_guard lock(m_mutex); + for (const auto& buffer : buffers) { + BufferBlock* buffer_block = get_allocated_buffer_block(buffer); + // wait on event if "shared" buffer was allocated on MPSAllocator and + // or actually needs waiting (based on retainCount) + if (buffer_block && (buffer_block->heap->pool->usage & UsageFlags::SHARED) && buffer_block->retainCount() > 1 && + buffer_block->event) { + buffer_blocks.push_back(buffer_block); + } + } + } + bool waitedForEvent = false; + + for (const auto& buffer_block : buffer_blocks) { + // check for retain count again as the previous wait might have released the buffer + if (buffer_block->retainCount() > 1) { + bool waitedOnCPU = buffer_block->event->synchronize(); + if (waitedOnCPU) { + // after waiting, it's a good time to free some pending inactive buffers + freeInactiveBuffers(); + waitedForEvent |= buffer_block->retainCount() <= 1; + } else { + // even if one of the buffers weren't recorded beforehand, we return + // without continuing with other buffers since retainCount > 1 + waitedForEvent = false; + break; + } + } + } + return waitedForEvent; +} + +id_t MPSHeapAllocatorImpl::getBufferId(const void* ptr) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = get_allocated_buffer_block(ptr); + return buffer_block ? buffer_block->buf_id : 0; +} + +ssize_t MPSHeapAllocatorImpl::getUnalignedBufferSize(const void* ptr) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = get_allocated_buffer_block(ptr); + if (buffer_block) { + return (ssize_t)buffer_block->requested_size; + } + // -1 indicates the passed buffer pointer wasn't found + return -1; +} + +void MPSHeapAllocatorImpl::setBufferShape(const void* ptr, const IntArrayRef& shape) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = get_allocated_buffer_block(ptr); + TORCH_INTERNAL_ASSERT(buffer_block, "failed to find the buffer ", ptr); + // note that the IntArrayRef doesn't own the underlying data, and the backing + // memory for shape data must persist as long as the buffer is in use. + // So we need to copy to vector. + buffer_block->shape = shape.vec(); +} + +IntArrayRef MPSHeapAllocatorImpl::getBufferShape(const void* ptr) { + std::lock_guard lock(m_mutex); + + BufferBlock* buffer_block = get_allocated_buffer_block(ptr); + if (buffer_block && !buffer_block->shape.empty()) { + return IntArrayRef{buffer_block->shape}; + } + return IntArrayRef(); +} + +void MPSHeapAllocatorImpl::free(void* ptr) { + BufferBlock* buffer_block = nullptr; + { + std::lock_guard lock(m_mutex); + + buffer_block = get_allocated_buffer_block(ptr); + TORCH_INTERNAL_ASSERT(buffer_block); + const BufferPool& pool = *buffer_block->heap->pool; + if (!(pool.usage & UsageFlags::SCALAR)) { + free_buffer(buffer_block); + return; + } + } + // we sync the scalar pool manually with completion handler at the time buffer is + // freed when the MPSScalar instance goes our of scope + m_stream->addCompletedHandler(^(id) { + std::lock_guard lock(m_mutex); + free_buffer(buffer_block); + }); +} + +void MPSHeapAllocatorImpl::freeInactiveBuffers() { + std::lock_guard lock(m_mutex); + + for (const auto& poolIt : m_pools) { + BufferPool& pool = *poolIt.second; + if (!pool.buffers_pending_free.empty()) { + for (auto it = pool.buffers_pending_free.begin(), last = pool.buffers_pending_free.end(); it != last;) { + BufferBlock* buffer_block = *it; + if (buffer_block->retainCount() <= 1) { + it = pool.buffers_pending_free.erase(it); + free_buffer(buffer_block); + } else { + ++it; + } + } + } + } +} + +void MPSHeapAllocatorImpl::emptyCache() { + std::lock_guard lock(m_mutex); + release_cached_buffers(); +} + +ssize_t MPSHeapAllocatorImpl::getLowWatermarkValue() { + // check if low watermark limit is disabled + if (m_low_watermark_ratio == 0.0) { + return std::numeric_limits::max(); + } + // current_allocated_size could exceed m_low_watermark_limit (e.g., when swapping to disk) + return std::max(0, (ssize_t)(m_low_watermark_limit - current_allocated_size()) / 1048576L); +} + +c10::CachingDeviceAllocator::DeviceStats MPSHeapAllocatorImpl::getDeviceStats() { + std::lock_guard lock(m_mutex); + c10::CachingDeviceAllocator::DeviceStats stats; + // MPS does not distinguish small/large pools in these stats, so only the + // aggregate ("all") entry is populated. + constexpr auto kAggregate = static_cast(c10::CachingAllocator::StatType::AGGREGATE); + stats.allocated_bytes[kAggregate] = m_current_allocated_memory; + stats.reserved_bytes[kAggregate] = m_total_allocated_memory; + return stats; +} + +void MPSHeapAllocatorImpl::resetAccumulatedStats() { + std::lock_guard lock(m_mutex); + m_current_allocated_memory.reset_accumulated(); + m_total_allocated_memory.reset_accumulated(); +} + +void MPSHeapAllocatorImpl::resetPeakStats() { + std::lock_guard lock(m_mutex); + m_current_allocated_memory.reset_peak(); + m_total_allocated_memory.reset_peak(); +} + +inline std::string MPSHeapAllocatorImpl::format_size(uint64_t size) const { + return c10::CachingAllocator::format_size(size); +} + +} // namespace HeapAllocator + +// Use "at::mps::GetMPSAllocator()" to acquire a handle to MPS Allocator +namespace { +HeapAllocator::MPSHeapAllocatorImpl& _getAllocImpl() { + static HeapAllocator::MPSHeapAllocatorImpl s_allocatorImpl; + return s_allocatorImpl; +} +} // namespace + +// MPS allocator struct to be registered with Pytorch +struct TORCH_API MPSAllocator final : public IMPSAllocator { + public: + // Construction is intentionally cheap (no Metal access) so the allocator can + // be registered with c10 at static-init time without forcing MPS/Metal + // initialization in processes that never touch the MPS device. + explicit MPSAllocator(uint32_t Usage) : m_usage(Usage) {} + + // No destructor: the underlying MPSHeapAllocatorImpl singleton empties its own + // cache in its destructor. Calling _getAllocImpl() from here at process exit + // would be unsafe, since that singleton may already have been destroyed. + DeleterFnPtr raw_deleter() const override { + return &Delete; + } + + DataPtr allocate(const size_t nbytes) override { + __block id buf = nbytes > 0 ? _getAllocImpl().malloc(nbytes, m_usage) : nullptr; + return {buf, buf, &Delete, at::Device(at::DeviceType::MPS, 0)}; + } + + // implementation of IMPSAllocator interface + DataPtr allocScalarBufferWithValue(void* value, size_t size) const override { + id buf = _getAllocImpl().allocScalarBufferWithValue(value, size); + return {buf, buf, &Delete, at::Device(at::DeviceType::MPS, 0)}; + } + std::pair getSharedBufferPtr(const void* ptr) const override { + return _getAllocImpl().getSharedBufferPtr(ptr); + } + c10::Storage getHostAliasStorage(const c10::Storage& mps_storage) const override { + return _getAllocImpl().getHostAliasStorage(mps_storage); + } + bool isSharedBuffer(const void* ptr) const override { + return _getAllocImpl().isSharedBuffer(ptr); + } + // c10::DeviceAllocator interface + bool initialized() override { + return HeapAllocator::s_mps_allocator_initialized.load(); + } + void emptyCache(c10::MempoolId_t mempool_id [[maybe_unused]] = {0, 0}) override { + _getAllocImpl().emptyCache(); + } + void recordStream(const DataPtr& ptr [[maybe_unused]], c10::Stream stream [[maybe_unused]]) override { + // MPS executes on a single serial stream, so there is no cross-stream + // dependency to track for buffer reuse. + } + c10::CachingDeviceAllocator::DeviceStats getDeviceStats(c10::DeviceIndex device [[maybe_unused]]) override { + return _getAllocImpl().getDeviceStats(); + } + void resetAccumulatedStats(c10::DeviceIndex device [[maybe_unused]]) override { + _getAllocImpl().resetAccumulatedStats(); + } + void resetPeakStats(c10::DeviceIndex device [[maybe_unused]]) override { + _getAllocImpl().resetPeakStats(); + } + std::pair getMemoryInfo(c10::DeviceIndex device [[maybe_unused]]) override { + const size_t total = _getAllocImpl().getRecommendedMaxMemory(); + const size_t used = _getAllocImpl().getDriverAllocatedMemory(); + return {total > used ? total - used : 0, total}; + } + void freeInactiveBuffers() const override { + _getAllocImpl().freeInactiveBuffers(); + } + ssize_t getUnalignedBufferSize(const void* ptr) const override { + return _getAllocImpl().getUnalignedBufferSize(ptr); + } + id_t getBufferId(const void* ptr) const override { + return _getAllocImpl().getBufferId(ptr); + }; + IntArrayRef getBufferShape(const void* ptr) const override { + return _getAllocImpl().getBufferShape(ptr); + } + void setBufferShape(const void* ptr, const IntArrayRef& shape) const override { + _getAllocImpl().setBufferShape(ptr, shape); + } + size_t getTotalAllocatedMemory() const override { + return _getAllocImpl().getTotalAllocatedMemory(); + } + size_t getCurrentAllocatedMemory() const override { + return _getAllocImpl().getCurrentAllocatedMemory(); + } + size_t getDriverAllocatedMemory() const override { + return _getAllocImpl().getDriverAllocatedMemory(); + } + size_t getRecommendedMaxMemory() const override { + return _getAllocImpl().getRecommendedMaxMemory(); + } + ssize_t getLowWatermarkValue() const override { + return _getAllocImpl().getLowWatermarkValue(); + } + size_t getLowWatermarkLimit() const override { + return _getAllocImpl().getLowWatermarkLimit(); + } + size_t getHighWatermarkLimit() const override { + return _getAllocImpl().getHighWatermarkLimit(); + } + void setLowWatermarkRatio(double ratio) const override { + _getAllocImpl().setLowWatermarkRatio(ratio); + } + void setHighWatermarkRatio(double ratio) const override { + _getAllocImpl().setHighWatermarkRatio(ratio); + } + bool recordEvents(c10::ArrayRef buffers) const override { + return _getAllocImpl().recordEvents(buffers); + } + bool waitForEvents(c10::ArrayRef buffers) const override { + return _getAllocImpl().waitForEvents(buffers); + } + std::string formatSize(size_t size) const override { + return _getAllocImpl().format_size(size); + } + + void copy_data(void* dest, const void* src, std::size_t count) const final { + default_copy_data(dest, src, count); + } + + private: + uint32_t m_usage; + + static void Delete(void* ptr) { + if (ptr) { + _getAllocImpl().free(ptr); + } + } +}; + +namespace { +MPSAllocator& _getSharedAllocator() { + static MPSAllocator s_mps_shared_alloc(HeapAllocator::UsageFlags::SHARED); + return s_mps_shared_alloc; +} + +// Register the shared allocator as the c10 allocator for MPS at static-init +// time so the generic c10::GetAllocator(MPS) / at::getDeviceAllocator(MPS) paths +// (used by the torch.accelerator memory APIs) resolve to it. The allocator is +// cheap to construct and does not touch Metal, so this does not force MPS +// initialization; DeviceAllocator::initialized() reports actual readiness. +struct MPSAllocatorRegisterer { + MPSAllocatorRegisterer() { + c10::SetAllocator(c10::DeviceType::MPS, &_getSharedAllocator()); + } +}; +static MPSAllocatorRegisterer s_mps_allocator_registerer; + +} // anonymous namespace + +IMPSAllocator* getIMPSAllocator() { + // MPS requires unified memory (enforced in MPSHeapAllocatorImpl::init_allocator), + // so the shared allocator is always usable. + return &_getSharedAllocator(); +} + +// torch.is_pinned() implementation +// Pinned memory will be helpful on Apple Silicon Macs with Unified memory as we +// will be able to use SharedStorageMode for MTLBuffer allocations. This will +// avoid extra copies on DataLoading operations. +bool isMPSPinnedPtr(const void* data) { + return at::mps::_getSharedAllocator().isSharedBuffer(data); +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocatorInterface.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocatorInterface.h new file mode 100644 index 0000000000000000000000000000000000000000..eb8bf98cf41c912e6f41da58ea017920fc557fa4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSAllocatorInterface.h @@ -0,0 +1,76 @@ +// Copyright © 2023 Apple Inc. + +#pragma once + +#include +#include +#include +#include +#include + +#define MB(x) (x * 1048576UL) + +namespace at::mps { + +// this is a public interface to access MPSAllocator. +// Do not declare methods that would depend on MPS or Metal frameworks. +class IMPSAllocator : public c10::DeviceAllocator { + public: + // see the comments in MPSAllocator.h for the description of these methods. + virtual void freeInactiveBuffers() const = 0; + virtual ssize_t getUnalignedBufferSize(const void* ptr) const = 0; + virtual IntArrayRef getBufferShape(const void* ptr) const = 0; + virtual id_t getBufferId(const void* ptr) const = 0; + virtual void setBufferShape(const void* ptr, const IntArrayRef& shape) + const = 0; + virtual bool isSharedBuffer(const void* ptr) const = 0; + virtual c10::DataPtr allocScalarBufferWithValue(void* value, size_t size) + const = 0; + virtual std::string formatSize(size_t size) const = 0; + virtual void setLowWatermarkRatio(double ratio) const = 0; + virtual void setHighWatermarkRatio(double ratio) const = 0; + virtual ssize_t getLowWatermarkValue() const = 0; + virtual size_t getLowWatermarkLimit() const = 0; + virtual size_t getHighWatermarkLimit() const = 0; + virtual size_t getTotalAllocatedMemory() const = 0; + virtual size_t getCurrentAllocatedMemory() const = 0; + virtual size_t getDriverAllocatedMemory() const = 0; + virtual size_t getRecommendedMaxMemory() const = 0; + virtual std::pair getSharedBufferPtr( + const void* ptr) const = 0; + // Returns a CPU-device c10::Storage that aliases the host-visible contents + // of the MTLBuffer backing `mps_storage`. The returned storage retains the + // source MPS storage for its lifetime, so the host pointer remains valid + // even after the originating tensor is freed. Raises if `mps_storage` was + // not allocated by the MPSAllocator, or if its MTLBuffer is private rather + // than shared (unified-memory) storage. + virtual c10::Storage getHostAliasStorage( + const c10::Storage& mps_storage) const = 0; + virtual bool recordEvents(c10::ArrayRef buffers) const = 0; + virtual bool waitForEvents(c10::ArrayRef buffers) const = 0; +}; + +class IMpsAllocatorCallback { + public: + enum class EventType { + ALLOCATED, // buffer got allocated to be used immediately + RECYCLED, // buffer pulled from free list to be reused + FREED, // buffer put to free list for future recycling + RELEASED, // buffer memory released + ALLOCATION_FAILED // buffer allocation failed + }; + virtual ~IMpsAllocatorCallback() = default; + virtual void executeMPSAllocatorCallback(void* ptr, EventType event) = 0; +}; + +// MPS allocator will execute every registered callback when a block of memory +// is freed. +TORCH_DECLARE_REGISTRY(MPSAllocatorCallbacksRegistry, IMpsAllocatorCallback); +#define REGISTER_MPS_ALLOCATOR_CALLBACK(name, ...) \ + C10_REGISTER_CLASS(MPSAllocatorCallbacksRegistry, name, __VA_ARGS__) + +IMPSAllocator* getIMPSAllocator(); + +bool isMPSPinnedPtr(const void* data); + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSDevice.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSDevice.h new file mode 100644 index 0000000000000000000000000000000000000000..65af18f2e6d00da5584f3bf85cce936556b5ca48 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSDevice.h @@ -0,0 +1,101 @@ +// Copyright © 2022 Apple Inc. + +#pragma once +#include +#include +#include +#include + +#ifdef __OBJC__ +// Metal.h pulls in Foundation.h, which transitively includes CarbonCore +// headers that emit a flood of -Wdeprecated-declarations on recent macOS SDKs. +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wdeprecated-declarations") +#include +C10_DIAGNOSTIC_POP() +typedef id MTLDevice_t; +#else +typedef void* MTLDevice_t; +#endif + +namespace at::mps { + +// Helper enum to check if a MPSGraph op is supported in a given macOS version +enum class MacOSVersion : uint32_t { + MACOS_14_4 = 0, + MACOS_15_0, + MACOS_15_1, + MACOS_15_2, + MACOS_26_0, + MACOS_26_2, + MACOS_26_4, + MACOS_27_0, +}; + +// Helper enum for GPU-family-gated workarounds +enum class AppleGPUFamily : uint32_t { + APPLE_7_PLUS = 1007, // M1 + APPLE_8_PLUS = 1008, // M2 + APPLE_9_PLUS = 1009, // M3 / M4 + APPLE_10_PLUS = 1010, // M5 +}; + +//----------------------------------------------------------------- +// MPSDevice +// +// MPSDevice is a singleton class that returns the default device +//----------------------------------------------------------------- + +class TORCH_API MPSDevice { + public: + /** + * MPSDevice should not be cloneable. + */ + MPSDevice(MPSDevice& other) = delete; + /** + * MPSDevice should not be assignable. + */ + void operator=(const MPSDevice&) = delete; + /** + * Gets single instance of the Device. + */ + static MPSDevice* getInstance(); + /** + * Returns the single device. + */ + MTLDevice_t device() { + return _mtl_device; + } + /** + * Returns whether running on Ventura or newer + */ + bool isMacOS13Plus(MacOSVersion version) const; + + /** + * Returns device name + */ + std::string getName() const; + + /** + * Returns number of GPU cores. + * 1 Core = 16 ExecutionUnit x 8 ALU x 24 threads + */ + unsigned getCoreCount() const; + + ~MPSDevice(); + + private: + static MPSDevice* _device; + MTLDevice_t _mtl_device; + MPSDevice(); +}; + +TORCH_API bool is_available(); +TORCH_API bool is_macos_at_least(MacOSVersion version); +TORCH_API bool is_apple_family_or_newer(AppleGPUFamily family); +TORCH_API at::Allocator* GetMPSAllocator(); + +inline Device getDeviceFromPtr(void* ptr) { + return {c10::DeviceType::MPS, 0}; +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSDevice.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSDevice.mm new file mode 100644 index 0000000000000000000000000000000000000000..9cc39d40e93b3d1d3fa03cf1c9dfa59b2b6ccd99 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSDevice.mm @@ -0,0 +1,138 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include +#include + +namespace at::mps { + +static inline MTLLanguageVersion getMetalLanguageVersion(const id& device) { + // MPS Advanced Indexing needs at least Metal 2.0 (support for Argument Buffers and function constants) + // host_name attribute needs at least Metal 2.2 and ulong needs Metal 2.3 (supported on MacOS 11+ + TORCH_CHECK([device supportsFamily:MTLGPUFamilyMac2], "Missing Metal support for MTLGPUFamilyMac2"); + return MTLLanguageVersion3_0; +} + +MPSDevice* MPSDevice::getInstance() { + static MPSDevice mps_device; + return &mps_device; +} + +MPSDevice::~MPSDevice() { + [_mtl_device release]; + _mtl_device = nil; +} + +MPSDevice::MPSDevice() : _mtl_device(nil) { + // Check that MacOS 13.0+ version of MPS framework is available + // Create the MPSGraph and check method introduced in 14.0 + // which is used by MPS backend. + id mpsCD = NSClassFromString(@"MPSGraph"); + + if ([mpsCD instancesRespondToSelector:@selector(HermiteanToRealFFTWithTensor:axes:descriptor:name:)] == NO) { + return; + } + + NSArray* devices = [MTLCopyAllDevices() autorelease]; + for (unsigned long i = 0; i < [devices count]; i++) { + id device = devices[i]; + if ([device isLowPower]) { // exclude Intel GPUs + continue; + } + if (![device supportsFamily:MTLGPUFamilyMac2]) { + // Exclude devices that does not support Metal 2.0 + // Virtualised MPS device on MacOS 12.6 should fail this check + TORCH_WARN("Skipping device ", [[device name] UTF8String], " that does not support Metal 2.0"); + continue; + } + _mtl_device = [device retain]; + break; + } + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(_mtl_device); +} + +bool MPSDevice::isMacOS13Plus(MacOSVersion version) const { + auto is_os_version_at_least = [](int major, int minor) { + @autoreleasepool { + NSProcessInfo* processInfo = [[NSProcessInfo new] autorelease]; + return [processInfo + isOperatingSystemAtLeastVersion:{.majorVersion = major, .minorVersion = minor, .patchVersion = 0}]; + } + }; + static bool _macos_14_4_plus = is_os_version_at_least(14, 4); + static bool _macos_15_0_plus = is_os_version_at_least(15, 0); + static bool _macos_15_1_plus = is_os_version_at_least(15, 1); + static bool _macos_15_2_plus = is_os_version_at_least(15, 2); + static bool _macos_26_0_plus = is_os_version_at_least(26, 0); + static bool _macos_26_2_plus = is_os_version_at_least(26, 2); + static bool _macos_26_4_plus = is_os_version_at_least(26, 4); + static bool _macos_27_0_plus = is_os_version_at_least(27, 0); + + switch (version) { + case MacOSVersion::MACOS_14_4: + return _macos_14_4_plus; + case MacOSVersion::MACOS_15_0: + return _macos_15_0_plus; + case MacOSVersion::MACOS_15_1: + return _macos_15_1_plus; + case MacOSVersion::MACOS_15_2: + return _macos_15_2_plus; + case MacOSVersion::MACOS_26_0: + return _macos_26_0_plus; + case MacOSVersion::MACOS_26_2: + return _macos_26_2_plus; + case MacOSVersion::MACOS_26_4: + return _macos_26_4_plus; + case MacOSVersion::MACOS_27_0: + return _macos_27_0_plus; + default: + return false; + } +} + +std::string MPSDevice::getName() const { + @autoreleasepool { + return [[_mtl_device name] UTF8String]; + } +} + +unsigned MPSDevice::getCoreCount() const { + io_iterator_t iterator = 0; + io_registry_entry_t entry = 0; + int core_count = 0; + auto matchingDict = IOServiceMatching("AGXAccelerator"); + TORCH_INTERNAL_ASSERT(matchingDict, "Failed to create matching dict"); + const auto status = IOServiceGetMatchingServices(kIOMainPortDefault, matchingDict, &iterator); + TORCH_INTERNAL_ASSERT(status == KERN_SUCCESS); + while ((entry = IOIteratorNext(iterator)) != 0) { + auto property = IORegistryEntryCreateCFProperty(entry, CFSTR("gpu-core-count"), kCFAllocatorDefault, 0); + auto found = CFNumberGetValue(static_cast(property), kCFNumberIntType, &core_count); + CFRelease(property); + IOObjectRelease(entry); + if (found) { + break; + } + } + IOObjectRelease(iterator); + return core_count; +} + +at::Allocator* GetMPSAllocator() { + return getIMPSAllocator(); +} +bool is_available() { + return MPSDevice::getInstance()->device() != nil; +} + +bool is_macos_at_least(MacOSVersion version) { + return MPSDevice::getInstance()->isMacOS13Plus(version); +} + +bool is_apple_family_or_newer(AppleGPUFamily family) { + // some ops which are on MPSGraph behave differently between GPU families + auto mtl_family = static_cast(family); + return [MPSDevice::getInstance()->device() supportsFamily:mtl_family]; +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSEvent.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSEvent.h new file mode 100644 index 0000000000000000000000000000000000000000..101a37fc1bd4a2fb574104df2b14145dbf833899 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSEvent.h @@ -0,0 +1,105 @@ +// Copyright © 2023 Apple Inc. + +#pragma once + +#include +#include +#include + +namespace at::mps { + +// NOTE: don't create instances of this class directly. +// Use MPSEventPool to acquire instances of MPSEvent. +class MPSEvent { + public: + explicit MPSEvent(id_t ID, MPSStream* stream, bool enable_timing); + ~MPSEvent(); + + // records an event on the stream + void record(bool needsLock, bool syncEvent = false); + // makes all future work submitted to the stream wait for this event. + bool wait(bool needsLock, bool syncEvent = false); + // schedules a notifyListener callback for the event. + bool notify(bool needsLock, MTLSharedEventNotificationBlock block); + // checks if events are already signaled. + bool query() const; + // blocks the CPU thread until all the GPU work that were scheduled + // prior to recording this event are completed. + bool synchronize(); + // resets this event with new parameters in case it gets reused from the event + // pool + void reset(MPSStream* stream, bool enable_timing); + // returns the unique ID of the event instance + id_t getID() const { + return m_id; + } + // returns the completion timestamp of the event + uint64_t getCompletionTime() const { + return m_completion_time; + } + // if already recorded, waits for cpu_sync_cv to be signaled + void waitForCpuSync(); + + private: + id_t m_id; + // enables measuring the completion time of the notifyListener of this event + bool m_enable_timing; + uint64_t m_signalCounter = 0; + MPSStream* m_stream = nullptr; + MTLSharedEvent_t m_event = nullptr; + MTLSharedEventListener* m_listener = nullptr; + // used to sync the events created on this Stream with CPU + std::mutex m_cpu_sync_mutex{}; + std::condition_variable m_cpu_sync_cv{}; + // CondVar predicate to sync the events created on this Stream with CPU + bool m_cpu_sync_completed = false; + // used to compute elapsed time + uint64_t m_completion_time = 0; + + void recordLocked(bool syncEvent); + bool waitLocked(bool syncEvent); + bool notifyLocked(MTLSharedEventNotificationBlock block); + void notifyCpuSync(); + static uint64_t getTime() { + return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW); + } +}; + +typedef std::unique_ptr> MPSEventPtr; + +class MPSEventPool { + public: + explicit MPSEventPool(MPSStream* default_stream); + ~MPSEventPool(); + + MPSEventPtr acquireEvent(bool enable_timing, MPSStream* stream); + void emptyCache(); + + // these are mainly used for MPSHooks and torch.mps.Event() bindings + id_t acquireEvent(bool enable_timing); + void releaseEvent(id_t event_id); + void recordEvent(id_t event_id, bool syncEvent); + void waitForEvent(id_t event_id, bool syncEvent); + void synchronizeEvent(id_t event_id); + bool queryEvent(id_t event_id); + // returns elapsed time between two recorded events in milliseconds + double elapsedTime(id_t start_event_id, id_t end_event_id); + + private: + MPSStream* m_default_stream = nullptr; + std::recursive_mutex m_mutex; + std::stack> m_pool{}; + // dictionary to associate event IDs with event objects + // used to retain in-use events out of the pool + // for torch.mps.Event() bindings. + std::unordered_map m_in_use_events{}; + uint64_t m_event_counter = 0; + std::function m_default_deleter; + + MPSEvent* getInUseEvent(id_t event_id, bool locked = true); +}; + +// shared_ptr is used to get MPSEventPool destroyed after dependent instances +std::shared_ptr getMPSEventPool(); + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSEvent.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSEvent.mm new file mode 100644 index 0000000000000000000000000000000000000000..211fc2e9512099d7b019582b35a5cee40b0a661e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSEvent.mm @@ -0,0 +1,257 @@ +// Copyright © 2023 Apple Inc. + +#include + +namespace at::mps { + +MPSEvent::MPSEvent(id_t ID, MPSStream* stream, bool enable_timing) + : m_id(ID), m_enable_timing(enable_timing), m_stream(stream), m_event([stream->device() newSharedEvent]) {} + +MPSEvent::~MPSEvent() { + if (m_event) { + [m_event release]; + m_event = nil; + } + if (m_listener) { + [m_listener release]; + m_listener = nil; + } +} + +void MPSEvent::recordLocked(bool syncEvent) { + // active encoders must end before encoding or waiting + m_stream->endKernelCoalescing(); + ++m_signalCounter; + if (m_enable_timing) { + notifyLocked(^(id, uint64_t) { + m_completion_time = getTime(); + notifyCpuSync(); + }); + } + id commandBuffer = m_stream->commandBuffer(); + [commandBuffer encodeSignalEvent:m_event value:m_signalCounter]; + if (syncEvent) { + m_stream->synchronize(SyncType::COMMIT); + } +} + +bool MPSEvent::waitLocked(bool syncEvent) { + // check if event is not recorded yet + if (m_event.signaledValue >= m_signalCounter) { + return false; + } + // active encoders must end before encoding or waiting + m_stream->endKernelCoalescing(); + id commandBuffer = m_stream->commandBuffer(); + [commandBuffer encodeWaitForEvent:m_event value:m_signalCounter]; + if (syncEvent) { + m_stream->synchronize(SyncType::COMMIT); + } + return true; +} + +bool MPSEvent::notifyLocked(MTLSharedEventNotificationBlock block) { + // check if event is not recorded yet + if (m_event.signaledValue >= m_signalCounter) { + return false; + } + if (!m_listener) { + m_listener = [[MTLSharedEventListener alloc] init]; + } + [m_event notifyListener:m_listener atValue:m_signalCounter block:block]; + return true; +} + +void MPSEvent::record(bool needsLock, bool syncEvent) { + if (!needsLock) { + recordLocked(syncEvent); + return; + } + dispatch_sync(m_stream->queue(), ^() { + @autoreleasepool { + recordLocked(syncEvent); + } + }); +} + +bool MPSEvent::wait(bool needsLock, bool syncEvent) { + __block bool waited = false; + if (!needsLock) { + return waitLocked(syncEvent); + } + dispatch_sync(m_stream->queue(), ^() { + @autoreleasepool { + waited = waitLocked(syncEvent); + } + }); + return waited; +} + +bool MPSEvent::notify(bool needsLock, MTLSharedEventNotificationBlock block) { + if (!needsLock) { + return notifyLocked(block); + } + __block bool scheduledNotify = false; + dispatch_sync(m_stream->queue(), ^() { + @autoreleasepool { + scheduledNotify = notifyLocked(block); + } + }); + return scheduledNotify; +} + +void MPSEvent::notifyCpuSync() { + std::lock_guard lock(m_cpu_sync_mutex); + m_cpu_sync_completed = true; + m_cpu_sync_cv.notify_one(); +} + +void MPSEvent::waitForCpuSync() { + std::unique_lock lock(m_cpu_sync_mutex); + m_cpu_sync_cv.wait(lock, [&] { return m_cpu_sync_completed; }); + m_cpu_sync_completed = false; +} + +bool MPSEvent::synchronize() { + bool scheduledNotify = notifyLocked(^(id, uint64_t) { + m_completion_time = getTime(); + notifyCpuSync(); + }); + + if (scheduledNotify) { + waitForCpuSync(); + return true; + } + return false; +} + +bool MPSEvent::query() const { + // return false if not recorded or signaled yet + return m_signalCounter && (m_event.signaledValue >= m_signalCounter); +} + +void MPSEvent::reset(MPSStream* stream, bool enable_timing) { + if (stream != m_stream) { + m_signalCounter = 0; + m_event.signaledValue = 0; + m_stream = stream; + } + // reset record time + m_completion_time = 0; + m_enable_timing = enable_timing; + m_cpu_sync_completed = false; +}; + +//----------------------------------------------------------------- +// MPSEventPool +//----------------------------------------------------------------- + +MPSEventPool::MPSEventPool(MPSStream* default_stream) : m_default_stream(default_stream) { + // default deleter to return the event back to pool after it gets released + m_default_deleter = [&](MPSEvent* event) { + std::lock_guard lock(m_mutex); + m_pool.push(std::unique_ptr(event)); + }; +} + +MPSEventPool::~MPSEventPool() { + emptyCache(); +} + +MPSEventPtr MPSEventPool::acquireEvent(bool enable_timing, MPSStream* stream) { + if (!stream) { + stream = m_default_stream; + } + { + std::lock_guard lock(m_mutex); + if (!m_pool.empty()) { + auto event = m_pool.top().release(); + m_pool.pop(); + event->reset(stream, enable_timing); + return MPSEventPtr(event, m_default_deleter); + } + } + auto new_event = std::make_unique(++m_event_counter, stream, enable_timing); + return MPSEventPtr(new_event.release(), m_default_deleter); +} + +void MPSEventPool::emptyCache() { + std::lock_guard lock(m_mutex); + while (!m_pool.empty()) { + m_pool.pop(); + } +} + +id_t MPSEventPool::acquireEvent(bool enable_timing) { + std::lock_guard lock(m_mutex); + MPSEventPtr event = acquireEvent(enable_timing, nullptr); + TORCH_INTERNAL_ASSERT(event); + id_t event_id = event->getID(); + m_in_use_events.emplace(event_id, std::move(event)); + return event_id; +} + +void MPSEventPool::releaseEvent(id_t event_id) { + std::lock_guard lock(m_mutex); + TORCH_CHECK(m_in_use_events.count(event_id) > 0, "Invalid Event ID: ", event_id); + // returns the event back to the MPSEventPool + m_in_use_events.erase(event_id); +} + +void MPSEventPool::recordEvent(id_t event_id, bool syncEvent) { + MPSEvent* event = getInUseEvent(event_id); + event->record(/*needsLock*/ true, syncEvent); +} + +void MPSEventPool::waitForEvent(id_t event_id, bool syncEvent) { + MPSEvent* event = getInUseEvent(event_id); + event->wait(/*needsLock*/ true, syncEvent); +} + +void MPSEventPool::synchronizeEvent(id_t event_id) { + MPSEvent* event = getInUseEvent(event_id); + event->synchronize(); +} + +bool MPSEventPool::queryEvent(id_t event_id) { + MPSEvent* event = getInUseEvent(event_id); + return event->query(); +} + +double MPSEventPool::elapsedTime(id_t start_event_id, id_t end_event_id) { + // first make sure notifyListeners are called to capture events' completion times + dispatch_sync(m_default_stream->queue(), ^() { + m_default_stream->synchronize(SyncType::COMMIT_AND_WAIT); + }); + std::lock_guard lock(m_mutex); + MPSEvent* start_event = getInUseEvent(start_event_id, false); + MPSEvent* end_event = getInUseEvent(end_event_id, false); + // the notify is called on a separate thread, so this waits for that + end_event->waitForCpuSync(); + const uint64_t start_time = start_event->getCompletionTime(); + const uint64_t end_time = end_event->getCompletionTime(); + + TORCH_CHECK(start_time > 0 && end_time > 0, "Events were not created with argument 'enable_timing=True'"); + TORCH_CHECK( + end_time > start_time, "End event ", end_event_id, " was not recorded after start event ", start_event_id); + return double(end_time - start_time) * 1e-6; +} + +MPSEvent* MPSEventPool::getInUseEvent(id_t event_id, bool locked) { + if (locked) { + m_mutex.lock(); + } + TORCH_CHECK(m_in_use_events.count(event_id) > 0, "Invalid Event ID: ", event_id); + MPSEvent* event = m_in_use_events[event_id].get(); + if (locked) { + m_mutex.unlock(); + } + return event; +} + +std::shared_ptr getMPSEventPool() { + static std::shared_ptr event_pool = std::make_shared(getDefaultMPSStream()); + return event_pool; +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSFallback.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSFallback.mm new file mode 100644 index 0000000000000000000000000000000000000000..37d6a5912c1b3ada4e348e5b87a9e73f311a4d5a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSFallback.mm @@ -0,0 +1,118 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include +#include + +namespace at { +#ifdef USE_DISTRIBUTED +static void mps_distributed_error(const c10::OperatorHandle& op) { + // c10d ops should never fall back to CPU as they require device-specific implementations + TORCH_CHECK_NOT_IMPLEMENTED( + op.operator_name().getNamespace().value_or("") != "c10d", + "The distributed operator '", + op.schema().operator_name(), + "' is not currently implemented ", + "for the MPS device. If you want this op to be considered for addition ", + "please comment on https://github.com/pytorch/pytorch/issues/141287 and mention use-case, that resulted in missing op", + " as well as commit hash ", + caffe2::GetBuildOptions().at("COMMIT_SHA"), + ". Please note, that distributed operators can not fall back to CPU"); +} +#endif + +static void mps_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { +#ifdef USE_DISTRIBUTED + mps_distributed_error(op); +#endif + + TORCH_WARN_ONCE("The operator '", + op.schema().operator_name(), + "' is not currently supported ", + "on the MPS backend and will fall back to run on the CPU.", + " This may have performance implications."); + + auto& profiler = mps::getMPSProfiler(); + const bool isCPUFallbackProfilingEnabled = profiler.isCPUFallbackProfilingEnabled(); + + // only do profiling if CPU Fallback op execution tracing or logging is enabled + if (isCPUFallbackProfilingEnabled) { + // we create a Tensors list to compute the size of copies required to convert + // the input MPS tensors to CPU, and the CPU results back to MPS + std::vector tensor_args; + for (const auto& ivalue : torch::jit::last(stack, op.schema().arguments().size())) { + if (ivalue.isTensor()) { + tensor_args.push_back(ivalue.toTensor()); + } + } + // TODO: check if any returns exist at this stage + for (const auto& ivalue : torch::jit::last(stack, op.schema().returns().size())) { + if (ivalue.isTensor()) { + tensor_args.push_back(ivalue.toTensor()); + } + } + profiler.beginProfileCPUFallback(op.schema().name(), tensor_args); + } + + native::cpu_fallback(op, stack); + + if (isCPUFallbackProfilingEnabled) { + profiler.endProfileCPUFallback(op.schema().name()); + } +} + +static void mps_error_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack) { +#ifdef USE_DISTRIBUTED + mps_distributed_error(op); +#endif + TORCH_CHECK_NOT_IMPLEMENTED( + false, + "The operator '", + op.schema().operator_name(), + "' is not currently implemented ", + "for the MPS device. If you want this op to be considered for addition ", + "please comment on https://github.com/pytorch/pytorch/issues/141287 and mention use-case, that resulted in missing op", + " as well as commit hash ", + caffe2::GetBuildOptions().at("COMMIT_SHA"), + ". As a temporary fix, you can set the environment variable `PYTORCH_ENABLE_MPS_FALLBACK=1` ", + "to use the CPU as a fallback for this op. WARNING: this will be slower than running natively ", + "on MPS."); +} + +// This dispatch should never be called for tensor on MPS but is frequently called +// If one of them are on CPU +static Tensor slow_conv2d_forward_mps(const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + const std::optional& bias, + IntArrayRef stride, + IntArrayRef padding) { + TORCH_CHECK(self.device() == weight.device(), + __func__, + ": input(device='", + self.device(), + "') and weight(device=", + weight.device(), + "') must be on the same device"); + TORCH_INTERNAL_ASSERT(false, __func__, " should not be called for both tensors on MPS device"); +} + +TORCH_LIBRARY_IMPL(_, MPS, m) { + static const auto enable_mps_fallback = c10::utils::get_env("PYTORCH_ENABLE_MPS_FALLBACK"); + if (!enable_mps_fallback || enable_mps_fallback == "0") { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&mps_error_fallback>()); + } else { + m.fallback(torch::CppFunction::makeFromBoxedFunction<&mps_fallback>()); + } +} + +TORCH_LIBRARY_IMPL(aten, MPS, m) { + // These ops are not supported via MPS backend currently, and we fallback to run on CPU. + // For the rest of unsupported ops the user needs to pass 'PYTORCH_ENABLE_MPS_FALLBACK=1' + // to fallback on CPU, otherwise we will error out. + m.impl("embedding_renorm_", torch::CppFunction::makeFromBoxedFunction<&mps_fallback>()); + m.impl("_slow_conv2d_forward", slow_conv2d_forward_mps); +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGeneratorImpl.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGeneratorImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..4cab0b7f7879dd62c2c62ff4c2fd1cbd22766e10 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGeneratorImpl.h @@ -0,0 +1,61 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#include +#include +#include +#include + +namespace at { +namespace mps::detail { + +constexpr uint32_t PHILOX_STATE_N = 7; +struct rng_data_pod { + std::array state{1}; + uint64_t seed = default_rng_seed_val; +}; + +TORCH_API const Generator& getDefaultMPSGenerator(); +TORCH_API Generator +createMPSGenerator(uint64_t seed_val = default_rng_seed_val); + +} // namespace mps::detail + +struct TORCH_API MPSGeneratorImpl : public c10::GeneratorImpl { + // Constructors + MPSGeneratorImpl(uint64_t seed_in = default_rng_seed_val); + ~MPSGeneratorImpl() override = default; + + // MPSGeneratorImpl methods + std::shared_ptr clone() const; + void set_current_seed(uint64_t seed) override; + void set_offset(uint64_t offset) override; + uint64_t get_offset() const override; + uint64_t current_seed() const override; + uint64_t seed() override; + void set_state(const c10::TensorImpl& new_state) override; + c10::intrusive_ptr get_state() const override; + void update_philox_counters(); + + void set_engine(at::Philox4_32 engine) { + engine_ = engine; + } + at::Philox4_32 engine() { + return engine_; + } + uint32_t* state_data() { + return data_.state.data(); + } + static DeviceType device_type() { + return DeviceType::MPS; + } + + private: + mps::detail::rng_data_pod data_; + at::Philox4_32 engine_; + + MPSGeneratorImpl* clone_impl() const override; +}; + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGeneratorImpl.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGeneratorImpl.mm new file mode 100644 index 0000000000000000000000000000000000000000..88a039be90800e0858cfda78983cb4aefd89af81 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGeneratorImpl.mm @@ -0,0 +1,120 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include + +namespace at { +namespace mps::detail { + +const Generator& getDefaultMPSGenerator() { + static auto default_gen_mps = createMPSGenerator(c10::detail::getNonDeterministicRandom()); + return default_gen_mps; +} + +Generator createMPSGenerator(uint64_t seed_val) { + auto gen = make_generator(seed_val); + gen.set_current_seed(seed_val); + return gen; +} + +} // namespace mps::detail + +MPSGeneratorImpl::MPSGeneratorImpl(uint64_t seed_in) + : c10::GeneratorImpl{Device(DeviceType::MPS, 0), DispatchKeySet(c10::DispatchKey::MPS)}, + data_({.seed = seed_in}), + engine_(seed_in, 0, 0) {} + +void MPSGeneratorImpl::set_current_seed(uint64_t seed) { + data_.seed = seed; + data_.state.fill(1); + // the two last state values are the Philox keys + // TODO: make "key" in PhiloxRNGEngine.h public so we don't duplicate code here + data_.state[5] = static_cast(seed); + data_.state[6] = static_cast(seed >> 32); + engine_.reset_state(seed); +} + +void MPSGeneratorImpl::set_offset(uint64_t offset) { + engine_.set_offset(offset); +} + +uint64_t MPSGeneratorImpl::get_offset() const { + return engine_.get_offset(); +} + +uint64_t MPSGeneratorImpl::current_seed() const { + return data_.seed; +} + +uint64_t MPSGeneratorImpl::seed() { + auto random = c10::detail::getNonDeterministicRandom(); + this->set_current_seed(random); + return random; +} + +// See Note [Acquire lock when using random generators] +void MPSGeneratorImpl::update_philox_counters() { + // calling engine_() would call operator() of philox_engine class to + // get each of the four newly generated counter values (see PhiloxRNGEngine.h). + for (int i = 1; i <= 4; i++) { + data_.state[i] = engine_(); + } +} + +c10::intrusive_ptr MPSGeneratorImpl::get_state() const { + constexpr size_t states_size = mps::detail::PHILOX_STATE_N * sizeof(uint32_t); + constexpr size_t seed_size = sizeof(uint64_t); + constexpr size_t offset_size = sizeof(uint64_t); + constexpr size_t total_size = states_size + seed_size + offset_size; + + auto state_tensor = at::detail::empty_cpu( + {(int64_t)total_size}, ScalarType::Byte, std::nullopt, std::nullopt, std::nullopt, std::nullopt); + auto rng_state = state_tensor.data_ptr(); + auto current_seed = this->current_seed(); + auto current_offset = this->get_offset(); + + static_assert(sizeof(decltype(current_seed)) == seed_size, "current_seed size is wrong"); + static_assert(sizeof(decltype(current_offset)) == offset_size, "current_offset size is wrong"); + + memcpy(rng_state, this->data_.state.data(), states_size); + memcpy(rng_state + states_size, ¤t_seed, seed_size); + memcpy(rng_state + states_size + seed_size, ¤t_offset, offset_size); + + return state_tensor.getIntrusivePtr(); +} + +void MPSGeneratorImpl::set_state(const c10::TensorImpl& new_state) { + constexpr size_t states_size = mps::detail::PHILOX_STATE_N * sizeof(uint32_t); + constexpr size_t seed_size = sizeof(uint64_t); + constexpr size_t offset_size = sizeof(uint64_t); + constexpr size_t total_size = states_size + seed_size + offset_size; + + detail::check_rng_state(new_state); + + auto new_state_size = new_state.numel(); + TORCH_CHECK(new_state_size == total_size, "RNG state is wrong size"); + + uint64_t input_seed = default_rng_seed_val; + uint64_t input_offset = 0; + auto new_rng_state = new_state.data_dtype_initialized(); + memcpy(&input_seed, new_rng_state + states_size, seed_size); + this->set_current_seed(input_seed); + memcpy(&input_offset, new_rng_state + states_size + seed_size, offset_size); + this->set_offset(input_offset); + // state.data must be copied after input_seed to not reset the state in set_current_seed() + memcpy(this->state_data(), new_rng_state, states_size); +} + +std::shared_ptr MPSGeneratorImpl::clone() const { + return std::shared_ptr(this->clone_impl()); +} + +MPSGeneratorImpl* MPSGeneratorImpl::clone_impl() const { + auto gen = new MPSGeneratorImpl(); + gen->data_ = this->data_; + gen->engine_ = this->engine_; + return gen; +} + +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGuardImpl.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGuardImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..1d35929c97a907064f35dcee8899eb1a801bbd81 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGuardImpl.h @@ -0,0 +1,194 @@ +// Copyright © 2022 Apple Inc. + +#pragma once +#include +#include +#include +#include +#include +#include + +#ifdef __OBJC__ +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::mps { + +typedef MPSEvent* mpsEvent_t; + +// TODO: Move the MPSGuardImpl to inherit from NoOpDeviceGuardImpl +// https://github.com/pytorch/pytorch/issues/77170 +struct TORCH_API MPSGuardImpl final + : public c10::impl::DeviceGuardImplInterface { + static constexpr c10::DeviceType static_type = c10::DeviceType::MPS; + + // constructor + MPSGuardImpl() = default; + explicit MPSGuardImpl(c10::DeviceType t) { + TORCH_CHECK( + t == DeviceType::MPS, + "MPSGuardImpl initialized with non-MPS DeviceType: ", + t); + } + + // returns the type + c10::DeviceType type() const override { + return c10::DeviceType::MPS; + } + + Device exchangeDevice(Device d) const override { + return Device(c10::DeviceType::MPS, 0); + } + + Device getDevice() const override { + return Device(c10::DeviceType::MPS, 0); + } + + std::optional uncheckedGetDevice() const noexcept { + return Device(c10::DeviceType::MPS, 0); + } + + void setDevice(Device d) const override { + TORCH_CHECK(d.is_mps(), "Expected a MPS device, but got ", d); + } + + void uncheckedSetDevice(Device d) const noexcept override { + // TODO: Currently setting only device 0 + } + + Stream getStream(Device d) const override { + return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0)); + } + + Stream getNewStream(Device, int priority = 0) const override { + (void)priority; + return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0)); + } + + Stream getDefaultStream(Device d) const override { + return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0)); + } + + // NB: These do NOT set the current device + Stream exchangeStream(Stream s) const override { + return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0)); + } + DeviceCapability getDeviceCapability(Device /* unused */) const override { + DeviceCapability cap; + cap.capability_data.capability_bits = (1ULL << kIndex_Byte) | + (1ULL << kIndex_Char) | (1ULL << kIndex_Short) | (1ULL << kIndex_Int) | + (1ULL << kIndex_Long) | (1ULL << kIndex_Half) | (1ULL << kIndex_Float) | + (1ULL << kIndex_ComplexHalf) | (1ULL << kIndex_ComplexFloat) | + (1ULL << kIndex_Bool) | (1ULL << kIndex_BFloat16) | + (1ULL << kIndex_UInt32) | (1ULL << kIndex_UInt16) | + (1ULL << kIndex_UInt64); + return cap; + } + + DeviceIndex deviceCount() const noexcept override { + if (at::hasMPS()) { + // TODO: extend it for multi-device case + return 1; + } else { + return 0; + } + } + + // Event-related functions + void createEvent(mpsEvent_t* event, const EventFlag flag) const; + + void destroyEvent(void* event, const DeviceIndex device_index) + const noexcept override; + + void record( + void** event, + const Stream& stream, + const DeviceIndex device_index, + const EventFlag flag) const override; + + void block(void* event, const Stream& stream) const override; + + bool queryEvent(void* event) const override; + + void synchronizeEvent(void* event) const override; + + double elapsedTime(void* event1, void* event2, const DeviceIndex device_index) + const override; + + void synchronizeDevice(const DeviceIndex device_index) const override; +}; + +/// A variant of OptionalDeviceGuard that is specialized for MPS. +struct OptionalMPSGuard { + explicit OptionalMPSGuard() : guard_() {} + + explicit OptionalMPSGuard(std::optional device_opt) + : guard_(device_opt) {} + + /// Set the current MPS device to the passed device index, if it is not + /// nullopt + explicit OptionalMPSGuard(std::optional device_index_opt) + : guard_(device_index_opt) {} + + // Copy is not allowed + OptionalMPSGuard(const OptionalMPSGuard&) = delete; + OptionalMPSGuard& operator=(const OptionalMPSGuard&) = delete; + OptionalMPSGuard(OptionalMPSGuard&& other) = delete; + OptionalMPSGuard& operator=(OptionalMPSGuard&& other) = delete; + + /// Sets the MPS device to the given device, initializing the guard if it + /// is not already initialized. Errors if the given device is not a MPS + /// device. + void set_device(Device device) { + guard_.set_device(device); + } + + /// Sets the MPS device to the given device, initializing the guard if it is + /// not already initialized. Errors if the given device is not a MPS device. + void reset_device(Device device) { + guard_.reset_device(device); + } + + /// Sets the MPS device to the given device index, initializing the guard if + /// it is not already initialized. + void set_index(DeviceIndex device_index) { + guard_.set_index(device_index); + } + + /// Returns the device that was set immediately prior to initialization of the + /// guard, or nullopt if the guard is uninitialized. + std::optional original_device() const { + return guard_.original_device(); + } + + /// Returns the most recent device that was set using this device guard, + /// either from construction, or via set_device, if the guard is initialized, + /// or nullopt if the guard is uninitialized. + std::optional current_device() const { + return guard_.current_device(); + } + + /// Restore the original MPS device, resetting this guard to uninitialized + /// state. + void reset() { + guard_.reset(); + } + + private: + c10::impl::InlineOptionalDeviceGuard guard_; +}; + +C10_REGISTER_GUARD_IMPL(MPS, MPSGuardImpl) + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGuardImpl.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGuardImpl.mm new file mode 100644 index 0000000000000000000000000000000000000000..c24ee335f30d1481489dfc5973348e09a25d0ea1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSGuardImpl.mm @@ -0,0 +1,69 @@ +// Copyright © 2022 Apple Inc. + +#include +#include + +namespace at::mps { + +void MPSGuardImpl::createEvent(mpsEvent_t* event, const EventFlag flag) const {} + +void MPSGuardImpl::destroyEvent(void* event, const DeviceIndex device_index) const noexcept { + if (!event) + return; + + auto mps_event_id = (__bridge id_t)(intptr_t)(event); + at::mps::getMPSEventPool()->releaseEvent(mps_event_id); +} + +void MPSGuardImpl::record(void** event, + const Stream& stream, + const DeviceIndex device_index, + const EventFlag flag) const { + TORCH_CHECK(device_index == -1 || device_index == stream.device_index(), + "Event device index ", + device_index, + " does not match recording stream's device index ", + stream.device_index(), + "."); + + // Check if the MPS event ID is valid. If not, acquire a new event from the + // MPS event pool and assign it to the event pointer. Then record the event in + // the MPS event pool. + auto mps_event_id = (__bridge id_t)(intptr_t)(*event); + if (!mps_event_id) { + mps_event_id = at::mps::getMPSEventPool()->acquireEvent(flag == EventFlag::BACKEND_DEFAULT); + *event = (__bridge void*)(intptr_t)(mps_event_id); + } + MPSStream mps_stream{stream}; + at::mps::getMPSEventPool()->recordEvent(mps_event_id, true); +} + +void MPSGuardImpl::block(void* event, const Stream& stream) const { + auto mps_event_id = (__bridge id_t)(intptr_t)(event); + MPSStream mps_stream{stream}; + + at::mps::getMPSEventPool()->waitForEvent(mps_event_id, false); +} + +bool MPSGuardImpl::queryEvent(void* event) const { + auto mps_event_id = (__bridge id_t)(intptr_t)(event); + return at::mps::getMPSEventPool()->queryEvent(mps_event_id); +} + +void MPSGuardImpl::synchronizeEvent(void* event) const { + auto mps_event_id = (__bridge id_t)(intptr_t)(event); + return at::mps::getMPSEventPool()->synchronizeEvent(mps_event_id); +} + +double MPSGuardImpl::elapsedTime(void* event1, void* event2, const DeviceIndex device_index) const { + TORCH_CHECK(event1 && event2, "Both events must be recorded before calculating elapsed time."); + auto start_event_id = (__bridge id_t)(intptr_t)(event1); + auto end_event_id = (__bridge id_t)(intptr_t)(event2); + return at::mps::getMPSEventPool()->elapsedTime(start_event_id, end_event_id); +} + +void MPSGuardImpl::synchronizeDevice(const DeviceIndex device_index) const { + at::mps::getDefaultMPSStream()->synchronize(SyncType::COMMIT_AND_WAIT); +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSHooks.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSHooks.h new file mode 100644 index 0000000000000000000000000000000000000000..47f1c151dca36f2cc3bfcf48b6b5c8328cc09516 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSHooks.h @@ -0,0 +1,75 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#include +#include +#include +#include + +namespace at::mps { + +// The real implementation of MPSHooksInterface +struct MPSHooks : public at::MPSHooksInterface { + MPSHooks() {} + void init() const override; + + // MPSDevice interface + bool hasMPS() const override; + bool isOnMacOSorNewer(unsigned major, unsigned minor) const override; + + Device getDeviceFromPtr(void* data) const override; + + // MPSGeneratorImpl interface + const Generator& getDefaultGenerator( + DeviceIndex device_index = -1) const override; + Generator getNewGenerator(DeviceIndex device_index = -1) const override; + + // MPSStream interface + void deviceSynchronize() const override; + void commitStream() const override; + void* getCommandBuffer() const override; + void* getDispatchQueue() const override; + + // MPSAllocator interface + Allocator* getMPSDeviceAllocator() const override; + void emptyCache() const override; + size_t getCurrentAllocatedMemory() const override; + size_t getDriverAllocatedMemory() const override; + size_t getRecommendedMaxMemory() const override; + void setMemoryFraction(double ratio) const override; + size_t getMaxBufferLength() const override; + bool isPinnedPtr(const void* data) const override; + Allocator* getPinnedMemoryAllocator() const override; + + // MPSProfiler interface + void profilerStartTrace(const std::string& mode, bool waitUntilCompleted) + const override; + void profilerStopTrace() const override; + + // MPSEvent interface + uint32_t acquireEvent(bool enable_timing) const override; + void releaseEvent(uint32_t event_id) const override; + void recordEvent(uint32_t event_id) const override; + void waitForEvent(uint32_t event_id) const override; + void synchronizeEvent(uint32_t event_id) const override; + bool queryEvent(uint32_t event_id) const override; + double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id) + const override; + + bool isBuilt() const override { + return true; + } + bool isAvailable() const override { + return hasMPS(); + } + bool hasPrimaryContext(DeviceIndex device_index) const override { + // When MPS is available, it is always in use for the one device. + return true; + } + DeviceIndex deviceCount() const override { + return hasMPS() ? 1 : 0; + } +}; + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSHooks.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSHooks.mm new file mode 100644 index 0000000000000000000000000000000000000000..645a41264560e2e47557c795825a77a1b2ebc836 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSHooks.mm @@ -0,0 +1,170 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::mps { + +void MPSHooks::init() const { + C10_LOG_API_USAGE_ONCE("aten.init.mps"); + // TODO: initialize MPS devices and streams here +} + +bool MPSHooks::hasMPS() const { + return at::mps::is_available(); +} + +bool MPSHooks::isOnMacOSorNewer(unsigned major, unsigned minor) const { + switch (major) { + case 26: + switch (minor) { + case 0: + return is_macos_at_least(MacOSVersion::MACOS_26_0); + default: + TORCH_WARN("Can't check whether running on 26.", minor, "+ returning one for 26.0+"); + return is_macos_at_least(MacOSVersion::MACOS_26_0); + } + case 15: + switch (minor) { + case 0: + return is_macos_at_least(MacOSVersion::MACOS_15_0); + case 1: + return is_macos_at_least(MacOSVersion::MACOS_15_1); + default: + TORCH_WARN("Can't check whether running on 15.", minor, "+ returning one for 15.1+"); + return is_macos_at_least(MacOSVersion::MACOS_15_1); + } + case 14: + switch (minor) { + case 0: + return true; + case 4: + return is_macos_at_least(MacOSVersion::MACOS_14_4); + default: + TORCH_WARN("Can't check whether running on 14.", minor, "+ returning one for 14.4+"); + return is_macos_at_least(MacOSVersion::MACOS_14_4); + } + case 13: + return true; + default: + TORCH_WARN("Checking for unexpected MacOS ", major, ".", minor, " returning false"); + return false; + } +} + +Allocator* MPSHooks::getMPSDeviceAllocator() const { + return at::mps::GetMPSAllocator(); +} + +const Generator& MPSHooks::getDefaultGenerator([[maybe_unused]] DeviceIndex device_index) const { + return at::mps::detail::getDefaultMPSGenerator(); +} + +Generator MPSHooks::getNewGenerator([[maybe_unused]] DeviceIndex device_index) const { + return make_generator(); +} + +void MPSHooks::deviceSynchronize() const { + at::mps::getDefaultMPSStream()->synchronize(SyncType::COMMIT_AND_WAIT); +} + +void MPSHooks::commitStream() const { + at::mps::getDefaultMPSStream()->synchronize(SyncType::COMMIT); +} + +void* MPSHooks::getCommandBuffer() const { + auto stream = at::mps::getDefaultMPSStream(); + // Release pending computeCommandEncoder, as extensions is likely to allocate new one + stream->endKernelCoalescing(); + return stream->commandBuffer(); +} + +void* MPSHooks::getDispatchQueue() const { + return at::mps::getDefaultMPSStream()->queue(); +} + +void MPSHooks::emptyCache() const { + at::mps::getIMPSAllocator()->emptyCache(); + at::native::mps::MPSGraphCache::getInstance()->clear(); +} + +size_t MPSHooks::getCurrentAllocatedMemory() const { + return at::mps::getIMPSAllocator()->getCurrentAllocatedMemory(); +} + +size_t MPSHooks::getDriverAllocatedMemory() const { + return at::mps::getIMPSAllocator()->getDriverAllocatedMemory(); +} + +size_t MPSHooks::getRecommendedMaxMemory() const { + return at::mps::getIMPSAllocator()->getRecommendedMaxMemory(); +} + +size_t MPSHooks::getMaxBufferLength() const { + return [MPSDevice::getInstance()->device() maxBufferLength]; +} + +void MPSHooks::setMemoryFraction(double ratio) const { + at::mps::getIMPSAllocator()->setHighWatermarkRatio(ratio); +} + +void MPSHooks::profilerStartTrace(const std::string& mode, bool waitUntilCompleted) const { + at::mps::getMPSProfiler().StartTrace(mode, waitUntilCompleted); +} + +void MPSHooks::profilerStopTrace() const { + at::mps::getMPSProfiler().StopTrace(); +} + +uint32_t MPSHooks::acquireEvent(bool enable_timing) const { + return at::mps::getMPSEventPool()->acquireEvent(enable_timing); +} + +void MPSHooks::releaseEvent(uint32_t event_id) const { + at::mps::getMPSEventPool()->releaseEvent(event_id); +} + +void MPSHooks::recordEvent(uint32_t event_id) const { + at::mps::getMPSEventPool()->recordEvent(event_id, /* syncEvent*/ true); +} + +Device MPSHooks::getDeviceFromPtr(void* data) const { + return at::mps::getDeviceFromPtr(data); +} + +void MPSHooks::waitForEvent(uint32_t event_id) const { + at::mps::getMPSEventPool()->waitForEvent(event_id, /* syncEvent*/ true); +} + +void MPSHooks::synchronizeEvent(uint32_t event_id) const { + at::mps::getMPSEventPool()->synchronizeEvent(event_id); +} + +bool MPSHooks::queryEvent(uint32_t event_id) const { + return at::mps::getMPSEventPool()->queryEvent(event_id); +} + +double MPSHooks::elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id) const { + return at::mps::getMPSEventPool()->elapsedTime(start_event_id, end_event_id); +} + +bool MPSHooks::isPinnedPtr(const void* data) const { + return at::mps::isMPSPinnedPtr(data); +} + +Allocator* MPSHooks::getPinnedMemoryAllocator() const { + return at::mps::getIMPSAllocator(); +} + +using at::MPSHooksRegistry; +using at::RegistererMPSHooksRegistry; + +REGISTER_MPS_HOOKS(MPSHooks); + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSProfiler.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSProfiler.h new file mode 100644 index 0000000000000000000000000000000000000000..3f6888f0910fd8f04e28436eb820260df5e3adb0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSProfiler.h @@ -0,0 +1,467 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#ifndef __OBJC__ +typedef void* MTLCaptureManager; +#endif + +namespace at::mps { + +namespace Profiler { + +struct BaseInfo { + // profiling info types + enum class Type { + GRAPH, + KERNEL, + COPY, + CPU_FALLBACK, + }; + + BaseInfo(Type infoType, uint64_t Id, const uintptr_t Handle) + : type(infoType), profileId(Id), handle(Handle) {} + virtual ~BaseInfo() = default; + + // type of profiling info + Type type; + // unique profile ID for execution instances of operations or copies + uint64_t profileId; + // ID generated by os_signpost + // since it's possible to use event and interval-based signposts at the + // same time, we need separate IDs for each. + os_signpost_id_t eventSignpostId = 0, intervalSignpostId = 0; + // accumulated GPU time in ms (obtained from CompletionHandler's "GPUEndTime - + // GPUStartTime") + std::atomic totalGpuTime{0.0}; + // accumulated Scheduling time in ms (obtained from CompletionHandler's + // "KernelEndTime - KernelStartTime") + std::atomic totalSchedulingTime{0.0}; + // indicates if the operation or copy execution has completed + std::atomic_bool completed{false}; + // handle used to identify the profile info's instance (usually the pointer) + const uintptr_t handle; + + virtual const std::string toString( + double gpuTime = 0, + double schedulingTime = 0) const; + // builds a string for a tensor (format: Device:ScalarType[tensor.sizes()]) + static std::string buildTensorString( + const Tensor& tensor, + bool includeBufferId = false); + static uint64_t getTime() { + return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW); + } +}; + +struct OperationInfo : BaseInfo { + OperationInfo( + const void* Handle, + bool IsGraph, + uint64_t Id, + const std::string& StrKey) + : BaseInfo(IsGraph ? Type::GRAPH : Type::KERNEL, Id, uintptr_t(Handle)), + strKey(StrKey) {} + + uint64_t runCount = 0; + std::string strKey; + + const std::string toString(double gpuTime = 0, double schedulingTime = 0) + const override; + + // builds a string for a kernel + static std::string buildKernelString( + const std::string& kernelName, + const TensorList& tensors, + bool includeBufferId = false) { + std::stringstream kernelStr; + kernelStr << kernelName; + for (const Tensor& tensor : tensors) { + kernelStr << ':' << BaseInfo::buildTensorString(tensor, includeBufferId); + } + return std::move(kernelStr).str(); + } +}; + +struct CpuFbInfo : BaseInfo { + CpuFbInfo(uint64_t Id, const std::string& OpName) + : BaseInfo(Type::CPU_FALLBACK, Id, 0), opName(OpName) {} + + uint64_t runCount = 0; + // the current and total overhead of copies in bytes required to convert the + // Op's input tensors from MPS to CPU and then output from CPU back to MPS + size_t currentCopyOverhead = 0; + size_t totalCopyOverhead = 0; + std::string opName; + std::string strKey; + uint64_t startTime = 0; + + const std::string toString(double gpuTime = 0, double schedulingTime = 0) + const override; + + void updateCopyOverhead(const TensorList& tensors) { + currentCopyOverhead = 0; + for (const Tensor& tensor : tensors) { + if (tensor.defined()) { + currentCopyOverhead += tensor.nbytes(); + } + } + totalCopyOverhead += currentCopyOverhead; + } +}; + +struct CopyInfo : BaseInfo { + enum class Kind { + MPS_TO_MPS, + MPS_TO_CPU, + CPU_TO_MPS, + }; + + CopyInfo( + const void* Handle, + size_t Length, + uint64_t Id, + bool IsNonBlocking, + bool UsesBlitter) + : BaseInfo(Type::COPY, Id, uintptr_t(Handle)), + kind(Kind::MPS_TO_MPS), + length(Length), + isNonBlocking(IsNonBlocking), + usesBlitter(UsesBlitter) {} + + Kind kind; + size_t length; + bool isNonBlocking; + bool usesBlitter; + std::string srcStrKey; + std::string dstStrKey; + // for copies that don't use blitters, we measure CPU time + uint64_t startTime = 0; + + const std::string toString(double gpuTime = 0, double schedulingTime = 0) + const override; + + static std::string buildTensorString( + const void* buffer, + const OptionalTensorRef tensor, + bool includeBufferId = false); + + static bool isStorageOnMPS( + const void* buffer, + const OptionalTensorRef tensor) { + if (tensor.has_value()) { + return tensor->device().type() == at::kMPS; + } + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer); + // getUnalignedBufferSize() returns -1 if input buffer is not on MPS device + return getIMPSAllocator()->getUnalignedBufferSize(buffer) >= 0; + } + + static Kind getCopyKind( + const void* srcBuffer, + const void* dstBuffer, + const OptionalTensorRef srcTensor, + const OptionalTensorRef dstTensor) { + const bool isSrcOnMPS = isStorageOnMPS(srcBuffer, srcTensor); + const bool isDstOnMPS = isStorageOnMPS(dstBuffer, dstTensor); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isSrcOnMPS || isDstOnMPS); + if (isSrcOnMPS && !isDstOnMPS) { + return Kind::MPS_TO_CPU; + } else if (!isSrcOnMPS && isDstOnMPS) { + return Kind::CPU_TO_MPS; + } + return Kind::MPS_TO_MPS; + } +}; + +struct CopyStat : CopyInfo { + explicit CopyStat(std::string CopyKindStr) + : CopyInfo(nullptr, 0, 0, false, false), + kindStr(std::move(CopyKindStr)) {} + // total number of copies + size_t totalCount = 0; + // number of Scalar copies (i.e., less than sizeof(int64)) + size_t scalarsCount = 0; + // number of blocking copies (i.e., require syncing to GPU) + size_t blockingCount = 0; + // number of copies that used memcpy(), instead of Metal Blit Encoder + size_t memcpyCount = 0; + // accumulated GPU time in ms for the scalar copies + std::atomic scalarsGpuTime{0.0}; + // copy kind in string type + std::string kindStr; +}; + +class MPSProfiler { + public: + // lower 16 bits used for profiler options + enum ProfileOptions : uint32_t { + OPTIONS_NONE = 0, + // ALL_* means, all signpost types (RUN_OPERATION|BLIT_COPY|CPU_FALLBACK, + // etc.) (used for convenience to not compute bit flags by OR-ing manually) + // trace all signpost types using events + ALL_SIGNPOST_EVENTS = (1 << 0), + // trace all signpost types using intervals + ALL_SIGNPOST_INTERVALS = (1 << 1), + // always wait for command buffer to finish executing after each commit + WAIT_UNTIL_COMPLETED = (1 << 2), + // for interval-based signposts, include the scheduling portion of + // Graph/Kernel/Copy executions as well. + // if flag is disable, only "GPU run time" is included in interval, + // and not schedule time. + INCLUDE_SCHEDULE_INTERVAL = (1 << 3), + + // use these if you need to trace signposts types individually (rarely + // required) trace signpost using intervals + USE_INTERVALS = (1 << 4), + // trace signpost by emitting events + USE_EVENTS = (1 << 5), + // used for sanity check (Change this when new option added) + OPTIONS_COUNT = (USE_EVENTS << 1) - 1, + }; + + // when adding new types, #define the type string in MPSProfiler.mm as well. + // upper 16 bits used for event types + enum SignpostTypes : uint32_t { + SIGNPOST_NONE = 0, + // trace signposts for PyTorch operation executions + RUN_OPERATION = (1 << 16), + // trace signposts for blitter copies + BLIT_COPY = (1 << 17), + // trace signposts for ops that fall back on CPU + CPU_FALLBACK = (1 << 18), + // used for sanity check (Change this when new type added) + SIGNPOST_COUNT = (CPU_FALLBACK << 1) - 1, + }; + + enum LogOptions : uint32_t { + LOG_NONE = 0, + + // Info logging options during execution + // ------------------------------------- + // prints operation info (id/key/run_count) during execution + OPERATION_INFO = (1 << 0), + // prints copy info (src/dst tensors/buffers, size, etc.) during execution + COPY_INFO = (1 << 1), + // prints CPU Fallback info (id/runCount/opName/copyOverhead) during + // execution + CPU_FALLBACK_INFO = (1 << 2), + + // Profiling Statistics logging options when process terminates + // ------------------------------------------------------------ + // prints all stats (OPERATION_STATS, COPY_STATS, CPU_FALLBACK_STATS) before + // process terminates this is convenient to not combine following stats bit + // flags manually + ALL_STATS = (1 << 3), + // prints operation stats (GPU times, run count, etc.) before process + // terminates + OPERATION_STATS = (1 << 4), + // prints copies stats (GPU times, copy kinds, sizes, etc.) before process + // terminates + COPY_STATS = (1 << 5), + // prints CPU Fallback stats (CPU times, run times, size of MPS<->CPU copies + // for tensors, etc.) before process terminates + CPU_FALLBACK_STATS = (1 << 6), + + // Metadata format options when logging the info + // --------------------------------------------- + // if enabled, includes GPU run time in metadata (i.e., + // GPUEndTime-GPUStartTime from Metal Command Buffers) (e.g., [GPU=0.324 + // ms]) + INCLUDE_GPU_TIME = (1 << 7), + // if enabled, includes GPU scheduling time in metadata separately + // (i.e., KernelEndTime-KernelStartTime from Metal Command Buffers) + // e.g., [GPU=0.324 ms, KRNL=0.036 ms] + INCLUDE_KERNEL_TIME = (1 << 8), + // if enabled, includes the unique buffer ID in metadata for the storage + // of a tensor that was allocated on MPSAllocator. This is useful (along + // with the EV "PYTORCH_DEBUG_MPS_ALLOCATOR") to identify buffers that are + // involved with various operations. + INCLUDE_BUFFER_ID = (1 << 9), + + // used for sanity check (Change this when new option added) + LOG_COUNT = (INCLUDE_BUFFER_ID << 1) - 1, + }; + + explicit MPSProfiler(); + ~MPSProfiler(); + + // the handle is either "MPSGraph*" or "id" for Metal + // Kernels the beginProfile*() functions return a profileId which is unique + // per graph/kernel/copy + uint64_t beginProfileKernel( + const void* handle, + const std::string& strKey, + bool isGraph); + uint64_t beginProfileKernel( + const void* handle, + const std::string& kernelName, + const TensorList& tensors); + uint64_t beginProfileCopy( + const void* srcBuffer, + const void* dstBuffer, + const OptionalTensorRef srcTensor, + const OptionalTensorRef dstTensor, + size_t length, + bool isNonBlocking, + bool usesBlitter = true); + uint64_t beginProfileCPUFallback( + const std::string& opName, + const TensorList& tensors); + void beginProfileGPUInterval(const void* handle); + + void endProfileCopy(uint64_t profileId, SyncType syncType); + void endProfileKernel(const void* handle, SyncType syncType = SyncType::NONE); + void endProfileCPUFallback(const std::string& opName); + + // these are used to hook into Python bindings for torch.mps.profiler module. + // this enables generating OS Signpost traces from MPSProfiler on-demand + // during runtime (instead of environment variables). + // The "mode" could be either "interval", "event", or both "interval,event" + // for interval-based and/or event-based signpost tracing. + void StartTrace(const std::string& mode, bool waitUntilCompleted); + void StopTrace(); + + // Abstractions for GPU trace capturing + bool isCaptureEnabled() const; + bool isCapturing() const; + void startCapture(const std::string& name, MPSStream* stream = nullptr); + void stopCapture(MPSStream* stream = nullptr); + + // convenience functions to indicate whether signpost tracing or + // logging are enabled for the SignpostTypes + bool isOperationProfilingEnabled() const { + return (m_signpost_types & SignpostTypes::RUN_OPERATION) || + (m_log_options & + (LogOptions::OPERATION_INFO | LogOptions::OPERATION_STATS)); + } + bool isCopyProfilingEnabled() const { + return (m_signpost_types & SignpostTypes::BLIT_COPY) || + (m_log_options & (LogOptions::COPY_INFO | LogOptions::COPY_STATS)); + } + bool isCPUFallbackProfilingEnabled() const { + return (m_signpost_types & SignpostTypes::CPU_FALLBACK) || + (m_log_options & + (LogOptions::CPU_FALLBACK_INFO | LogOptions::CPU_FALLBACK_STATS)); + } + bool isSignpostTracingEnabled() const { + return (m_signpost_types != SignpostTypes::SIGNPOST_NONE); + } + + private: + // indicates what type of signpost types are enabled and traced by MPS + // profiler. + uint32_t m_signpost_types = 0; + uint32_t m_profile_options = 0; + uint32_t m_log_options = 0; + uint64_t m_kernel_counter = 0; + uint64_t m_graph_counter = 0; + uint64_t m_cpu_fb_counter = 0; + uint64_t m_copy_counter = 0; + // technically, it's possible to trace both events and intervals at the same + // time so we use separate os_log categories for them + os_log_t m_os_log_events; + os_log_t m_os_log_intervals; + // stats logging could run either from destructor or signal handler + // so this is used to check if logging has already started. + std::atomic_bool hasLoggedStats{false}; + // indicates there are pending completionHandler callbacks that haven't been + // called yet. + std::atomic_bool hasPendingCompletionHandlers{false}; + // used to capture sigint signal to log profiling stats + static struct sigaction currentSigint, previousSigint; + + // We use the following lists for two reasons: + // 1- for interval-based signposts the "begin" point won't be in same function + // as the "end" point where we need to be able to retrieve signpost's info + // 2- if Operations info need to be logged when process ends using + // LogOptions::OPERATION_INFO. + + // the pointer key for this map is either "MPSGraph*" or + // "id" for Metal Kernels this list is retained and + // could be logged along with aggregate profiling numbers when the process + // ends. + std::unordered_map> + m_op_info_list{}; + // the string key for this map is the op name that we fall back to execute on + // CPU this list is retained and could be logged along with aggregate + // profiling numbers when the process ends. + std::unordered_map> + m_cpu_fb_info_list{}; + // this list contains the info for copies, and its key is the unique profileId + // which is generated from m_copy_counter + // The copyInfo list is not retained. + std::unordered_map> m_copy_info_list{}; + // a short list that contains copy stats + std::unordered_map> + m_copy_stat_list{}; + + mutable MTLCaptureManager* captureManager = nil; + unsigned captureCount = 0; + + void initialize(); + void beginProfileExecution(BaseInfo& info, bool cpuExecution = false); + void endProfileExecution( + BaseInfo& info, + os_signpost_id_t event_signpost_id, + os_signpost_id_t interval_signpost_id, + double gpuTime, + double schedulingTime); + void addProfilerScheduledHandler(BaseInfo& info); + void addProfilerCompletedHandler(BaseInfo& info, SyncType syncType); + void emitSignpostEvent( + SignpostTypes signpost_type, + os_signpost_id_t signpost_id, + const std::string& msg) const; + void beginSignpostInterval( + SignpostTypes signpost_type, + os_signpost_id_t signpost_id, + const std::string& msg) const; + void endSignpostInterval( + SignpostTypes signpost_type, + os_signpost_id_t signpost_id) const; + + void updateCopyStats( + const CopyInfo& copyInfo, + double gpuTime, + double schedulingTime); + // returns true if logging the profiling info "during the execution" is + // enabled + bool isProfileInfoLoggingEnabled( + BaseInfo::Type infoType, + bool isExecutionEnded); + // logs all the profiling stats that are enabled + void logProfilingStats(); + // logs kernel profiling stats when the process ends. + void logOperationsProfilingStats(std::FILE* f) const; + // logs CPU Fallback profiling stats when the process ends. + void logCPUFallbackProfilingStats(std::FILE* f) const; + // logs copy profiling stats when the process ends. + void logCopyProfilingStats(std::FILE* f) const; + + os_signpost_id_t generateSignpostId( + os_signpost_type_t signpostType, + const void* ptr = nullptr); + static SignpostTypes getSignpostType(BaseInfo::Type infoType); + static void handleIntSignal(int signal); +}; + +} // namespace Profiler + +Profiler::MPSProfiler& getMPSProfiler(); + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSProfiler.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSProfiler.mm new file mode 100644 index 0000000000000000000000000000000000000000..2f95159bb1ad5f80935ee80a80510cbfc95125ac --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSProfiler.mm @@ -0,0 +1,831 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include +#include + +// these need to be literal strings when passed to os_signpost*() +// function macros; so no LUTs could be used +#define kMPSProfilerSubSystemStr "PyTorchMPS" +#define kMPSCategoryEventsStr "Events" +#define kMPSCategoryIntervalsStr "Intervals" +#define kIntSignpostRunOperationStr "PyTorchOperationIntervals" +#define kIntSignpostBlitCopyStr "PyTorchCopyIntervals" +#define kIntSignpostCPUFallbacksStr "PyTorchCPUFallbackIntervals" +#define kEvtSignpostRunOperationStr "PyTorchOperationEvents" +#define kEvtSignpostBlitCopyStr "PyTorchCopyEvents" +#define kEvtSignpostCPUFallbacksStr "PyTorchCPUFallbacksEvents" +#define kEVLogProfileInfoStr "PYTORCH_MPS_LOG_PROFILE_INFO" +#define kEVTraceSignpostsStr "PYTORCH_MPS_TRACE_SIGNPOSTS" + +namespace at::mps { +namespace Profiler { + +const std::string BaseInfo::toString(double gpuTime, double schedulingTime) const { + // the gpuTime will be non-zero mainly for event-based signposts. + // The interval-based signposts will have "duration" as well as accumulated + // total GPU time, up to the point of execution. + return fmt::format("{}{}", + gpuTime > 0.0 ? fmt::format(", gpu={:.3f} ms", gpuTime) : "", + schedulingTime > 0.0 ? fmt::format(", cpu={:.3f} ms", schedulingTime) : ""); +} + +std::string BaseInfo::buildTensorString(const Tensor& tensor, bool includeBufferId) { + if (tensor.defined()) { + std::stringstream tensorStr; + auto deviceType = tensor.device().type(); + tensorStr << c10::DeviceTypeName(deviceType); + // see comments for INCLUDE_BUFFER_ID + if (includeBufferId && deviceType == at::kMPS) { + id buffer = __builtin_bit_cast(id, tensor.storage().data()); + tensorStr << "(buf#" << (getIMPSAllocator()->getBufferId(buffer)) << ':' << buffer.retainCount << ')'; + } + tensorStr << ':' << tensor.scalar_type() << tensor.sizes(); + return std::move(tensorStr).str(); + } else { + return "undefined"; + } +} + +const std::string OperationInfo::toString(double gpuTime, double schedulingTime) const { + return fmt::format("aten::{} (id={}{}, run={}{})", + strKey, + type == Type::GRAPH ? "G" : "K", + profileId, + runCount, + BaseInfo::toString(gpuTime, schedulingTime)); +} + +const std::string CpuFbInfo::toString(double gpuTime, double schedulingTime) const { + return fmt::format("CPU Fallback::{} (id={}, run={}, CopyOverhead={}{})", + strKey, + profileId, + runCount, + getIMPSAllocator()->formatSize(currentCopyOverhead), + BaseInfo::toString(0.0, schedulingTime)); +} + +const std::string CopyInfo::toString(double gpuTime, double schedulingTime) const { + return fmt::format("{}Copy{}: {} --> {} (len={}{})", + // Copies could be using Blit Encoder, or using regular + // memcpy() on Unified memory + usesBlitter ? "Blit" : "Mem", + // CopySync indicates COMMIT_AND_WAIT was used to synchronize + // the GPU stream with CPU after the blocking copy + isNonBlocking ? "" : "Sync", + srcStrKey, + dstStrKey, + getIMPSAllocator()->formatSize(length), + BaseInfo::toString(gpuTime, schedulingTime)); +} + +std::string CopyInfo::buildTensorString(const void* buffer, const OptionalTensorRef tensor, bool includeBufferId) { + if (tensor.has_value()) { + return BaseInfo::buildTensorString(*tensor, includeBufferId); + } + // if tensor is not defined (e.g., copy_blit_mps()), then use buffer + // pointer to build the string. + const bool isBufferOnMPS = isStorageOnMPS(buffer, tensor); + return fmt::format("{}:{:p}", isBufferOnMPS ? "MPS" : "CPU", buffer); +} + +MPSProfiler::MPSProfiler() : m_os_log_events(nullptr), m_os_log_intervals(nullptr) { + // see enum LogOptions for the description. + static const auto log_options_str = c10::utils::get_env(kEVLogProfileInfoStr); + m_log_options = log_options_str ? strtol(log_options_str->c_str(), nullptr, 0) : 0; + // see enums profilerOptions and SignpostTypes for the description. + static const auto trace_signpost_str = c10::utils::get_env(kEVTraceSignpostsStr); + uint32_t trace_signposts = trace_signpost_str ? strtol(trace_signpost_str->c_str(), nullptr, 0) : 0; + + TORCH_CHECK(m_log_options <= LogOptions::LOG_COUNT, + "invalid log options ", + m_log_options, + " passed to ", + kEVLogProfileInfoStr) + // lower 16 bits used for options (see enum ProfileOptions) + m_profile_options |= trace_signposts & 0xFFFF; + TORCH_CHECK(m_profile_options <= ProfileOptions::OPTIONS_COUNT, + "invalid profiling options ", + trace_signposts, + " passed to ", + kEVTraceSignpostsStr) + // upper 16 bits used for signpost types (see enum SignpostTypes) + m_signpost_types |= trace_signposts & 0xFFFF0000; + TORCH_CHECK(m_signpost_types <= SignpostTypes::SIGNPOST_COUNT, + "invalid signpost types ", + trace_signposts, + " passed to ", + kEVTraceSignpostsStr) + currentSigint.sa_handler = nullptr; + previousSigint.sa_handler = nullptr; + + initialize(); +} + +MPSProfiler::~MPSProfiler() { + // first make sure completion handlers are completed + auto stream = getDefaultMPSStream(); + dispatch_sync(stream->queue(), ^() { + if (hasPendingCompletionHandlers) { + stream->synchronize(SyncType::COMMIT_AND_WAIT); + } + }); + logProfilingStats(); + + if (m_os_log_events) { + os_release(m_os_log_events); + } + if (m_os_log_intervals) { + os_release(m_os_log_intervals); + } +} + +void MPSProfiler::initialize() { + if ((m_signpost_types == SignpostTypes::SIGNPOST_NONE) && + (m_profile_options & ProfileOptions::INCLUDE_SCHEDULE_INTERVAL)) { + m_profile_options |= ProfileOptions::ALL_SIGNPOST_INTERVALS; + } + + if (m_profile_options & (ProfileOptions::ALL_SIGNPOST_EVENTS | ProfileOptions::ALL_SIGNPOST_INTERVALS)) { + // enable all signposts types + m_signpost_types |= (SignpostTypes::RUN_OPERATION | SignpostTypes::CPU_FALLBACK | SignpostTypes::BLIT_COPY); + + if (m_profile_options & ProfileOptions::ALL_SIGNPOST_EVENTS) { + m_profile_options |= ProfileOptions::USE_EVENTS; + } + if (m_profile_options & ProfileOptions::ALL_SIGNPOST_INTERVALS) { + m_profile_options |= ProfileOptions::USE_INTERVALS; + } + } + + if (m_log_options & LogOptions::ALL_STATS) { + m_log_options |= LogOptions::OPERATION_STATS | LogOptions::COPY_STATS | LogOptions::CPU_FALLBACK_STATS; + } + + if (m_signpost_types != SignpostTypes::SIGNPOST_NONE) { + // if no signpost options passed, use interval mode by default + if (!(m_profile_options & (ProfileOptions::USE_EVENTS | ProfileOptions::USE_INTERVALS))) { + m_profile_options |= ProfileOptions::USE_INTERVALS; + } + if ((m_profile_options & ProfileOptions::INCLUDE_SCHEDULE_INTERVAL) && + (m_profile_options & ProfileOptions::USE_EVENTS)) { + TORCH_CHECK((m_profile_options & ProfileOptions::USE_INTERVALS), + "the option 'INCLUDE_SCHEDULE_INTERVAL' only works for interval-based signposts"); + } + + // technically, it's possible to trace both events and intervals at the same time + if (m_profile_options & ProfileOptions::USE_EVENTS) { + if (!m_os_log_events) { + m_os_log_events = os_log_create(kMPSProfilerSubSystemStr, kMPSCategoryEventsStr); + TORCH_CHECK(m_os_log_events, "failed to create OS signpost log for events profiler"); + } + // include GPU time in metadata for event-based intervals by default, since + // events are marked in Metal Completion Handlers which outputs GPU time + m_log_options |= INCLUDE_GPU_TIME; + } + if (m_profile_options & ProfileOptions::USE_INTERVALS) { + if (!m_os_log_intervals) { + m_os_log_intervals = os_log_create(kMPSProfilerSubSystemStr, kMPSCategoryIntervalsStr); + TORCH_CHECK(m_os_log_intervals, "failed to create OS signpost log for intervals profiler"); + } + } + } + + if (m_log_options & LogOptions::COPY_STATS) { + if (m_copy_stat_list.empty()) { + m_copy_stat_list.emplace(CopyInfo::Kind::MPS_TO_MPS, std::make_unique("MPS to MPS")); + m_copy_stat_list.emplace(CopyInfo::Kind::MPS_TO_CPU, std::make_unique("MPS to CPU")); + m_copy_stat_list.emplace(CopyInfo::Kind::CPU_TO_MPS, std::make_unique("CPU to MPS")); + } + } + + // used to capture sigint signal to log profiling stats + if (m_log_options & (LogOptions::OPERATION_STATS | LogOptions::COPY_STATS | LogOptions::CPU_FALLBACK_STATS)) { + if (!currentSigint.sa_handler) { + currentSigint.sa_handler = &handleIntSignal; + currentSigint.sa_flags = SA_RESTART; + sigfillset(¤tSigint.sa_mask); + if (sigaction(SIGINT, ¤tSigint, &previousSigint) == -1) { + TORCH_CHECK(false, "Cannot install SIGINT handler for MPSProfiler."); + } + } + } +} + +void MPSProfiler::StartTrace(const std::string& mode, bool waitUntilCompleted) { + TORCH_CHECK(m_profile_options == ProfileOptions::OPTIONS_NONE, "Tracing Signposts is already enabled "); + + std::stringstream ss(mode); + std::string token; + while (getline(ss, token, ',')) { + if (!token.empty()) { + if (token == "interval") { + m_profile_options |= ProfileOptions::ALL_SIGNPOST_INTERVALS; + } else if (token == "event") { + m_profile_options |= ProfileOptions::ALL_SIGNPOST_EVENTS; + } else { + TORCH_CHECK(false, "Invalid Signpost trace mode: ", token); + } + } + } + if (m_profile_options != ProfileOptions::OPTIONS_NONE) { + if (waitUntilCompleted) { + m_profile_options |= ProfileOptions::WAIT_UNTIL_COMPLETED; + } + initialize(); + } +} + +void MPSProfiler::StopTrace() { + m_profile_options = ProfileOptions::OPTIONS_NONE; + m_signpost_types = SignpostTypes::SIGNPOST_NONE; +} + +void MPSProfiler::beginProfileExecution(BaseInfo& info, bool cpuExecution) { + // see comments in isProfileInfoLoggingEnabled() + if (isProfileInfoLoggingEnabled(info.type, /*isExecutionEnded*/ false)) { + fmt::print(stderr, "{}\n", info.toString()); + } + SignpostTypes signpostType = getSignpostType(info.type); + if (!(m_signpost_types & signpostType)) { + return; + } + if (m_profile_options & ProfileOptions::USE_EVENTS) { + info.eventSignpostId = generateSignpostId(OS_SIGNPOST_EVENT); + } + if (m_profile_options & ProfileOptions::USE_INTERVALS) { + info.intervalSignpostId = generateSignpostId(OS_SIGNPOST_INTERVAL_BEGIN); + // if scheduling part is included, we begin the interval early in here, + // otherwise we begin when the scheduledHandler callback is triggered. + if ((m_profile_options & ProfileOptions::INCLUDE_SCHEDULE_INTERVAL) || cpuExecution) { + beginSignpostInterval(signpostType, info.intervalSignpostId, info.toString()); + info.completed = false; + // for graphs, we add the scheduleHandler in beginProfileGPUInterval() + } else if (info.type == BaseInfo::Type::KERNEL || info.type == BaseInfo::Type::COPY) { + addProfilerScheduledHandler(info); + } + } +} + +void MPSProfiler::endProfileExecution(BaseInfo& info, + os_signpost_id_t event_signpost_id, + os_signpost_id_t interval_signpost_id, + double gpuTime, + double schedulingTime) { + const SignpostTypes signpostType = getSignpostType(info.type); + + if (info.type == BaseInfo::Type::COPY) { + updateCopyStats(static_cast(info), gpuTime, schedulingTime); + } else { + info.totalGpuTime = info.totalGpuTime + gpuTime; + info.totalSchedulingTime = info.totalSchedulingTime + schedulingTime; + } + // if Kernel time is not included in metadata separately, we add it to gpuTime in metadata + if (gpuTime > 0.0 && !(m_log_options & LogOptions::INCLUDE_KERNEL_TIME)) { + gpuTime += schedulingTime; + schedulingTime = 0; + } + const std::string& infoStr = info.toString(gpuTime, schedulingTime); + // see comments in isProfileInfoLoggingEnabled() + if (isProfileInfoLoggingEnabled(info.type, /*isExecutionEnded*/ true)) { + fmt::print(stderr, "{}\n", infoStr); + } + // it is possible to use both interval and event based signposts at the same time + if ((m_profile_options & ProfileOptions::USE_EVENTS) && event_signpost_id) { + emitSignpostEvent(signpostType, event_signpost_id, infoStr); + } + // GPU time for signpost intervals is calculated based on its duration + if ((m_profile_options & ProfileOptions::USE_INTERVALS) && interval_signpost_id) { + endSignpostInterval(signpostType, interval_signpost_id); + } + info.completed = true; +} + +uint64_t MPSProfiler::beginProfileKernel(const void* handle, const std::string& strKey, bool isGraph) { + // only do profiling if operation execution profiling or logging are enabled + if (!isOperationProfilingEnabled()) { + return 0; + } + if (m_op_info_list.count(uintptr_t(handle)) == 0) { + auto opInfo = + std::make_unique(handle, isGraph, isGraph ? ++m_graph_counter : ++m_kernel_counter, strKey); + m_op_info_list.emplace(opInfo->handle, std::move(opInfo)); + } + auto& opInfo = *m_op_info_list[uintptr_t(handle)]; + opInfo.strKey.assign(strKey); + opInfo.runCount++; + beginProfileExecution(opInfo); + + return opInfo.profileId; +} + +uint64_t MPSProfiler::beginProfileKernel(const void* handle, const std::string& kernelName, const TensorList& tensors) { + if (isOperationProfilingEnabled()) { + const bool includeBufferId = m_log_options & LogOptions::INCLUDE_BUFFER_ID; + std::string profilerStrKey = OperationInfo::buildKernelString(kernelName, tensors, includeBufferId); + return beginProfileKernel(handle, profilerStrKey, false); + } + return 0; +} + +void MPSProfiler::beginProfileGPUInterval(const void* handle) { + // this function is only relevant for interval-based Signposts which exclude + // schedule time (only includes GPU run time) + if (!(m_profile_options & ProfileOptions::USE_INTERVALS) || + (m_profile_options & ProfileOptions::INCLUDE_SCHEDULE_INTERVAL)) { + return; + } + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(m_op_info_list.count(uintptr_t(handle)), "Failed to get operation information!"); + auto& opInfo = *m_op_info_list[uintptr_t(handle)]; + // this begins the interval when scheduling the execution is + // completed already (i.e., scheduling excluded from interval) + addProfilerScheduledHandler(opInfo); +} + +void MPSProfiler::endProfileKernel(const void* handle, SyncType syncType) { + // only do profiling if operation execution profiling or logging are enabled + if (!isOperationProfilingEnabled()) { + return; + } + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(m_op_info_list.count(uintptr_t(handle)), "Failed to get operation information!"); + auto& opInfo = *m_op_info_list[uintptr_t(handle)]; + addProfilerCompletedHandler(opInfo, syncType); +} + +uint64_t MPSProfiler::beginProfileCPUFallback(const std::string& opName, const TensorList& tensors) { + if (m_cpu_fb_info_list.count(opName) == 0) { + auto cpuFbInfo = std::make_unique(++m_cpu_fb_counter, opName); + m_cpu_fb_info_list.emplace(opName, std::move(cpuFbInfo)); + } + auto& cpuFbInfo = *m_cpu_fb_info_list[opName]; + cpuFbInfo.runCount++; + cpuFbInfo.startTime = BaseInfo::getTime(); + const bool includeBufferId = m_log_options & LogOptions::INCLUDE_BUFFER_ID; + cpuFbInfo.strKey = OperationInfo::buildKernelString(opName, tensors, includeBufferId); + cpuFbInfo.updateCopyOverhead(tensors); + beginProfileExecution(cpuFbInfo, true); + + return cpuFbInfo.profileId; +} + +void MPSProfiler::endProfileCPUFallback(const std::string& opName) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(m_cpu_fb_info_list.count(opName), "Failed to get CPU Fallback information!"); + auto& cpuFbInfo = *m_cpu_fb_info_list[opName]; + // CPU time in ms + double cpuTime = double(BaseInfo::getTime() - cpuFbInfo.startTime) * 1e-6; + endProfileExecution(cpuFbInfo, cpuFbInfo.eventSignpostId, cpuFbInfo.intervalSignpostId, 0, cpuTime); +} + +uint64_t MPSProfiler::beginProfileCopy(const void* srcBuffer, + const void* dstBuffer, + const OptionalTensorRef srcTensor, + const OptionalTensorRef dstTensor, + size_t length, + bool isNonBlocking, + bool usesBlitter) { + if (!isCopyProfilingEnabled()) { + return 0; + } + const bool includeBufferId = m_log_options & LogOptions::INCLUDE_BUFFER_ID; + const uint64_t profileId = ++m_copy_counter; + auto copyInfo = std::make_unique(dstBuffer, length, profileId, isNonBlocking, usesBlitter); + copyInfo->srcStrKey = CopyInfo::buildTensorString(srcBuffer, srcTensor, includeBufferId); + copyInfo->dstStrKey = CopyInfo::buildTensorString(dstBuffer, dstTensor, includeBufferId); + copyInfo->kind = CopyInfo::getCopyKind(srcBuffer, dstBuffer, srcTensor, dstTensor); + if (!usesBlitter) { + // for copies that don't use blitters, we measure CPU time + copyInfo->startTime = BaseInfo::getTime(); + } + // don't generate signposts if the non-blocking copy is not using the blitter + if (usesBlitter || !isNonBlocking) { + beginProfileExecution(*copyInfo, !usesBlitter); + } + // this should not happen since we erase the copy info after profiling/logging it. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(m_copy_info_list.count(profileId) == 0); + // the copy info isn't retained in the list, so we erase the completed ones + for (auto it = m_copy_info_list.begin(), last = m_copy_info_list.end(); it != last;) { + if (it->second->completed) { + it = m_copy_info_list.erase(it); + } else { + ++it; + } + } + m_copy_info_list.emplace(profileId, std::move(copyInfo)); + + return profileId; +} + +void MPSProfiler::endProfileCopy(uint64_t profileId, SyncType syncType) { + // this is just an identifier, and not used to access memory + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(m_copy_info_list.count(profileId), "Failed to get copy information!"); + auto& copyInfo = *m_copy_info_list[profileId]; + if (copyInfo.usesBlitter) { + addProfilerCompletedHandler(copyInfo, syncType); + } else { + double cpuTime = double(BaseInfo::getTime() - copyInfo.startTime) * 1e-6; + endProfileExecution(copyInfo, copyInfo.eventSignpostId, copyInfo.intervalSignpostId, 0, cpuTime); + } +} + +void MPSProfiler::addProfilerScheduledHandler(BaseInfo& info) { + const SignpostTypes signpostType = getSignpostType(info.type); + const os_signpost_id_t intervalSignpostId = info.intervalSignpostId; + + auto m_stream = getDefaultMPSStream(); + // NOTE: the following block isn't thread-safe + [m_stream->commandBuffer() addScheduledHandler:^(id cb) { + // begin the interval once scheduling has completed (if INCLUDE_SCHEDULE_INTERVAL flag is disabled) + beginSignpostInterval(signpostType, intervalSignpostId, info.toString()); + info.completed = false; + }]; +} + +void MPSProfiler::updateCopyStats(const CopyInfo& copyInfo, double gpuTime, double schedulingTime) { + if (!(m_log_options & LogOptions::COPY_STATS)) { + return; + } + auto& copyStat = *m_copy_stat_list[copyInfo.kind]; + copyStat.totalCount++; + copyStat.length += copyInfo.length; + copyStat.totalGpuTime = copyStat.totalGpuTime + gpuTime; + copyStat.totalSchedulingTime = copyStat.totalSchedulingTime + schedulingTime; + if (copyInfo.length <= sizeof(int64_t)) { + copyStat.scalarsCount++; + copyStat.scalarsGpuTime = copyStat.scalarsGpuTime + gpuTime; + } + copyStat.blockingCount += !copyInfo.isNonBlocking ? 1 : 0; + copyStat.memcpyCount += !copyInfo.usesBlitter ? 1 : 0; +} + +void MPSProfiler::addProfilerCompletedHandler(BaseInfo& info, SyncType syncType) { + const os_signpost_id_t intervalSignpostId = info.intervalSignpostId; + const os_signpost_id_t eventSignpostId = info.eventSignpostId; + + // signpost ID is used only for interval-based signposts, and must be non-zero + if (m_profile_options & ProfileOptions::USE_INTERVALS) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(intervalSignpostId, "Signpost interval has no identifier!"); + } + // reset signpostIds for sanity check on next call + info.intervalSignpostId = 0; + info.eventSignpostId = 0; + hasPendingCompletionHandlers = true; + + auto m_stream = getDefaultMPSStream(); + // NOTE: the following block isn't thread-safe + [m_stream->commandBuffer() addCompletedHandler:^(id cb) { + CFTimeInterval gpuTime = cb.GPUEndTime > cb.GPUStartTime ? (cb.GPUEndTime - cb.GPUStartTime) * 1000.0 : 0.; + CFTimeInterval schedulingTime = + cb.kernelEndTime > cb.kernelStartTime ? (cb.kernelEndTime - cb.kernelStartTime) * 1000.0 : 0.; + + endProfileExecution(info, eventSignpostId, intervalSignpostId, gpuTime, schedulingTime); + hasPendingCompletionHandlers = false; + }]; + + m_stream->synchronize((m_profile_options & ProfileOptions::WAIT_UNTIL_COMPLETED) ? SyncType::COMMIT_AND_WAIT + : syncType); +} + +void MPSProfiler::logOperationsProfilingStats(std::FILE* f) const { + if (m_op_info_list.empty()) { + // this is not an error, but to let the user know that the + // LogOptions::KERNEL_STATS that they passed to EV is not yielding anything. + fmt::print(f, "There are no MPS operations logged for profiling\n"); + return; + } + // dump the ops info into a vector to sort them + std::vector opsList; + std::transform(m_op_info_list.begin(), m_op_info_list.end(), std::back_inserter(opsList), [](auto& opInfo) { + return opInfo.second.get(); + }); + + // sort based on "Mean GPU time" in descending order + std::sort(opsList.begin(), opsList.end(), [](const OperationInfo* a, const OperationInfo* b) { + return (a->totalGpuTime / double(a->runCount)) > (b->totalGpuTime / double(b->runCount)); + }); + // print the table of operation profiling stats + fmt::print(f, + "\n{:-^200}\n{:^6}|{:^7}|{:^15}|{:^14}|{:^15}| {}\n{:-^200}\n", + fmt::format(" MPS Operations Profiling: {} graphs, {} kernels ", m_graph_counter, m_kernel_counter), + "ID", + "#Runs", + "Mean KRNL(ms)", + "Mean GPU(ms)", + "Total GPU(ms)", + "Operation Name", + ""); + + for (const auto& opInfo : opsList) { + fmt::print(f, + "{:^7}{:^8}{:^16}{:^15}{:^16} {}\n", + fmt::format("{}{}", opInfo->type == BaseInfo::Type::GRAPH ? "G" : "K", opInfo->profileId), + opInfo->runCount, + fmt::format("{:.3f}", opInfo->totalSchedulingTime / double(opInfo->runCount)), + fmt::format("{:.3f}", opInfo->totalGpuTime / double(opInfo->runCount)), + fmt::format("{:.3f}", opInfo->totalGpuTime.load()), + opInfo->strKey); + } +} + +void MPSProfiler::logCPUFallbackProfilingStats(std::FILE* f) const { + if (m_cpu_fb_info_list.empty()) { + // this is not an error, but to let the user know that the + // LogOptions::KERNEL_STATS that they passed to EV is not yielding anything. + fmt::print(f, "There are no CPU Fallbacks logged for profiling\n"); + return; + } + size_t totalCopyOverhead = 0; + size_t totalRunCount = 0; + double totalCPUTime = 0.; + // dump the map's info into a vector to sort them + std::vector cpuFbList; + std::transform( + m_cpu_fb_info_list.begin(), m_cpu_fb_info_list.end(), std::back_inserter(cpuFbList), [&](auto& cpuFbInfo) { + auto cpuFbInfoPtr = cpuFbInfo.second.get(); + totalRunCount += cpuFbInfoPtr->runCount; + totalCopyOverhead += cpuFbInfoPtr->totalCopyOverhead; + totalCPUTime += cpuFbInfoPtr->totalSchedulingTime; + return cpuFbInfoPtr; + }); + + // sort based on "Mean CPU time" in descending order + std::sort(cpuFbList.begin(), cpuFbList.end(), [](const CpuFbInfo* a, const CpuFbInfo* b) { + return (a->totalSchedulingTime / double(a->runCount)) > (b->totalSchedulingTime / double(b->runCount)); + }); + + // print the table of CPU Fallback profiling stats + fmt::print(f, + "\n{:-^150}\n{:^5}|{:^7}|{:^14}|{:^15}|{:^15}| {}\n{:-^150}\n", + fmt::format(" CPU Fallback Profiling: Total {} Runs, {:.2f} ms, {} Copies ", + totalRunCount, + totalCPUTime, + getIMPSAllocator()->formatSize(totalCopyOverhead)), + "ID", + "#Runs", + "Mean CPU(ms)", + "Total CPU(ms)", + "Copy Overhead", + "Operation Name", + ""); + + for (const auto& cpuFbInfo : cpuFbList) { + fmt::print(f, + "{:^6}{:^8}{:^15}{:^16}{:^16} {}\n", + cpuFbInfo->profileId, + cpuFbInfo->runCount, + fmt::format("{:.3f}", cpuFbInfo->totalSchedulingTime / double(cpuFbInfo->runCount)), + fmt::format("{:.3f}", cpuFbInfo->totalSchedulingTime.load()), + getIMPSAllocator()->formatSize(cpuFbInfo->totalCopyOverhead), + cpuFbInfo->opName); + } +} + +void MPSProfiler::logCopyProfilingStats(std::FILE* f) const { + size_t totalCopiesCount = 0; + size_t totalCopySize = 0; + size_t totalScalarCopyCount = 0; + + for (const auto& copyStatPair : m_copy_stat_list) { + const auto& copyStat = *copyStatPair.second; + totalCopiesCount += copyStat.totalCount; + totalCopySize += copyStat.length; + totalScalarCopyCount += copyStat.scalarsCount; + } + if (totalCopiesCount == 0) { + // this is not an error, but to let the user know that the + // LogOptions::COPY_STATS that they passed to EV is not yielding anything. + fmt::print(f, "There are no copies logged for profiling\n"); + return; + } + + // print the table of copy profiling stats + fmt::print(f, + "\n{:-^160}\n{:^12}|{:^10}|{:^17}|{:^16}|{:^15}|{:^9}|{:^13}|{:^10}|{:^8}\n{:-^160}\n", + fmt::format(" MPS Copy Profiling: {} total copies ({}), {} scalar copies ", + totalCopiesCount, + getIMPSAllocator()->formatSize(totalCopySize), + totalScalarCopyCount), + "Kind", + "Total#", + "Total Size", + "Total KRNL(ms)", + "Total GPU(ms)", + "Scalars", + "Scalars GPU", + "Blocking", + "memcpy", + ""); + + for (const auto& copyStatPair : m_copy_stat_list) { + const auto& copyStat = *copyStatPair.second; + if (copyStat.totalCount > 0) { + fmt::print( + f, + "{:^13}{:^11}{:^18}{:^17}{:^16}{:^10}{:^14}{:^11}{:^9}\n", + copyStat.kindStr, + copyStat.totalCount, + getIMPSAllocator()->formatSize(copyStat.length), + fmt::format("{:.3f}", copyStat.totalSchedulingTime.load()), + fmt::format("{:.3f}", copyStat.totalGpuTime.load()), + copyStat.scalarsCount, + fmt::format("{:.2f} %", + copyStat.totalGpuTime > 0.0 + ? (1.0 - ((copyStat.totalGpuTime - copyStat.scalarsGpuTime) / copyStat.totalGpuTime)) * 100.0 + : 0.0), + copyStat.blockingCount, + copyStat.memcpyCount); + } + } +} + +void MPSProfiler::logProfilingStats() { + if (hasLoggedStats.exchange(true)) { + return; + } + // logs kernel profiling stats when the process ends (if enabled). + if (m_log_options & LogOptions::OPERATION_STATS) { + logOperationsProfilingStats(stderr); + } + // logs CPU Fallback profiling stats when the process ends (if enabled). + if (m_log_options & LogOptions::CPU_FALLBACK_STATS) { + logCPUFallbackProfilingStats(stderr); + } + // logs copies profiling stats when the process ends (if enabled). + if (m_log_options & LogOptions::COPY_STATS) { + logCopyProfilingStats(stderr); + } +} + +bool MPSProfiler::isProfileInfoLoggingEnabled(BaseInfo::Type infoType, bool isExecutionEnded) { + bool isInfoLoggingEnabled = false; + // logging the operations, copies, cpu fallbacks info during the execution + // is enabled via the env-var defined in kEVLogProfileInfoStr + switch (infoType) { + case BaseInfo::Type::GRAPH: + case BaseInfo::Type::KERNEL: + isInfoLoggingEnabled = (m_log_options & LogOptions::OPERATION_INFO); + break; + case BaseInfo::Type::COPY: + isInfoLoggingEnabled = (m_log_options & LogOptions::COPY_INFO); + break; + case BaseInfo::Type::CPU_FALLBACK: + isInfoLoggingEnabled = (m_log_options & LogOptions::CPU_FALLBACK_INFO); + break; + default: + TORCH_CHECK(false, "invalid profiling info type"); + } + if (!isInfoLoggingEnabled) { + return false; + } + // if GPU/Kernel times are included then log info when op execution ends + bool logWhenExecutionEnds = m_log_options & (LogOptions::INCLUDE_GPU_TIME | LogOptions::INCLUDE_KERNEL_TIME); + return isExecutionEnded ? logWhenExecutionEnds : !logWhenExecutionEnds; +} + +void MPSProfiler::emitSignpostEvent(SignpostTypes signpost_type, + os_signpost_id_t signpost_id, + const std::string& msg_str) const { + if (!(m_signpost_types & signpost_type) || !signpost_id || !m_os_log_events || + !os_signpost_enabled(m_os_log_events)) { + return; + } + const char* msg = msg_str.c_str(); + + // need to use switch-case as the signpost names must be literal strings + switch (signpost_type) { + case SignpostTypes::RUN_OPERATION: + os_signpost_event_emit(m_os_log_events, signpost_id, kEvtSignpostRunOperationStr, "%s", msg); + break; + case SignpostTypes::BLIT_COPY: + os_signpost_event_emit(m_os_log_events, signpost_id, kEvtSignpostBlitCopyStr, "%s", msg); + break; + case SignpostTypes::CPU_FALLBACK: + os_signpost_event_emit(m_os_log_events, signpost_id, kEvtSignpostCPUFallbacksStr, "%s", msg); + break; + default: + TORCH_CHECK(false, "unknown SignpostType in MPS profiler"); + } +} + +void MPSProfiler::beginSignpostInterval(SignpostTypes signpost_type, + os_signpost_id_t signpost_id, + const std::string& msg_str) const { + if (!(m_signpost_types & signpost_type) || !signpost_id || !m_os_log_intervals || + !os_signpost_enabled(m_os_log_intervals)) { + return; + } + const char* msg = msg_str.c_str(); + + switch (signpost_type) { + case SignpostTypes::RUN_OPERATION: + os_signpost_interval_begin(m_os_log_intervals, signpost_id, kIntSignpostRunOperationStr, "%s", msg); + break; + case SignpostTypes::BLIT_COPY: + os_signpost_interval_begin(m_os_log_intervals, signpost_id, kIntSignpostBlitCopyStr, "%s", msg); + break; + case SignpostTypes::CPU_FALLBACK: + os_signpost_interval_begin(m_os_log_intervals, signpost_id, kIntSignpostCPUFallbacksStr, "%s", msg); + break; + default: + TORCH_CHECK(false, "unknown SignpostType in MPS profiler"); + } +} + +void MPSProfiler::endSignpostInterval(SignpostTypes signpost_type, os_signpost_id_t signpost_id) const { + if (!m_os_log_intervals || !os_signpost_enabled(m_os_log_intervals)) { + return; + } + switch (signpost_type) { + case SignpostTypes::RUN_OPERATION: + os_signpost_interval_end(m_os_log_intervals, signpost_id, kIntSignpostRunOperationStr); + break; + case SignpostTypes::BLIT_COPY: + os_signpost_interval_end(m_os_log_intervals, signpost_id, kIntSignpostBlitCopyStr); + break; + case SignpostTypes::CPU_FALLBACK: + os_signpost_interval_end(m_os_log_intervals, signpost_id, kIntSignpostCPUFallbacksStr); + break; + default: + TORCH_CHECK(false, "unknown SignpostType in MPS profiler"); + } +} + +os_signpost_id_t MPSProfiler::generateSignpostId(os_signpost_type_t signpostType, const void* ptr) { + os_log_t os_log = signpostType == OS_SIGNPOST_EVENT ? m_os_log_events : m_os_log_intervals; + if (ptr) { + return os_signpost_id_make_with_pointer(os_log, ptr); + } + return os_signpost_id_generate(os_log); +} + +MPSProfiler::SignpostTypes MPSProfiler::getSignpostType(BaseInfo::Type infoType) { + switch (infoType) { + case BaseInfo::Type::GRAPH: + case BaseInfo::Type::KERNEL: + return SignpostTypes::RUN_OPERATION; + case BaseInfo::Type::COPY: + return SignpostTypes::BLIT_COPY; + case BaseInfo::Type::CPU_FALLBACK: + return SignpostTypes::CPU_FALLBACK; + default: + TORCH_CHECK(false, "invalid profiling info type"); + } +} + +void MPSProfiler::handleIntSignal(int signal) { + getMPSProfiler().logProfilingStats(); + if (previousSigint.sa_handler) { + previousSigint.sa_handler(signal); + } +} + +// used to capture sigint signal to log profiling stats +struct sigaction MPSProfiler::currentSigint{}; +struct sigaction MPSProfiler::previousSigint{}; + +bool MPSProfiler::isCapturing() const { + return [captureManager isCapturing]; +} + +bool MPSProfiler::isCaptureEnabled() const { + if (captureManager == nil) { + captureManager = [MTLCaptureManager sharedCaptureManager]; + } + static bool isEnabled = [this]() { + return [captureManager supportsDestination:MTLCaptureDestinationGPUTraceDocument]; + }(); + return isEnabled; +} + +void MPSProfiler::startCapture(const std::string& name, MPSStream* stream) { + if (captureManager == nil) { + captureManager = [MTLCaptureManager sharedCaptureManager]; + } + NSError* err = nil; + NSString* fname = [NSString stringWithFormat:@"%04d-%s.gputrace", captureCount++, name.c_str()]; + MTLCaptureDescriptor* captureDescriptor = [MTLCaptureDescriptor new]; + captureDescriptor.captureObject = stream ? (id)stream->commandQueue() : (id)MPSDevice::getInstance()->device(); + captureDescriptor.destination = MTLCaptureDestinationGPUTraceDocument; + captureDescriptor.outputURL = [NSURL fileURLWithPath:fname]; + auto rc = [captureManager startCaptureWithDescriptor:captureDescriptor error:&err]; + TORCH_CHECK(rc, "Failed to start capture of ", [fname UTF8String], " error ", [[err description] UTF8String]); +} + +void MPSProfiler::stopCapture(MPSStream* stream) { + if (stream) { + stream->synchronize(SyncType::COMMIT); + } + [captureManager stopCapture]; +} + +} // namespace Profiler + +Profiler::MPSProfiler& getMPSProfiler() { + static std::unique_ptr mps_profiler; + if (mps_profiler == nullptr) { + mps_profiler = std::make_unique(); + } + return *mps_profiler; +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSStream.h b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSStream.h new file mode 100644 index 0000000000000000000000000000000000000000..6efee8557d2fee1f97a3785134ddee510a54c132 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSStream.h @@ -0,0 +1,170 @@ +// Copyright © 2022 Apple Inc. + +#pragma once + +#include +#include + +#include +#include +#include +#include + +#ifdef __OBJC__ +// Apple framework headers emit deprecation warnings from CarbonCore and +// missing-attribute warnings from MPSGraph on recent macOS SDKs. +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wdeprecated-declarations") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wobjc-property-no-attribute") +#include +#include +#include +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +typedef MPSCommandBuffer* MPSCommandBuffer_t; +typedef id MTLCommandQueue_t; +typedef id MTLComputeCommandEncoder_t; +typedef id MTLSharedEvent_t; +typedef id MTLDevice_t; +typedef id MTLBuffer_t; +#else +#include +typedef void* MPSCommandBuffer_t; +typedef void* MPSGraph; +typedef void* MPSGraphExecutionDescriptor; +typedef void* MPSGraphCompilationDescriptor; +typedef void* MTLCommandQueue_t; +typedef void* MTLComputeCommandEncoder_t; +typedef void* MTLSharedEvent_t; +typedef void* MTLDevice_t; +typedef void* MTLBuffer_t; +typedef void* MTLCommandBufferHandler; +typedef void* NSDictionary; +#define nil NULL +#endif + +namespace at::mps { + +//----------------------------------------------------------------- +// MPSStream +//----------------------------------------------------------------- + +enum class SyncType { + NONE, // no commit to command buffer + COMMIT, // commit and flush the command buffer + COMMIT_AND_WAIT, // flush and wait for command buffer execution to finish + COMMIT_AND_CONTINUE, // commit and continue with a new underlying command buffer + COMMIT_ADAPTIVE, // commit adaptively based on available memory +}; + +class TORCH_API MPSStream { + public: + enum Unchecked { UNCHECKED }; + + /// Construct a MPSStream from a Stream. This construction is checked, + /// and will raise an error if the Stream is not, in fact, a MPS stream. + explicit MPSStream(Stream stream); + + ~MPSStream(); + + MTLCommandQueue_t commandQueue() const { + return _commandQueue; + } + + dispatch_queue_t queue() const { + return _serialQueue; + } + + MPSCommandBuffer_t commandBuffer(); + MTLComputeCommandEncoder_t commandEncoder(); + void endKernelCoalescing(); + void synchronize(SyncType syncType); + void copy(MTLBuffer_t srcBuffer, + MTLBuffer_t dstBuffer, + size_t length, + size_t srcOffset, + size_t dstOffset, + uint64_t profileId, + SyncType syncType = SyncType::NONE); + void copy_and_sync(MTLBuffer_t srcBuffer, + MTLBuffer_t dstBuffer, + size_t length, + size_t srcOffset, + size_t dstOffset, + bool non_blocking, + uint64_t profileId); + void executeMPSGraph(MPSGraph* mpsGraph, + NSDictionary* feeds, + NSDictionary* results, + SyncType syncType = SyncType::NONE); + void addCompletedHandler(MTLCommandBufferHandler block); + + /// Get the MPS device index that this stream is associated with. + c10::DeviceIndex device_index() const { + return _stream.device_index(); + } + + MTLCommandQueue_t stream() const { + return _commandQueue; + } + + MTLDevice_t device() const; + + /// Explicit conversion to Stream. + Stream unwrap() const { + return _stream; + } + + MTLBuffer_t getErrorBuffer(); + void checkLastError(); + + private: + Stream _stream; + MTLCommandQueue_t _commandQueue = nil; + MPSCommandBuffer_t _commandBuffer = nil; + MPSCommandBuffer_t _prevCommandBuffer = nil; + MTLComputeCommandEncoder_t _commandEncoder = nil; + MPSGraphExecutionDescriptor* _executionDescriptor = nil; + MPSGraphCompilationDescriptor* _compilationDescriptor = nil; + dispatch_queue_t _serialQueue = nullptr; + // CommitAndContinue is enabled by default + bool _enableCommitAndContinue = true; + // Buffer that contains last raised error + MTLBuffer_t _errorBuffer = nil; + + // use synchronize() to access any of these commit functions outside MPSStream + void commit(); + void commitAndWait(); + void commitAndContinue(); + void flush(); +}; + +/** + * Get the current MPS stream + */ +TORCH_API MPSStream* getCurrentMPSStream(); + +/** + * Get the default MPS stream + */ +TORCH_API MPSStream* getDefaultMPSStream(); + +//----------------------------------------------------------------- +// MPSStreamImpl +//----------------------------------------------------------------- + +class TORCH_API MPSStreamImpl { + public: + /** + * Gets single instance of the MPSStream. + */ + static MPSStream* getInstance(); + + private: + static MPSStream* _stream; + MPSStreamImpl(); +}; + +#ifdef __OBJC__ +void dispatch_sync_with_rethrow(dispatch_queue_t queue, void (^block)()); +#endif +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/mps/MPSStream.mm b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSStream.mm new file mode 100644 index 0000000000000000000000000000000000000000..d98db5329090c8d8e9de5c05d58ef7f1e09bf3b2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/mps/MPSStream.mm @@ -0,0 +1,306 @@ +// Copyright © 2022 Apple Inc. + +#include +#include +#include +#include + +@interface MPSGraphExecutionDescriptor () +@property(readwrite, atomic) BOOL enableCommitAndContinue; +@end + +namespace at::mps { +//----------------------------------------------------------------- +// MPSStream +//----------------------------------------------------------------- + +MPSStream::MPSStream(Stream stream) : _stream(stream) { + _commandQueue = [MPSDevice::getInstance()->device() newCommandQueue]; + TORCH_CHECK(_stream.device_type() == DeviceType::MPS); + _serialQueue = dispatch_queue_create("metal gpu stream", nullptr); + _executionDescriptor = [MPSGraphExecutionDescriptor new]; + _compilationDescriptor = [MPSGraphCompilationDescriptor new]; + + // disable commitAndContinue if Signpost tracing is enabled + if (getMPSProfiler().isSignpostTracingEnabled() || getMPSProfiler().isCaptureEnabled()) { + _enableCommitAndContinue = false; + } + _executionDescriptor.enableCommitAndContinue = _enableCommitAndContinue; + + // Choose level which optimizes for GPU + _compilationDescriptor.optimizationLevel = MPSGraphOptimizationLevel0; + _executionDescriptor.compilationDescriptor = _compilationDescriptor; + + _errorBuffer = [MPSDevice::getInstance()->device() newBufferWithLength:sizeof(c10::metal::ErrorMessages) + options:MTLResourceStorageModeShared]; + std::memset([_errorBuffer contents], 0, 1024); +} + +MPSStream::~MPSStream() { + [_commandQueue release]; + _commandQueue = nil; + [_executionDescriptor release]; + [_compilationDescriptor release]; + _executionDescriptor = nil; + [_errorBuffer release]; + _errorBuffer = nil; + _compilationDescriptor = nil; + + assert(_commandBuffer == nil); +} + +MPSCommandBuffer* MPSStream::commandBuffer() { + if (!_commandBuffer) { + _commandBuffer = [MPSCommandBuffer commandBufferFromCommandQueue:_commandQueue].retain; + } + + return _commandBuffer; +} + +id MPSStream::device() const { + return [_commandQueue device]; +} + +id MPSStream::commandEncoder() { + if (!_commandEncoder) { + _commandEncoder = [commandBuffer() computeCommandEncoder].retain; + } + + return _commandEncoder; +} + +void MPSStream::synchronize(SyncType syncType) { + endKernelCoalescing(); + switch (syncType) { + case SyncType::NONE: + // typically in GPU to GPU copies we won't commit explicitly + break; + case SyncType::COMMIT: + commit(); + break; + case SyncType::COMMIT_ADAPTIVE: + // the adaptive commit only commits if we hit the low watermark memory threshold + if (getIMPSAllocator()->getLowWatermarkValue() <= 1) { + commit(); + } + break; + case SyncType::COMMIT_AND_WAIT: + commitAndWait(); + break; + case SyncType::COMMIT_AND_CONTINUE: + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(_enableCommitAndContinue, + "CommitAndContinue is called but it is disabled globally!"); + commitAndContinue(); + break; + } +} + +void MPSStream::commit() { + if (_enableCommitAndContinue) { + [commandBuffer() commitAndContinue]; + } else { + flush(); + } +} + +void MPSStream::commitAndWait() { + if (_prevCommandBuffer) { + // the previous command buffer (if exists) has already been committed, + // so we just wait until it's completed and then dispose it. + [_prevCommandBuffer waitUntilCompleted]; + [_prevCommandBuffer release]; + _prevCommandBuffer = nil; + checkLastError(); + } + + if (_commandBuffer) { + [_commandBuffer commit]; + [_commandBuffer waitUntilCompleted]; + [_commandBuffer release]; + _commandBuffer = nil; + checkLastError(); + } +} + +void MPSStream::commitAndContinue() { + assert(_commandBuffer); + [_commandBuffer commitAndContinue]; +} + +void MPSStream::endKernelCoalescing() { + if (_commandEncoder) { + [_commandEncoder endEncoding]; + [_commandEncoder release]; + _commandEncoder = nil; + } +} + +void MPSStream::flush() { + if (_commandBuffer) { + [_commandBuffer commit]; + // if commitAndContinue is disabled (e.g., for Profiler), we keep the command + // buffer so we could wait on it later, if required. + if (!_enableCommitAndContinue) { + _prevCommandBuffer = _commandBuffer; + } else { + [_commandBuffer release]; + } + _commandBuffer = nil; + } +} + +void MPSStream::addCompletedHandler(MTLCommandBufferHandler block) { + dispatch_sync(_serialQueue, ^() { + @autoreleasepool { + [commandBuffer() addCompletedHandler:block]; + } + }); +} + +void MPSStream::copy(id srcBuffer, + id dstBuffer, + size_t length, + size_t srcOffset, + size_t dstOffset, + uint64_t profileId, + SyncType syncType) { + dispatch_sync_with_rethrow(_serialQueue, ^() { + @autoreleasepool { + endKernelCoalescing(); + id blitEncoder = [commandBuffer() blitCommandEncoder]; + + // For some reason copyFromBuffer for 4Gb fails without returning an error + // See https://github.com/pytorch/pytorch/issues/124335 + // Workaround by batching copy commands into 2Gb chunks + constexpr size_t max_copy_size = 0x80000000; // 2GB + size_t bytes_copied = 0; + size_t bytes_remains = length; + while (bytes_remains > 0) { + NSUInteger bytes_to_copy = std::min(max_copy_size, bytes_remains); + [blitEncoder copyFromBuffer:srcBuffer + sourceOffset:(NSUInteger)srcOffset + bytes_copied + toBuffer:dstBuffer + destinationOffset:(NSUInteger)dstOffset + bytes_copied + size:bytes_to_copy]; + bytes_copied += bytes_to_copy; + bytes_remains -= bytes_to_copy; + } + [blitEncoder endEncoding]; + + // profilerId has a value only if copy profiling is enabled + if (profileId) { + getMPSProfiler().endProfileCopy(profileId, syncType); + } else { + synchronize(syncType); + } + } + }); +} + +void MPSStream::copy_and_sync(id srcBuffer, + id dstBuffer, + size_t length, + size_t srcOffset, + size_t dstOffset, + bool non_blocking, + uint64_t profileId) { + copy(srcBuffer, + dstBuffer, + length, + srcOffset, + dstOffset, + profileId, + !non_blocking ? SyncType::COMMIT_AND_WAIT : SyncType::COMMIT); +} + +void MPSStream::executeMPSGraph(MPSGraph* mpsGraph, NSDictionary* feeds, NSDictionary* results, SyncType syncType) { + auto& profiler = getMPSProfiler(); + const bool isGraphProfilingEnabled = profiler.isOperationProfilingEnabled(); + + dispatch_sync_with_rethrow(_serialQueue, ^() { + endKernelCoalescing(); + if (isGraphProfilingEnabled) { + // this function call is only relevant for interval-based Signposts + // which exclude schedule time (only includes GPU run time) + profiler.beginProfileGPUInterval(mpsGraph); + } + // note: CommitAndContinue feature is enabled/disabled via "_executionDescriptor" + [mpsGraph encodeToCommandBuffer:commandBuffer() + feeds:feeds + targetOperations:nil + resultsDictionary:results + executionDescriptor:_executionDescriptor]; + + SyncType _syncType = syncType; + // if commitAndContinue is disabled, we need to always commit manually after encoding + if (!_enableCommitAndContinue && syncType != SyncType::COMMIT_AND_WAIT) { + _syncType = SyncType::COMMIT; + } + + // check if graph execution profiling is enabled + if (isGraphProfilingEnabled) { + // with profiler enabled, we commit after adding the completedHandler in MPSProfiler + profiler.endProfileKernel(mpsGraph, _syncType); + } else { + synchronize(_syncType); + } + }); +} + +id MPSStream::getErrorBuffer() { + return _errorBuffer; +} + +void MPSStream::checkLastError() { + auto msgs = reinterpret_cast([_errorBuffer contents]); + if (!msgs) { + return; + } + const auto& msg = msgs->msg[0]; + unsigned int count = 0; + std::swap(count, msgs->count); + if (!count) { + return; + } + throw c10::AcceleratorError({msg.func, msg.file, msg.line}, 1, msg.message); +} + +//----------------------------------------------------------------- +// MPSStreamImpl +//----------------------------------------------------------------- + +MPSStream* MPSStreamImpl::_stream = nullptr; + +MPSStream* MPSStreamImpl::getInstance() { + if (_stream == nullptr) { + _stream = new MPSStream(Stream(Stream::UNSAFE, c10::Device(DeviceType::MPS, 0), 0)); + } + return _stream; +} + +MPSStreamImpl::MPSStreamImpl() {} + +MPSStream* getCurrentMPSStream() { + return getDefaultMPSStream(); +} + +MPSStream* getDefaultMPSStream() { + return MPSStreamImpl::getInstance(); +} + +// Helper methods +void dispatch_sync_with_rethrow(dispatch_queue_t queue, void (^block)()) { + __block std::optional block_exception; + dispatch_sync(queue, ^() { + try { + block(); + } catch (...) { + block_exception = std::current_exception(); + } + }); + if (block_exception) { + std::rethrow_exception(*block_exception); + } +} + +} // namespace at::mps diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Activation.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Activation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66593d4b1aaba9844ed5f6db42317ff3c1568c74 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Activation.cpp @@ -0,0 +1,849 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#if defined(C10_MOBILE) && defined(USE_XNNPACK) +#include +#endif +#include + +#include +#include +#if AT_MKLDNN_ENABLED() +#include +#include +#endif + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace at::meta { +// computes `result = self <= threshold ? value : other` +// other is `self` in threshold() and `grad` in threshold_backward() +TORCH_META_FUNC(threshold)(const Tensor& self, const Scalar& threshold, const Scalar& value) { + const Tensor& result = maybe_get_output(); + build(TensorIteratorConfig() + .set_check_mem_overlap(false) // threshold is idempotent, so overlap is okay + .add_output(result) + .add_const_input(self) + .add_const_input(self) // other + .allow_cpu_scalars(true) + .promote_inputs_to_common_dtype(true) + .cast_common_dtype_to_outputs(true) + .enforce_safe_casting_to_output(true)); +} +// computes `result = self <= threshold ? value : other` +// other is `self` in threshold() and `grad` in threshold_backward() +TORCH_META_FUNC(threshold_backward)(const Tensor& grad, const Tensor& self, const Scalar& threshold) { + const Tensor& gradInput = maybe_get_output(); + build(TensorIteratorConfig() + .set_check_mem_overlap(false) // threshold is idempotent, so overlap is okay + .add_output(gradInput) + .add_const_input(self) + .add_const_input(grad) // other + .allow_cpu_scalars(true) + .promote_inputs_to_common_dtype(true) + .cast_common_dtype_to_outputs(true) + .enforce_safe_casting_to_output(true)); +} + +TORCH_META_FUNC(elu) ( + const Tensor& self, const Scalar& alpha, const Scalar& scale, const Scalar& input_scale +) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(elu_backward) ( + const Tensor& grad_output, + const Scalar& alpha, + const Scalar& scale, + const Scalar& input_scale, + bool is_result, + const Tensor& self_or_result +) { + TORCH_CHECK( + !is_result || alpha.to() >= 0.0, + "In-place elu backward calculation is triggered with a negative slope which is not supported. " + "This is caused by calling in-place forward function with a negative slope, " + "please call out-of-place version instead."); + + build_borrowing_binary_op(maybe_get_output(), grad_output, self_or_result); +} + +TORCH_META_FUNC(silu) (const Tensor& self) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(silu_backward) ( + const Tensor& grad_output, const Tensor& input +) { + build_borrowing_binary_op(maybe_get_output(), grad_output, input); +} + +TORCH_META_FUNC(mish) (const Tensor& self) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(softplus) ( + const Tensor& self, const Scalar& beta, const Scalar& threshold +) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(softplus_backward) ( + const Tensor& grad_output, + const Tensor& self, + const Scalar& beta, + const Scalar& threshold +) { + build_borrowing_binary_op(maybe_get_output(), grad_output, self); +} + +TORCH_META_FUNC(leaky_relu) ( + const Tensor& self, const Scalar& negval +) { + build_unary_op(maybe_get_output(), self); +} + +// Note: leakyReLu backward calculation doesn't support in-place call with negative slope. +// The reason is that for in-place forward call, the forward result will be saved into autograd +// node instead of the input itself, when calculating backward gradient, there is no way to know +// whether the original input for current node is positive or not if the input slope is +// negative. eg. forward is 2, slope is -0.2, the original input for this node could be +// either 2, or -10, so no way to get a correct backward gradient in this case. +TORCH_META_FUNC(leaky_relu_backward) ( + const Tensor& grad_output, + const Tensor& self_or_result, + const Scalar& negval, + bool is_result +) { + TORCH_CHECK( + !is_result || negval.to() >= 0.0, + "In-place leakyReLu backward calculation is triggered with a negative slope which is not supported. " + "This is caused by calling in-place forward function with a negative slope, " + "please call out-of-place version instead. File an issue at https://github.com/pytorch/pytorch if you do " + "require supporting in-place leakRelu backward calculation with negative slope"); + + build_borrowing_binary_op(maybe_get_output(), self_or_result, grad_output); +} + +TORCH_META_FUNC(hardsigmoid) (const Tensor& self) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(hardsigmoid_backward) (const Tensor& grad_output, const Tensor& self) { + build_borrowing_binary_op(maybe_get_output(), grad_output, self); +} + +TORCH_META_FUNC(hardshrink) (const Tensor & self, const Scalar& lambd) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(hardshrink_backward) ( + const Tensor & grad, const Tensor & self, const Scalar& lambd +) { + build_borrowing_binary_op(maybe_get_output(), grad, self); +} + +TORCH_META_FUNC(softshrink) ( + const Tensor & self, const Scalar& lambd +) { + double lamb = lambd.to(); + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, + self.scalar_type(), "softshrink_check", [&] { + auto max_val = static_cast(std::numeric_limits::max()); + TORCH_CHECK(0 <= lamb && lamb <= max_val, + "lambda must be in range [0, ", max_val, "] for input dtype ", + self.scalar_type(), ", but found ", lamb); + }); + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(softshrink_backward) ( + const Tensor & grad, const Tensor & self, const Scalar& lambd +) { + build_borrowing_binary_op(maybe_get_output(), grad, self); +} + +TORCH_META_FUNC(gelu) (const Tensor & self, std::string_view approximate) { + build_unary_op(maybe_get_output(), self); +} + +TORCH_META_FUNC(gelu_backward) ( + const Tensor& grad, const Tensor& self, std::string_view approximate +) { + build_borrowing_binary_op(maybe_get_output(), grad, self); +} + +} // namespace at::meta + +namespace at::native { + +static constexpr double SELU_ALPHA = 1.6732632423543772848170429916717; +static constexpr double SELU_SCALE = 1.0507009873554804934193349852946; + +DEFINE_DISPATCH(elu_stub); +DEFINE_DISPATCH(elu_backward_stub); +DEFINE_DISPATCH(softplus_stub); +DEFINE_DISPATCH(softplus_backward_stub); +DEFINE_DISPATCH(log_sigmoid_cpu_stub); +DEFINE_DISPATCH(log_sigmoid_backward_stub); +DEFINE_DISPATCH(threshold_stub); +DEFINE_DISPATCH(hardtanh_backward_stub); +DEFINE_DISPATCH(hardsigmoid_stub); +DEFINE_DISPATCH(hardsigmoid_backward_stub); +DEFINE_DISPATCH(hardswish_stub); +DEFINE_DISPATCH(hardswish_backward_stub); +DEFINE_DISPATCH(hardshrink_stub); +DEFINE_DISPATCH(softshrink_stub); +DEFINE_DISPATCH(shrink_backward_stub); +DEFINE_DISPATCH(leaky_relu_stub); +DEFINE_DISPATCH(leaky_relu_backward_stub); +DEFINE_DISPATCH(silu_stub); +DEFINE_DISPATCH(silu_backward_stub); +DEFINE_DISPATCH(mish_stub); +DEFINE_DISPATCH(mish_backward_stub); +DEFINE_DISPATCH(prelu_stub); +DEFINE_DISPATCH(prelu_backward_stub); + +TORCH_IMPL_FUNC(elu_out) ( + const Tensor& self, const Scalar& alpha, const Scalar& scale, const Scalar& input_scale, const Tensor& result +) { + elu_stub(device_type(), *this, alpha, scale, input_scale); +} + +TORCH_IMPL_FUNC(elu_backward_out) ( + const Tensor& grad_output, + const Scalar& alpha, + const Scalar& scale, + const Scalar& input_scale, + bool is_result, + const Tensor& self_or_result, + const Tensor& grad_input +) { + elu_backward_stub(device_type(), *this, alpha, scale, input_scale, is_result); +} + +TORCH_IMPL_FUNC(silu_out) ( + const Tensor& self, const Tensor& result +) { + silu_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(silu_backward_out) ( + const Tensor& grad_output, const Tensor& input, const Tensor& grad_input +) { + silu_backward_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(mish_out) ( + const Tensor& self, const Tensor& result +) { + mish_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(softplus_out) ( + const Tensor& self, const Scalar& beta, const Scalar& threshold, const Tensor& result +) { + softplus_stub(device_type(), *this, beta, threshold); +} + +TORCH_IMPL_FUNC(softplus_backward_out) ( + const Tensor& grad_output, + const Tensor& self, + const Scalar& beta, + const Scalar& threshold, + const Tensor& grad_input +) { + softplus_backward_stub(device_type(), *this, beta, threshold); +} + +TORCH_IMPL_FUNC(leaky_relu_out) ( + const Tensor& self, const Scalar& negval, const Tensor& result +) { + leaky_relu_stub(device_type(), *this, negval); +} + +TORCH_IMPL_FUNC(leaky_relu_backward_out) ( + const Tensor& grad_output, + const Tensor& self_or_result, + const Scalar& negval, + bool is_result, + const Tensor& grad_input +) { + leaky_relu_backward_stub(device_type(), *this, negval); +} + +TORCH_IMPL_FUNC(hardsigmoid_out) ( + const Tensor& self, const Tensor& result +) { + hardsigmoid_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(hardsigmoid_backward_out) ( + const Tensor& grad_output, const Tensor& self, const Tensor& grad_input +) { + hardsigmoid_backward_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(hardshrink_out) ( + const Tensor & self, const Scalar& lambd, const Tensor& result +) { + hardshrink_stub(device_type(), *this, lambd); +} + +TORCH_IMPL_FUNC(hardshrink_backward_out) ( + const Tensor & grad, const Tensor & self, const Scalar& lambd, const Tensor& grad_input +) { + shrink_backward_stub(device_type(), *this, lambd); +} + +TORCH_IMPL_FUNC(softshrink_out) ( + const Tensor & self, const Scalar& lambd, const Tensor& result +) { + softshrink_stub(device_type(), *this, lambd); +} + +TORCH_IMPL_FUNC(softshrink_backward_out) ( + const Tensor & grad, const Tensor & self, const Scalar& lambd, const Tensor& grad_input +) { + shrink_backward_stub(device_type(), *this, lambd); +} + +#if AT_MKLDNN_ENABLED() +static bool use_mkldnn(const Tensor& input) { + if (!at::globalContext().userEnabledMkldnn()) { + return false; + } + if (!input.is_contiguous() || input.numel() <= 1) { + return false; + } + return (input.is_mkldnn()) || // input is mkldnn Tensor + (input.device().is_cpu() && + (((input.scalar_type() == kBFloat16) && mkldnn_bf16_device_check()) || + ((input.scalar_type() == kHalf) && mkldnn_fp16_device_check()) || + (input.scalar_type() == kFloat))); // input is dense layout and bfloat16/float16/float32 +} +#endif + +TORCH_IMPL_FUNC(gelu_out_cpu) ( + const Tensor& self, std::string_view approximate, const Tensor& result +) { +auto approximate_type = get_gelutype_enum(approximate); +#if AT_MKLDNN_ENABLED() + if (use_mkldnn(self) && (approximate_type == GeluType::None)) { + const ideep::tensor& x = itensor_from_tensor(self, /*from_const_data_ptr*/true); + ideep::tensor y = itensor_from_tensor(result); + ideep::eltwise_forward::compute( + x, y, ideep::algorithm::eltwise_gelu_erf, ideep::prop_kind::forward_training, /*alpha*/ 0.0); +#ifdef __aarch64__ + } else if (use_mkldnn(self) && (approximate_type == GeluType::Tanh)) { + const ideep::tensor& x = itensor_from_tensor(self, /*from_const_data_ptr*/true); + ideep::tensor y = itensor_from_tensor(result); + ideep::eltwise_forward::compute( + x, y, ideep::algorithm::eltwise_gelu_tanh, ideep::prop_kind::forward_training, /*alpha*/ 0.0); +#endif // ifdef __aarch64__ + } else { + GeluKernel(kCPU, *this, approximate_type); + } +#else + GeluKernel(kCPU, *this, approximate_type); +#endif +} + +TORCH_IMPL_FUNC(gelu_backward_out_cpu) ( + const Tensor& grad, const Tensor& self, std::string_view approximate, const Tensor& grad_input +) { +auto approximate_type = get_gelutype_enum(approximate); +#if AT_MKLDNN_ENABLED() + if (use_mkldnn(self) && (approximate_type == GeluType::None)) { + const ideep::tensor& x = itensor_from_tensor(self, /*from_const_data_ptr*/true); + ideep::tensor grady = itensor_from_tensor(grad, /*from_const_data_ptr*/true); + ideep::tensor gradx = itensor_from_tensor(grad_input); + ideep::eltwise_backward::compute(x, grady, gradx, + ideep::algorithm::eltwise_gelu_erf, /*alpha*/ 0.0); + } else { + GeluBackwardKernel(kCPU, *this, approximate_type); + } +#else + GeluBackwardKernel(kCPU, *this, approximate_type); +#endif +} + +Tensor hardtanh(const Tensor& self, const Scalar& min, const Scalar& max) { + Tensor result = at::empty_like(self); + return at::hardtanh_out(result, self, min, max); +} + +Tensor& hardtanh_out(const Tensor& self, const Scalar& min, const Scalar& max, Tensor& result) { + TORCH_CHECK(self.scalar_type() != at::kBool, + "Bool inputs not supported for hardtanh"); + //preserve legacy behavior of boundaries not causing type promotion + Scalar min_, max_; + if (at::isIntegralType(self.scalar_type(), /*include_bool*/false)) { + int64_t minval = min.toLong(); + int64_t maxval = max.toLong(); + TORCH_CHECK(self.dtype() != at::kByte || (minval >= 0 && + maxval >=0), "cannot do hardtanh on an unsigned type with negative limits"); + min_ = minval; + max_ = maxval; + } else { + min_ = min; + max_ = max; + } + return at::clamp_out(result, self, min_, max_); +} + +Tensor& hardtanh_(Tensor& self, const Scalar& min, const Scalar& max) { + return at::hardtanh_out(self, self, min, max); +} + +Tensor& hardtanh_backward_out(const Tensor& grad_output, const Tensor& self, const Scalar& min, const Scalar& max, Tensor& grad_input) { + auto iter = TensorIterator::borrowing_binary_op(grad_input, grad_output, self); + hardtanh_backward_stub(iter.device_type(), iter, min, max); + return grad_input; +} + +Tensor hardtanh_backward(const Tensor& grad_output, const Tensor& self, const Scalar& min, const Scalar& max) { + Tensor result; + auto iter = TensorIterator::borrowing_binary_op(result, grad_output, self); + hardtanh_backward_stub(iter.device_type(), iter, min, max); + return iter.output(); +} + +Tensor hardswish(const Tensor& self) { + #if defined(C10_MOBILE) && defined(USE_XNNPACK) + if (xnnpack::use_hardswish(self)) { + return xnnpack::hardswish(self); + } + #endif + Tensor result; + auto iter = TensorIterator::unary_op(result, self); + hardswish_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor& hardswish_out(const Tensor& self, Tensor& result) { + auto iter = TensorIterator::unary_op(result, self); + hardswish_stub(iter.device_type(), iter); + return result; +} + +Tensor& hardswish_(Tensor& self) { + #if defined(C10_MOBILE) && defined(USE_XNNPACK) + if (xnnpack::use_hardswish(self)) { + xnnpack::hardswish_(self); + return self; + } + #endif + auto iter = TensorIterator::unary_op(self, self); + hardswish_stub(iter.device_type(), iter); + return self; +} + +Tensor hardswish_backward(const Tensor& grad_output, const Tensor& self) { + Tensor grad_input; + auto iter = TensorIterator::borrowing_binary_op(grad_input, grad_output, self); + hardswish_backward_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor relu(const Tensor & self) { + TORCH_CHECK(self.scalar_type() != at::kBool, "Boolean inputs not supported for relu"); + return at::clamp_min(self, 0); +} + +Tensor & relu_(Tensor & self) { + TORCH_CHECK(self.scalar_type() != at::kBool, "Boolean inputs not supported for relu"); + return at::clamp_min_(self, 0); +} + +Tensor selu(const Tensor & self) { + return at::elu(self, SELU_ALPHA, SELU_SCALE); +} + +Tensor relu6(const Tensor & self) { + return at::hardtanh(self, /*min_val=*/0, /*max_val=*/6); +} + +Tensor & selu_(Tensor & self) { + return at::elu_(self, SELU_ALPHA, SELU_SCALE); +} + +Tensor & relu6_(Tensor & self) { + return at::hardtanh_(self, /*min_val=*/0, /*max_val=*/6); +} + +Tensor celu(const Tensor & self, const Scalar& alpha) { + TORCH_CHECK(alpha.to() != 0, + "ZeroDivisionError: alpha cannot be 0 for CELU"); + double inv_alpha = 1. / alpha.to(); + return at::elu(self, alpha, Scalar(1.0), Scalar(inv_alpha)); +} + +Tensor & celu_(Tensor & self, const Scalar& alpha) { + TORCH_CHECK(alpha.to() != 0, + "ZeroDivisionError: alpha cannot be 0 for CELU"); + double inv_alpha = 1. / alpha.to(); + return at::elu_(self, alpha, Scalar(1.0), Scalar(inv_alpha)); +} + +Tensor math_silu_backward( + const Tensor& grad_output, + const Tensor& input) { + auto input_sigmoid = at::sigmoid(input); + return grad_output * (input_sigmoid * (1 + input * (1 - input_sigmoid))); +} + +Tensor mish_backward( + const Tensor& grad_output, + const Tensor& input) { + Tensor grad_input = at::empty({0}, input.options()); + auto iter = TensorIterator::binary_op(grad_input, grad_output, input); + mish_backward_stub(iter.device_type(), iter); + return grad_input; +} + +Tensor math_mish_backward( + const Tensor& grad_output, + const Tensor& input) { + auto input_tanh_softplus = at::tanh(at::softplus(input)); + auto input_sigmoid = at::sigmoid(input); + return grad_output * (input_tanh_softplus + (input * input_sigmoid * (1 - input_tanh_softplus * input_tanh_softplus))); +} + +template +static void _rrelu_with_noise_train( + Tensor& output, + const Tensor& input, + Tensor& noise, + const Scalar& lower_, + const Scalar& upper_, + const std::optional& generator) { + using opmath_t = at::opmath_type; + opmath_t lower = lower_.to(); + opmath_t upper = upper_.to(); + Tensor tmp_tensor = output.contiguous(); + scalar_t* output_data = tmp_tensor.mutable_data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + scalar_t* noise_data = noise.mutable_data_ptr(); + auto gen = at::get_generator_or_default(generator, detail::getDefaultCPUGenerator()); + std::lock_guard lock(gen->mutex_); + for (const auto i : c10::irange(input.numel())) { + if (input_data[i] <= 0) { + at::uniform_real_distribution uniform(lower, upper); + const opmath_t r = (opmath_t)uniform(gen); + output_data[i] = input_data[i] * r; + noise_data[i] = r; + } else { + noise_data[i] = 1; + output_data[i] = input_data[i]; + } + } + if (!output.is_contiguous()) { + output.copy_(tmp_tensor); + } +} + +Tensor& rrelu_with_noise_out_cpu(const Tensor& self, + Tensor& noise, + const Scalar& lower, + const Scalar& upper, + bool training, + std::optional generator, + Tensor& output) { + TORCH_CHECK(self.sym_sizes() == noise.sym_sizes(), "noise tensor shape must match self tensor shape. Got self.shape = ", self.sym_sizes(), " noise.shape = ", noise.sym_sizes()); + if (training) { + AT_DISPATCH_FLOATING_TYPES_AND(ScalarType::BFloat16, self.scalar_type(), "rrelu_with_noise_out_cpu", [&] { + _rrelu_with_noise_train(output, self.contiguous(), noise, lower, upper, generator); + }); + return output; + } else { + auto lower_tensor = scalar_to_tensor(lower); + auto upper_tensor = scalar_to_tensor(upper); + auto negative = (lower_tensor + upper_tensor) / 2; + Scalar negative_slope = negative.item(); + return at::leaky_relu_out(output, self, negative_slope); + } +} + +Tensor rrelu_with_noise_cpu( + const Tensor& self, + Tensor& noise, + const Scalar& lower, + const Scalar& upper, + bool training, + std::optional generator) { + auto output = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + return at::native::rrelu_with_noise_out_cpu( + self, noise, lower, upper, training, std::move(generator), output); +} + +Tensor& rrelu_with_noise_cpu_( + Tensor& self, + Tensor& noise, + const Scalar& lower, + const Scalar& upper, + bool training, + std::optional generator) { + return at::native::rrelu_with_noise_out_cpu( + self, noise, lower, upper, training, std::move(generator), self); +} + +Tensor rrelu_with_noise_backward( + const Tensor& grad_output, + const Tensor& self_or_result, + const Tensor& noise, + const Scalar& lower, + const Scalar& upper, + bool training, + bool is_result) { + if (training) { + return noise * grad_output; + } else { + auto l = lower.toDouble(); + auto u = upper.toDouble(); + auto mid = (l + u) / 2.; + return at::leaky_relu_backward(grad_output, self_or_result, mid, is_result); + } +} + +Tensor rrelu(const Tensor & self, const Scalar& lower, const Scalar& upper, bool training, std::optional generator) { + TORCH_CHECK(std::isfinite(lower.to()), "rrelu: lower bound must be finite, got ", lower.to()); + TORCH_CHECK(std::isfinite(upper.to()), "rrelu: upper bound must be finite, got ", upper.to()); + TORCH_CHECK(lower.to() <= upper.to(), "Lower bound should be less than or equal to the upper bound"); + auto noise = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + return at::rrelu_with_noise(self, noise, lower, upper, training, std::move(generator)); +} + +Tensor & rrelu_(Tensor & self, const Scalar& lower, const Scalar& upper, bool training, std::optional generator) { + TORCH_CHECK(lower.to() <= upper.to(), "Lower bound should be less than or equal to the upper bound"); + auto noise = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + return at::rrelu_with_noise_(self, noise, lower, upper, training, std::move(generator)); +} + +TORCH_IMPL_FUNC(threshold_out)(const Tensor& self, const Scalar& threshold, const Scalar& value, const Tensor& result) { + threshold_stub(device_type(), *this, threshold, value); +} + +TORCH_IMPL_FUNC(threshold_backward_out)(const Tensor& grad, const Tensor& self, const Scalar& threshold, const Tensor& gradInput) { + threshold_stub(device_type(), *this, threshold, 0); +} + +Tensor prelu(const Tensor& self, const Tensor& weight_) { + TORCH_INTERNAL_ASSERT(weight_.defined()); + auto self_dim = self.dim(); + TORCH_CHECK(self.scalar_type() == weight_.scalar_type(), + "prelu: Type promoting not supported. Got ", + self.scalar_type(), " and ", weight_.scalar_type()); + if (weight_.sym_numel() != 1) { + TORCH_CHECK(self_dim > 0, "Not allow zero-dim input tensor."); + + auto channel_size = self_dim > 1 ? self.sym_size(1) : 1; // channel_size default to 1 + TORCH_CHECK(channel_size == weight_.sym_numel(), + "Mismatch of parameter numbers and input channel size. Found parameter numbers = ", weight_.numel(), + " and channel size = ", channel_size, "."); + } + + TORCH_CHECK( + weight_.dim() <= 1, + "prelu: Expected `weight` to be a scalar or 1D tensor, but got: ndim = ", weight_.dim()); + // Adjust weight to broadcast over self and have weight.ndim == self.ndim + auto weight = weight_; + if (self_dim != weight.dim()) { + SymDimVector dim_w(self_dim, 1); + if (self_dim > 1) { + dim_w[1] = weight_.sym_numel(); + } + // This will always be a view in CPU/CUDA, but some backends + // like MKLDNN do not support views + weight = weight.reshape_symint(dim_w); + } + return at::_prelu_kernel(self, weight); +} + + +Tensor _prelu_kernel(const Tensor& self, const Tensor& weight) { + // Weight broadcasts over self and they have the same dtype + auto result = at::empty_like(self); + auto iter = TensorIteratorConfig() + .add_output(result) + .add_const_input(self) + .add_const_input(weight) + .build(); + prelu_stub(iter.device_type(), iter); + return result; +} + +std::tuple _prelu_kernel_backward(const Tensor& grad_out, const Tensor& self, const Tensor& weight) { + Tensor grad_self = at::empty({0}, self.options()); + Tensor grad_weight = at::empty({0}, weight.options()); + auto iter = TensorIteratorConfig() + .add_output(grad_self) + .add_output(grad_weight) + .add_const_input(self) + .add_const_input(weight) + .add_const_input(grad_out) + .build(); + prelu_backward_stub(iter.device_type(), iter); + return {grad_self, grad_weight}; +} + +Tensor infinitely_differentiable_gelu_backward( + const Tensor& grad, + const Tensor& self) { + constexpr double kAlpha = M_2_SQRTPI * M_SQRT1_2 * 0.5; + const auto result_dtype = at::result_type(grad, self); + const auto opmath_dtype = at::toOpMathType(result_dtype); + const Tensor grad_ = grad.to(opmath_dtype); + const Tensor self_ = self.to(opmath_dtype); + Tensor cdf = (1.0 + (self_ * M_SQRT1_2).erf_()).mul_(0.5); + Tensor pdf = (-0.5 * self_ * self_).exp_(); + return cdf.addcmul_(self_, pdf, kAlpha).mul_(grad_).to(result_dtype); +} + +std::tuple log_sigmoid_forward_cpu(const Tensor& input) { + auto result = at::empty_like(input, at::MemoryFormat::Contiguous); + auto buffer = at::empty_like(input, at::MemoryFormat::Contiguous); + log_sigmoid_cpu_stub(kCPU, result, buffer, input.contiguous()); + return std::make_tuple(std::move(result), std::move(buffer)); +} + +std::tuple log_sigmoid_forward_out_cpu(const Tensor& input, Tensor& result, Tensor& buffer) { + result.resize_as_(input); + buffer.resize_as_(input, at::MemoryFormat::Contiguous); + TORCH_CHECK(buffer.is_contiguous(), "Contiguous buffer required for log_sigmoid with out parameter"); + Tensor result_tmp = result.is_contiguous() ? result : at::empty_like(result, at::MemoryFormat::Contiguous); + log_sigmoid_cpu_stub(kCPU, result_tmp, buffer, input.contiguous()); + if (!result.is_contiguous()) { + result.copy_(result_tmp); + } + return std::forward_as_tuple(result, buffer); +} + +Tensor & log_sigmoid_out(const Tensor & self, Tensor & output) { + Tensor buffer = at::empty({0}, self.options()); + return std::get<0>(at::log_sigmoid_forward_out(output, buffer, self)); +} + +Tensor log_sigmoid(const Tensor & self) { + return std::get<0>(at::log_sigmoid_forward(self)); +} + +Tensor log_sigmoid_backward_cuda(const Tensor& grad_output, const Tensor& input, const Tensor& buffer) { + auto grad_input = at::empty_like(grad_output); + // NOTE: buffer is only used by CPU dispatch, we just ignore it here + auto iter = at::TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(grad_output) + .build(); + log_sigmoid_backward_stub(kCUDA, iter); + return iter.output(); +} + +Tensor log_sigmoid_backward_cpu(const Tensor& grad_output, const Tensor& input, const Tensor& buffer) { + auto grad_input = at::empty_like(grad_output); + auto iter = at::TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(buffer) + .add_const_input(grad_output) + .build(); + log_sigmoid_backward_stub(kCPU, iter); + return iter.output(); +} + +Tensor& log_sigmoid_backward_cuda_out(const Tensor& grad_output, const Tensor& input, + const Tensor& buffer, Tensor& grad_input) { + auto iter = TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(grad_output) + .build(); + log_sigmoid_backward_stub(kCUDA, iter); + return grad_input; +} + +Tensor& log_sigmoid_backward_cpu_out(const Tensor& grad_output, + const Tensor& input, + const Tensor& buffer, + Tensor& grad_input) { + auto iter = TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(buffer) + .add_const_input(grad_output) + .build(); + log_sigmoid_backward_stub(kCPU, iter); + return grad_input; +} + +DEFINE_DISPATCH(GeluKernel); +DEFINE_DISPATCH(GeluBackwardKernel); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Activation.h b/western_ai/usa/pytorch/aten/src/ATen/native/Activation.h new file mode 100644 index 0000000000000000000000000000000000000000..02cc5090f1dd0d033678c525445cff69c06b2ae5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Activation.h @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include + +namespace c10 { +class Scalar; +} + +namespace at { +struct TensorIterator; +struct TensorIteratorBase; +class TensorBase; +} + +namespace at::native { + +using structured_activation_fn = void (*)(TensorIteratorBase&); +using structured_activation_backward_fn = void (*)(TensorIteratorBase&); + +using activation_fn = void (*)(TensorIterator&); +using activation_backward_fn = void (*)(TensorIterator&); +using softplus_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&); +using softplus_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&); +using threshold_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&); +using hardtanh_backward_fn = void (*)(TensorIterator&, const c10::Scalar&, const c10::Scalar&); +using hardsigmoid_fn = void(*)(TensorIteratorBase&); +using hardsigmoid_backward_fn = void(*)(TensorIteratorBase&); +using hardswish_fn = void(*)(TensorIterator&); +using hardswish_backward_fn = void(*)(TensorIterator&); +using shrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&); +using softshrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&); +using shrink_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&); +using elu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&); +using elu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&, bool); +using leaky_relu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&); +using leaky_relu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&); +using log_sigmoid_cpu_fn = void (*)(TensorBase&, TensorBase&, const TensorBase&); +using gelu_fn = void (*)(TensorIteratorBase&, GeluType); +using gelu_backward_fn = void (*)(TensorIteratorBase&, GeluType); +using glu_jvp_fn = void (*)(TensorIteratorBase&); + +DECLARE_DISPATCH(elu_fn, elu_stub) +DECLARE_DISPATCH(elu_backward_fn, elu_backward_stub) +DECLARE_DISPATCH(softplus_fn, softplus_stub) +DECLARE_DISPATCH(softplus_backward_fn, softplus_backward_stub) +DECLARE_DISPATCH(log_sigmoid_cpu_fn, log_sigmoid_cpu_stub) +DECLARE_DISPATCH(activation_backward_fn, log_sigmoid_backward_stub) +DECLARE_DISPATCH(threshold_fn, threshold_stub) +DECLARE_DISPATCH(gelu_fn, GeluKernel) +DECLARE_DISPATCH(gelu_backward_fn, GeluBackwardKernel) +DECLARE_DISPATCH(hardtanh_backward_fn, hardtanh_backward_stub) +DECLARE_DISPATCH(hardsigmoid_fn, hardsigmoid_stub) +DECLARE_DISPATCH(hardsigmoid_backward_fn, hardsigmoid_backward_stub) +DECLARE_DISPATCH(hardswish_fn, hardswish_stub) +DECLARE_DISPATCH(hardswish_backward_fn, hardswish_backward_stub) +DECLARE_DISPATCH(shrink_fn, hardshrink_stub) +DECLARE_DISPATCH(softshrink_fn, softshrink_stub) +DECLARE_DISPATCH(shrink_backward_fn, shrink_backward_stub) +DECLARE_DISPATCH(leaky_relu_fn, leaky_relu_stub) +DECLARE_DISPATCH(leaky_relu_backward_fn, leaky_relu_backward_stub) +DECLARE_DISPATCH(structured_activation_fn, glu_stub) +DECLARE_DISPATCH(activation_backward_fn, glu_backward_stub) +DECLARE_DISPATCH(glu_jvp_fn, glu_jvp_stub) +DECLARE_DISPATCH(structured_activation_fn, silu_stub) +DECLARE_DISPATCH(structured_activation_backward_fn, silu_backward_stub) +DECLARE_DISPATCH(structured_activation_fn, mish_stub) +DECLARE_DISPATCH(activation_backward_fn, mish_backward_stub) +DECLARE_DISPATCH(activation_fn, prelu_stub) +DECLARE_DISPATCH(activation_backward_fn, prelu_backward_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveAveragePooling.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveAveragePooling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e3e9b6b274521f79e3096a91cc2ae0650dfb38d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveAveragePooling.cpp @@ -0,0 +1,151 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + + +namespace at::native { + +namespace { + + void adaptive_avg_pool2d_out_cpu_template( + at::Tensor& output, + at::Tensor const& input, + IntArrayRef output_size) + { + TORCH_CHECK(output_size.size() == 2, "adaptive_avg_pool2d: output_size must be 2"); + int64_t ndim = input.dim(); + TORCH_CHECK((ndim == 3 || ndim == 4), + "adaptive_avg_pool2d(): Expected 3D or 4D tensor, but got ", input.sizes()); + for (const auto i : {-2, -1}) { + TORCH_CHECK(input.size(i) > 0, + "adaptive_avg_pool2d(): Expected input to have non-zero size for non-batch dimensions, " + "but input has sizes ", input.sizes(), " with dimension ", i + ndim, " being " + "empty"); + } + + TORCH_CHECK(input.dtype() == output.dtype(), + "expected dtype ", input.dtype(), " for `output` but got dtype ", output.dtype()); + + int64_t channels = input.size(-3); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + if (ndim == 3) { + output.resize_({channels, output_height, output_width}); + } else { + int64_t nbatch = input.size(0); + output.resize_({nbatch, channels, output_height, output_width}, input.suggest_memory_format()); + } + + if (output.numel() == 0) { + return; + } + + adaptive_avg_pool2d_kernel(kCPU, output, input, output_size); + } + + Tensor& adaptive_avg_pool2d_backward_out_cpu_template( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input) + { + adaptive_pool_empty_output_check(grad_output, "adaptive_avg_pool2d_backward"); + int64_t ndim = grad_output.dim(); + TORCH_CHECK(input.dim() == ndim, + __func__, ": Expected dimensions ", input.dim(), " for `grad_output` but got dimensions ", ndim); + TORCH_CHECK((ndim == 3 || ndim == 4), + __func__, ": Expected 3D or 4D tensor, but got ", input.sizes()); + TORCH_CHECK(input.dtype() == grad_output.dtype(), + __func__, ": Expected dtype ", input.dtype(), " for `grad_output` but got dtype ", grad_output.dtype()); + TORCH_CHECK(input.dtype() == grad_input.dtype(), + __func__, ": Expected dtype ", input.dtype(), " for `grad_input` but got dtype ", grad_input.dtype()); + + grad_input.resize_(input.sizes(), input.suggest_memory_format()); + grad_input.zero_(); + + adaptive_avg_pool2d_backward_kernel(kCPU, grad_input, grad_output); + return grad_input; + } + +} // namespace + + Tensor& adaptive_avg_pool2d_out_cpu(const Tensor& input, + IntArrayRef output_size, + Tensor& output) + { + adaptive_avg_pool2d_out_cpu_template( + output, input, output_size); + return output; + } + + Tensor adaptive_avg_pool2d_cpu( + at::Tensor const& input, + IntArrayRef output_size) + { + auto output = at::empty({0}, input.options()); + adaptive_avg_pool2d_out_cpu_template( + output, input, output_size); + return output; + } + + Tensor adaptive_avg_pool2d_symint(at::Tensor const& input, SymIntArrayRef output_size) { + TORCH_CHECK(output_size.size() == 2, "adaptive_avg_pool2d: output_size must be 2"); + TORCH_CHECK( + (output_size[0] >= 0 && output_size[1] >= 0), + "adaptive_avg_pool2d: elements of output_size must be greater than or equal to 0 ", + "but received {", output_size[0], ", ", output_size[1], "}"); + + if (input.is_mkldnn()) { + return at::mkldnn_adaptive_avg_pool2d(input, C10_AS_INTARRAYREF_SLOW(output_size)); + } + + if (!input.is_quantized() && output_size[0] == 1 && output_size[1] == 1) { + // in this case, adaptive pooling is just computing mean over hw + // dimensions, which can be done more efficiently + #if defined(C10_MOBILE) && defined(USE_XNNPACK) + if (xnnpack::use_global_average_pool(input)) { + return xnnpack::global_average_pool(input); + } + #endif + + Tensor out = input.mean({-1, -2}, /* keepdim = */ true); + if (input.suggest_memory_format() == at::MemoryFormat::ChannelsLast) { + // assert ndim == 4, since ndim = 3 doesn't give channels_last + const auto n = input.sym_size(0); + const auto c = input.sym_size(1); + out.as_strided__symint({n, c, 1, 1}, {c, 1, c, c}); + } + return out; + } else { + return _adaptive_avg_pool2d_symint(input, output_size); + } + } + + Tensor adaptive_avg_pool2d_backward_cpu( + const Tensor& grad_output, + const Tensor& input) + { + auto grad_input = at::empty({0}, input.options()); + adaptive_avg_pool2d_backward_out_cpu_template( + grad_input, grad_output, input); + return grad_input; + } + +DEFINE_DISPATCH(adaptive_avg_pool2d_kernel); +DEFINE_DISPATCH(adaptive_avg_pool2d_backward_kernel); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveAveragePooling3d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveAveragePooling3d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c9d72ffd5711cfdab2c6d77facb885ad59367a2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveAveragePooling3d.cpp @@ -0,0 +1,349 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +template +void adaptive_avg_pool3d_out_frame( + const scalar_t* input_p, + scalar_t* output_p, + int64_t sizeD, + int64_t isizeT, + int64_t isizeH, + int64_t isizeW, + int64_t osizeT, + int64_t osizeH, + int64_t osizeW, + int64_t istrideD, + int64_t istrideT, + int64_t istrideH, + int64_t istrideW) { + at::parallel_for(0, sizeD, 1, [&](int64_t start, int64_t end) { + for (const auto d : c10::irange(start, end)) { + /* loop over output */ + for (const auto ot : c10::irange(osizeT)) { + auto istartT = start_index(ot, osizeT, isizeT); + auto iendT = end_index(ot, osizeT, isizeT); + auto kT = iendT - istartT; + + for (const auto oh : c10::irange(osizeH)) { + auto istartH = start_index(oh, osizeH, isizeH); + auto iendH = end_index(oh, osizeH, isizeH); + auto kH = iendH - istartH; + + for (const auto ow : c10::irange(osizeW)) { + auto istartW = start_index(ow, osizeW, isizeW); + auto iendW = end_index(ow, osizeW, isizeW); + auto kW = iendW - istartW; + + /* local pointers */ + const scalar_t* ip = input_p + d * istrideD + istartT * istrideT + + istartH * istrideH + istartW * istrideW; + scalar_t* op = output_p + d * osizeT * osizeH * osizeW + + ot * osizeH * osizeW + oh * osizeW + ow; + + /* compute local average: */ + scalar_t sum = 0; + for (const auto it : c10::irange(kT)) { + for (const auto ih : c10::irange(kH)) { + for (const auto iw : c10::irange(kW)) { + scalar_t val = + *(ip + it * istrideT + ih * istrideH + iw * istrideW); + sum += val; + } + } + } + + /* set output to local average */ + *op = sum / kT / kH / kW; + } + } + } + } + }); +} + +void adaptive_avg_pool3d_out_cpu_template( + Tensor& output, + Tensor const& input, + IntArrayRef output_size) { + TORCH_CHECK(output_size.size() == 3, "adaptive_avg_pool3d: output_size must be 3"); + + for (const auto i : c10::irange(1, input.ndimension())) { + TORCH_CHECK( + input.size(i) > 0, + "adaptive_avg_pool3d(): Expected input to have non-zero size for non-batch dimensions, " + "but input has sizes ", + input.sizes(), + " with dimension ", + i, + " being " + "empty"); + } + + TORCH_CHECK( + (input.ndimension() == 4 || input.ndimension() == 5), + "adaptive_avg_pool3d(): Expected 4D or 5D tensor, but got ", + input.sizes()); + TORCH_CHECK(input.dtype() == output.dtype(), + "expected dtype ", input.dtype(), " for `output` but got dtype ", output.dtype()); + + /* sizes */ + int64_t sizeD = input.size(-4); + int64_t isizeT = input.size(-3); + int64_t isizeH = input.size(-2); + int64_t isizeW = input.size(-1); + /* strides */ + int64_t istrideD = input.stride(-4); + int64_t istrideT = input.stride(-3); + int64_t istrideH = input.stride(-2); + int64_t istrideW = input.stride(-1); + /* output sizes */ + auto osizeT = output_size[0]; + auto osizeH = output_size[1]; + auto osizeW = output_size[2]; + + if (input.ndimension() == 4) { + output.resize_({sizeD, osizeT, osizeH, osizeW}); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_cpu", [&] { + auto input_data = input.const_data_ptr(); + auto output_data = output.mutable_data_ptr(); + adaptive_avg_pool3d_out_frame( + input_data, + output_data, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW, + istrideD, + istrideT, + istrideH, + istrideW); + }); + } else { + output.resize_({input.size(-5), sizeD, osizeT, osizeH, osizeW}); + int64_t n = input.size(0); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_cpu", [&] { + auto input_data = input.const_data_ptr(); + auto output_data = output.mutable_data_ptr(); + at::parallel_for(0, n, 1, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + adaptive_avg_pool3d_out_frame( + input_data + b * input.stride(0), + output_data + b * sizeD * osizeT * osizeH * osizeW, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW, + istrideD, + istrideT, + istrideH, + istrideW); + } + }); + }); + } +} + +template +void adaptive_avg_pool3d_backward_out_frame( + scalar_t* gradInput_p, + const scalar_t* gradOutput_p, + int64_t sizeD, + int64_t isizeT, + int64_t isizeH, + int64_t isizeW, + int64_t osizeT, + int64_t osizeH, + int64_t osizeW) { + at::parallel_for(0, sizeD, 1, [&](int64_t start, int64_t end) { + for (const auto d : c10::irange(start, end)) { + scalar_t* gradInput_p_d = gradInput_p + d * isizeT * isizeW * isizeH; + const scalar_t* gradOutput_p_d = gradOutput_p + d * osizeT * osizeW * osizeH; + + /* calculate average */ + for (const auto ot : c10::irange(osizeT)) { + auto istartT = start_index(ot, osizeT, isizeT); + auto iendT = end_index(ot, osizeT, isizeT); + auto kT = iendT - istartT; + + for (const auto oh : c10::irange(osizeH)) { + auto istartH = start_index(oh, osizeH, isizeH); + auto iendH = end_index(oh, osizeH, isizeH); + auto kH = iendH - istartH; + + for (const auto ow : c10::irange(osizeW)) { + auto istartW = start_index(ow, osizeW, isizeW); + auto iendW = end_index(ow, osizeW, isizeW); + auto kW = iendW - istartW; + + scalar_t grad_delta = + gradOutput_p_d[ot * osizeH * osizeW + oh * osizeW + ow] / kT / + kH / kW; + + for (const auto it : c10::irange(istartT, iendT)) { + for (const auto ih : c10::irange(istartH, iendH)) { + for (const auto iw : c10::irange(istartW, iendW)) { + /* update gradient */ + gradInput_p_d[it * isizeH * isizeW + ih * isizeW + iw] += + grad_delta; + } + } + } + } + } + } + } + }); +} + +Tensor& adaptive_avg_pool3d_backward_out_cpu_template( + Tensor& gradInput, + const Tensor& gradOutput_, + const Tensor& input) { + /* get contiguous gradOutput */ + auto gradOutput = gradOutput_.contiguous(); + + adaptive_pool_empty_output_check(gradOutput_, "adaptive_avg_pool3d_backward"); + TORCH_CHECK(input.dim() == gradOutput_.dim(), + __func__, ": Expected dimensions ", input.dim(), " for `gradOutput_` but got dimensions ", gradOutput_.dim()); + + /* sizes */ + int64_t sizeD = input.size(-4); + int64_t isizeT = input.size(-3); + int64_t isizeH = input.size(-2); + int64_t isizeW = input.size(-1); + int64_t osizeT = gradOutput.size(-3); + int64_t osizeH = gradOutput.size(-2); + int64_t osizeW = gradOutput.size(-1); + + /* backprop */ + if (input.ndimension() == 4) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_backward_cpu", [&] { + /* get raw pointers */ + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput.const_data_ptr(); + + adaptive_avg_pool3d_backward_out_frame( + gradInput_data, + gradOutput_data, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW); + }); + } else { + int64_t n = input.size(0); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_backward_cpu", [&] { + /* get raw pointers */ + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput.const_data_ptr(); + at::parallel_for(0, n, 1, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + adaptive_avg_pool3d_backward_out_frame( + gradInput_data + b * sizeD * isizeT * isizeH * isizeW, + gradOutput_data + b * sizeD * osizeT * osizeH * osizeW, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW); + } + }); + }); + } + return gradInput; +} + +} // namespace + +Tensor& adaptive_avg_pool3d_out_cpu(const Tensor& input, + IntArrayRef output_size, + Tensor& output) { + adaptive_avg_pool3d_out_cpu_template(output, input, output_size); + return output; +} + +Tensor adaptive_avg_pool3d_cpu(Tensor const& input, IntArrayRef output_size) { + auto output = at::empty({0}, input.options()); + adaptive_avg_pool3d_out_cpu_template(output, input, output_size); + return output; +} + +Tensor adaptive_avg_pool3d_symint(Tensor const& input, SymIntArrayRef output_size) { + TORCH_CHECK(output_size.size() == 3, "adaptive_avg_pool3d: output_size must be 3"); + TORCH_CHECK( + (output_size[0] >= 0 && output_size[1] >= 0 && output_size[2] >= 0), + "adaptive_avg_pool3d: elements of output_size must be greater than or equal to 0 ", + "but received {", output_size[0], ", ", output_size[1], ",", output_size[2], "}"); + + if (output_size[0] == 1 && output_size[1] == 1 && output_size[2] == 1) { + // in this case, adaptive pooling is just computing mean over hw + // dimensions, which can be done more efficiently + Tensor out = input.mean({-1, -2, -3}, /* keepdim = */ true); + if (input.suggest_memory_format() == at::MemoryFormat::ChannelsLast3d) { + // assert ndim == 5, since ndim = 4 doesn't give channels_last + const auto n = input.sym_size(0); + const auto c = input.sym_size(1); + out.as_strided__symint({n, c, 1, 1, 1}, {c, 1, c, c, c}); + } + return out; + } else { + return _adaptive_avg_pool3d_symint(input, output_size); + } +} + +Tensor& adaptive_avg_pool3d_backward_out_cpu(const Tensor& gradOutput_, + const Tensor& input, + Tensor& gradInput) { + gradInput.resize_as_(input).zero_(); + adaptive_avg_pool3d_backward_out_cpu_template(gradInput, gradOutput_, input); + return gradInput; +} + +Tensor adaptive_avg_pool3d_backward_cpu(const Tensor& gradOutput_, + const Tensor& input) { + auto gradInput = at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + adaptive_avg_pool3d_backward_out_cpu_template(gradInput, gradOutput_, input); + return gradInput; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveMaxPooling2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveMaxPooling2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..544f2821493d7a77fdb491438013dbef764ee9e5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveMaxPooling2d.cpp @@ -0,0 +1,91 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::meta { +TORCH_META_FUNC(adaptive_max_pool2d) (const Tensor& input, IntArrayRef output_size) { + int ndim = input.ndimension(); + TORCH_CHECK(ndim == 3 || ndim == 4, + "adaptive_max_pool2d(): Expected 3D or 4D tensor, but got: ", + input.sizes()); + for (const auto i : c10::irange(1, ndim)) { + TORCH_CHECK(input.size(i) > 0, + "adaptive_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, " + "but input has sizes ", input.sizes(), " with dimension ", i, + " being empty"); + } + + TORCH_CHECK(output_size.size() == 2, + "adaptive_max_pool2d(): internal error: output_size.size() must be 2"); + + int dimH = 1; + int64_t sizeB = 1; + int64_t sizeD = 0; + + if (input.ndimension() == 4) { + sizeB = input.size(0); + dimH++; + } + + sizeD = input.size(dimH - 1); + + int64_t osizeH = output_size[0]; + int64_t osizeW = output_size[1]; + + /* resize output */ + if (input.ndimension() == 3) { + set_output_raw_strided(0, {sizeD, osizeH, osizeW}, {}, input.options()); + /* indices will contain i,j locations for each output point */ + set_output_raw_strided(1, {sizeD, osizeH, osizeW}, {}, input.options().dtype(kLong)); + } else { + set_output_raw_strided(0, {sizeB, sizeD, osizeH, osizeW}, {}, input.options().memory_format(input.suggest_memory_format())); + /* indices will contain i,j locations for each output point */ + set_output_raw_strided(1, {sizeB, sizeD, osizeH, osizeW}, {}, input.options().memory_format(input.suggest_memory_format()).dtype(kLong)); + } +} + +TORCH_META_FUNC(adaptive_max_pool2d_backward) +(const Tensor& grad_output, const Tensor& input, const Tensor& indices) { + int64_t ndim = grad_output.ndimension(); + TORCH_CHECK(ndim == 3 || ndim == 4, + "adaptive_max_pooling2d_backward(): Expected 3D or 4D grad_output, but got: ", grad_output.sizes()); + + at::native::adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool2d_backward"); + + TORCH_CHECK(input.ndimension() == indices.ndimension(), + "expected dimensions ", input.ndimension(), " for `indices` but got dimensions ", indices.ndimension()); + TORCH_CHECK(input.dtype() == grad_output.dtype(), + "expected dtype ", input.dtype(), " for `grad_output` but got dtype ", grad_output.dtype()); + TORCH_CHECK(indices.sizes() == grad_output.sizes(), + "expected sizes ", indices.sizes(), " for `grad_output` but got sizes ", grad_output.sizes()); + + set_output_raw_strided(0, input.sizes(), {}, input.options().memory_format(input.suggest_memory_format())); +} +} // namespace at::meta + +namespace at::native { + +TORCH_IMPL_FUNC(adaptive_max_pool2d_out_cpu) +(const Tensor& input, IntArrayRef output_size, const Tensor& output, const Tensor& indices) { + adaptive_max_pool2d_kernel(kCPU, output, indices, input, output_size); +} + +TORCH_IMPL_FUNC(adaptive_max_pool2d_backward_out_cpu) +(const Tensor& grad_output, const Tensor& input, const Tensor& indices, const Tensor& grad_input) { + grad_input.zero_(); + adaptive_max_pool2d_backward_kernel(kCPU, grad_input, grad_output, indices); + } + +DEFINE_DISPATCH(adaptive_max_pool2d_kernel); +DEFINE_DISPATCH(adaptive_max_pool2d_backward_kernel); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveMaxPooling3d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveMaxPooling3d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0f1988782723b09b15edc1d5d1ae2f737cfd3f5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptiveMaxPooling3d.cpp @@ -0,0 +1,446 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at::meta { +TORCH_META_FUNC(adaptive_max_pool3d) (const Tensor& input, IntArrayRef output_size) { + auto ndim = input.ndimension(); + TORCH_CHECK( + ndim == 4 || ndim == 5, + "adaptive_max_pool3d(): Expected 4D or 5D tensor, but got: ", input.sizes()); + for (const auto i : c10::irange(1, ndim)) { + TORCH_CHECK( + input.size(i) > 0, + "adaptive_max_pool3d(): Expected input to have non-zero size for non-batch dimensions, " + "but input has sizes ", + input.sizes(), + " with dimension ", + i, + " being " + "empty"); + } + + TORCH_CHECK( + output_size.size() == 3, + "adaptive_max_pool3d(): internal error: output_size.size() must be 3"); + + int dimD = 0; + int64_t sizeB = 1; + int64_t sizeD = 0; + + if (ndim == 5) { + sizeB = input.size(0); + dimD++; + } + + /* sizes */ + sizeD = input.size(dimD); + + int64_t osizeT = output_size[0]; + int64_t osizeH = output_size[1]; + int64_t osizeW = output_size[2]; + + /* resize output */ + if (ndim == 4) { + set_output_raw_strided(0, {sizeD, osizeT, osizeH, osizeW}, {}, input.options()); + /* indices will contain max input locations for each output point */ + set_output_raw_strided(1, {sizeD, osizeT, osizeH, osizeW}, {}, input.options().dtype(kLong)); + } else { + set_output_raw_strided(0, {sizeB, sizeD, osizeT, osizeH, osizeW}, {}, input.options()); + /* indices will contain max input locations for each output point */ + set_output_raw_strided(1, {sizeB, sizeD, osizeT, osizeH, osizeW}, {}, input.options().dtype(kLong)); + } +} + +TORCH_META_FUNC(adaptive_max_pool3d_backward) +(const Tensor& gradOutput, const Tensor& input, const Tensor& indices) { + int64_t ndim = gradOutput.ndimension(); + TORCH_CHECK(ndim == 4 || ndim == 5, + "adaptive_max_pool3d_backward(): Expected 4D or 5D gradOutput, but got: ", gradOutput.sizes()); + + at::native::adaptive_pool_empty_output_check(gradOutput, "adaptive_max_pool3d_backward"); + + TORCH_CHECK(input.ndimension() == indices.ndimension(), + "expected dimensions ", input.ndimension(), " for `indices` but got dimensions ", indices.ndimension()); + TORCH_CHECK(input.dtype() == gradOutput.dtype(), + "expected dtype ", input.dtype(), " for `gradOutput` but got dtype ", gradOutput.dtype()); + TORCH_CHECK(indices.sizes() == gradOutput.sizes(), + "expected sizes ", indices.sizes(), " for `gradOutput` but got sizes ", gradOutput.sizes()); + + set_output_raw_strided(0, input.sizes(), {}, input.options()); +} +} // namespace meta + +namespace at::native { + +namespace { + +// #define START_IND(a,b,c) a * c / b +// #define END_IND(a,b,c) (a + 1) * c / b + ((a + 1) * c % b > 0)?1:0 + +// 5d tensor B x D x T x H x W + +template +void adaptive_max_pool3d_single_out_frame( + const scalar_t *input_p, + scalar_t *output_p, + int64_t *ind_p, + int64_t sizeD, + int64_t isizeT, + int64_t isizeH, + int64_t isizeW, + int64_t osizeT, + int64_t osizeH, + int64_t osizeW, + int64_t istrideD, + int64_t istrideT, + int64_t istrideH, + int64_t istrideW) +{ + at::parallel_for(0, sizeD, 0, [&](int64_t start, int64_t end) { + for (const auto d : c10::irange(start, end)) { + /* loop over output */ + int64_t ot = 0, oh = 0, ow = 0; + for(ot = 0; ot < osizeT; ot++) + { + int64_t istartT = start_index(ot, osizeT, isizeT); + int64_t iendT = end_index(ot, osizeT, isizeT); + int64_t kT = iendT - istartT; + + for(oh = 0; oh < osizeH; oh++) + { + int64_t istartH = start_index(oh, osizeH, isizeH); + int64_t iendH = end_index(oh, osizeH, isizeH); + int64_t kH = iendH - istartH; + + for(ow = 0; ow < osizeW; ow++) + { + + int64_t istartW = start_index(ow, osizeW, isizeW); + int64_t iendW = end_index(ow, osizeW, isizeW); + int64_t kW = iendW - istartW; + + /* local pointers */ + const scalar_t *ip = input_p + d*istrideD + istartT *istrideT + istartH*istrideH + istartW*istrideW; + scalar_t *op = output_p + d*osizeT*osizeH*osizeW + ot*osizeH*osizeW + oh*osizeW + ow; + int64_t *indp = ind_p + d*osizeT*osizeH*osizeW + ot*osizeH*osizeW + oh*osizeW + ow; + + /* compute local max: */ + int64_t it = 0, ih = 0, iw = 0; + int64_t maxindex = (it+istartT)*isizeH*isizeW + (ih+istartH)*isizeW + (iw+istartW); + scalar_t maxval = -std::numeric_limits::infinity(); + for(it = 0; it < kT; it++) + { + for(ih = 0; ih < kH; ih++) + { + for(iw = 0; iw < kW; iw++) + { + scalar_t val = *(ip + it*istrideT + ih*istrideH + iw*istrideW); + if ((val > maxval) || std::isnan(val)) + { + maxval = val; + maxindex = (it+istartT)*isizeH*isizeW + (ih+istartH)*isizeW + (iw+istartW); + } + } + } + } + + /* set output to local max */ + *op = maxval; + + /* store location of max */ + *indp = maxindex; + } + } + } + } + }); +} + +template +void adaptive_max_pool3d_out_frame( + const scalar_t *input_data, + scalar_t *output_data, + int64_t *indices_data, + int64_t sizeB, + int64_t sizeD, + int64_t isizeT, + int64_t isizeH, + int64_t isizeW, + int64_t osizeT, + int64_t osizeH, + int64_t osizeW, + int64_t istrideB, + int64_t istrideD, + int64_t istrideT, + int64_t istrideH, + int64_t istrideW) +{ + at::parallel_for(0, sizeB, 0, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + adaptive_max_pool3d_single_out_frame(input_data+b*istrideB, output_data+b*sizeD*osizeT*osizeH*osizeW, + indices_data+b*sizeD*osizeT*osizeH*osizeW, + sizeD, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW, + istrideD, istrideT, + istrideH, istrideW); + } + }); +} + +template +void adaptive_max_pool3d_backward_single_out_frame( + scalar_t *gradInput_p, + const scalar_t *gradOutput_p, + const int64_t *ind_p, + int64_t sizeD, + int64_t isizeT, + int64_t isizeH, + int64_t isizeW, + int64_t osizeT, + int64_t osizeH, + int64_t osizeW) +{ + at::parallel_for(0, sizeD, 0, [&](int64_t start, int64_t end) { + for (const auto d : c10::irange(start, end)) { + scalar_t *gradInput_p_d = gradInput_p + d*isizeT*isizeH*isizeW; + const scalar_t *gradOutput_p_d = gradOutput_p + d*osizeT*osizeH*osizeW; + const int64_t *ind_p_d = ind_p + d*osizeT*osizeH*osizeW; + + /* calculate max points */ + int64_t ot = 0, oh = 0, ow = 0; + for(ot = 0; ot < osizeT; ot++) + { + for(oh = 0; oh < osizeH; oh++) + { + for(ow = 0; ow < osizeW; ow++) + { + /* retrieve position of max */ + int64_t maxp = ind_p_d[ot*osizeH*osizeW + oh*osizeW + ow]; + + /* update gradient */ + gradInput_p_d[maxp] += gradOutput_p_d[ot*osizeH*osizeW + oh*osizeW + ow]; + } + } + } + } + }); +} + +template +void adaptive_max_pool3d_backward_out_frame( + scalar_t *gradInput_data, + const scalar_t *gradOutput_data, + const int64_t *indices_data, + int64_t sizeB, + int64_t sizeD, + int64_t isizeT, + int64_t isizeH, + int64_t isizeW, + int64_t osizeT, + int64_t osizeH, + int64_t osizeW) +{ + at::parallel_for(0, sizeB, 0, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + adaptive_max_pool3d_backward_single_out_frame(gradInput_data+b*sizeD*isizeT*isizeH*isizeW, gradOutput_data+b*sizeD*osizeT*osizeH*osizeW, + indices_data+b*sizeD*osizeT*osizeH*osizeW, + sizeD, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW); + } + }); +} +} // namespace + +TORCH_IMPL_FUNC(adaptive_max_pool3d_out_cpu) +(const Tensor& input, IntArrayRef output_size, const Tensor& output, const Tensor& indices) { + int dimD = 0; + int dimT = 1; + int dimH = 2; + int dimW = 3; + int64_t sizeB = 1; + int64_t sizeD = 0; + int64_t isizeT = 0; + int64_t isizeH = 0; + int64_t isizeW = 0; + + int64_t istrideB = 0; + int64_t istrideD = 0; + int64_t istrideT = 0; + int64_t istrideH = 0; + int64_t istrideW = 0; + + if (input.ndimension() == 5) { + istrideB = input.stride(0); + sizeB = input.size(0); + dimD++; + dimT++; + dimH++; + dimW++; + } + + /* sizes */ + sizeD = input.size(dimD); + isizeT = input.size(dimT); + isizeH = input.size(dimH); + isizeW = input.size(dimW); + /* strides */ + istrideD = input.stride(dimD); + istrideT = input.stride(dimT); + istrideH = input.stride(dimH); + istrideW = input.stride(dimW); + + int64_t osizeT = output_size[0]; + int64_t osizeH = output_size[1]; + int64_t osizeW = output_size[2]; + + if (input.ndimension() == 4) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, + input.scalar_type(), "adaptive_max_pool3d_cpu", [&] { + auto input_data = input.const_data_ptr(); + auto output_data = output.mutable_data_ptr(); + auto indices_data = indices.mutable_data_ptr(); + + adaptive_max_pool3d_single_out_frame( + input_data, + output_data, + indices_data, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW, + istrideD, + istrideT, + istrideH, + istrideW); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, + input.scalar_type(), "adaptive_max_pool3d_cpu", [&] { + auto input_data = input.const_data_ptr(); + auto output_data = output.mutable_data_ptr(); + auto indices_data = indices.mutable_data_ptr(); + + adaptive_max_pool3d_out_frame( + input_data, + output_data, + indices_data, + sizeB, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW, + istrideB, + istrideD, + istrideT, + istrideH, + istrideW); + }); + } +} + +TORCH_IMPL_FUNC(adaptive_max_pool3d_backward_out_cpu) +(const Tensor& gradOutput, + const Tensor& input, + const Tensor& indices, + const Tensor& gradInput) { + int dimD = 0; + int dimT = 1; + int dimH = 2; + int dimW = 3; + int64_t sizeB = 1; + int64_t sizeD = 0; + int64_t isizeT = 0; + int64_t isizeH = 0; + int64_t isizeW = 0; + int64_t osizeT = 0; + int64_t osizeH = 0; + int64_t osizeW = 0; + + /* get contiguous gradOutput */ + auto gradOutput_ = gradOutput.contiguous(); + + /* resize */ + gradInput.zero_(); + + if (input.ndimension() == 5) { + sizeB = input.size(0); + dimD++; + dimT++; + dimH++; + dimW++; + } + + /* sizes */ + sizeD = input.size(dimD); + isizeT = input.size(dimT); + isizeH = input.size(dimH); + isizeW = input.size(dimW); + osizeT = gradOutput_.size(dimT); + osizeH = gradOutput_.size(dimH); + osizeW = gradOutput_.size(dimW); + + /* backprop */ + if (input.ndimension() == 4) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, + input.scalar_type(), "adaptive_max_pool3d_backward", [&] { + /* get raw pointers */ + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput_.const_data_ptr(); + const int64_t* indices_data = indices.const_data_ptr(); + + adaptive_max_pool3d_backward_single_out_frame( + gradInput_data, + gradOutput_data, + indices_data, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, + input.scalar_type(), "adaptive_max_pool3d_backward", [&] { + /* get raw pointers */ + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput_.const_data_ptr(); + const int64_t* indices_data = indices.const_data_ptr(); + + adaptive_max_pool3d_backward_out_frame( + gradInput_data, + gradOutput_data, + indices_data, + sizeB, + sizeD, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW); + }); + } +} +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AdaptivePooling.h b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptivePooling.h new file mode 100644 index 0000000000000000000000000000000000000000..0fce2aa38779471b37137f9d7906dd3a0ceea361 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AdaptivePooling.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace at::native { + +using adaptive_avg_pooling2d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size); +using adaptive_avg_pooling2d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output); +DECLARE_DISPATCH(adaptive_avg_pooling2d_fn, adaptive_avg_pool2d_kernel) +DECLARE_DISPATCH(adaptive_avg_pooling2d_backward_fn, adaptive_avg_pool2d_backward_kernel) + +using adaptive_max_pooling2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size); +using adaptive_max_pooling2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices); +DECLARE_DISPATCH(adaptive_max_pooling2d_fn, adaptive_max_pool2d_kernel) +DECLARE_DISPATCH(adaptive_max_pooling2d_backward_fn, adaptive_max_pool2d_backward_kernel) + +using adaptive_avg_pooling3d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size); +using adaptive_avg_pooling3d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output); +DECLARE_DISPATCH(adaptive_avg_pooling3d_fn, adaptive_avg_pool3d_kernel) +DECLARE_DISPATCH(adaptive_avg_pooling3d_backward_fn, adaptive_avg_pool3d_backward_kernel) + +using adaptive_max_pooling3d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size); +using adaptive_max_pooling3d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices); +DECLARE_DISPATCH(adaptive_max_pooling3d_fn, adaptive_max_pool3d_kernel) +DECLARE_DISPATCH(adaptive_max_pooling3d_backward_fn, adaptive_max_pool3d_backward_kernel) + +inline int64_t start_index(int64_t a, int64_t b, int64_t c) { + return (a / b) * c + ((a % b) * c) / b; +} + +inline int64_t end_index(int64_t a, int64_t b, int64_t c) { + return 1 + ((a + 1) * c - 1) / b; +} + +inline void adaptive_pool_empty_output_check(const Tensor& gradOutput_, const char* arg_name) { + int64_t ndim = gradOutput_.ndimension(); + for (const auto i : c10::irange(1, ndim)) { + TORCH_CHECK(gradOutput_.size(i) > 0, + arg_name, "(): Expected grad_output to have non-zero size for non-batch dimensions, " + "but grad_output has sizes ", gradOutput_.sizes(), " with dimension ", i, + " being empty"); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AffineGridGenerator.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AffineGridGenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69ac9cdff41890523a5830996cb4e922f9ef1456 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AffineGridGenerator.cpp @@ -0,0 +1,146 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +static at::Tensor linspace_from_neg_one(const Tensor& grid, int64_t num_steps, + bool align_corners) { + if (num_steps <= 1) { + return at::tensor(0, grid.options()); + } + auto range = at::linspace(-1, 1, num_steps, grid.options()); + if (!align_corners) { + range = range * (num_steps - 1) / num_steps; + } + return range; +} + +static Tensor make_base_grid_4D( + const Tensor& theta, + int64_t N, + int64_t C, + int64_t H, + int64_t W, + bool align_corners) { + auto base_grid = at::empty({N, H, W, 3}, theta.options()); + + base_grid.select(-1, 0).copy_(linspace_from_neg_one(theta, W, align_corners)); + base_grid.select(-1, 1).copy_(linspace_from_neg_one(theta, H, align_corners).unsqueeze_(-1)); + base_grid.select(-1, 2).fill_(1); + + return base_grid; +} + +static Tensor make_base_grid_5D( + const Tensor& theta, + int64_t N, + int64_t C, + int64_t D, + int64_t H, + int64_t W, + bool align_corners) { + auto base_grid = at::empty({N, D, H, W, 4}, theta.options()); + + base_grid.select(-1, 0).copy_(linspace_from_neg_one(theta, W, align_corners)); + base_grid.select(-1, 1).copy_(linspace_from_neg_one(theta, H, align_corners).unsqueeze_(-1)); + base_grid.select(-1, 2).copy_(linspace_from_neg_one(theta, D, align_corners).unsqueeze_(-1).unsqueeze_(-1)); + base_grid.select(-1, 3).fill_(1); + + return base_grid; +} + +static Tensor affine_grid_generator_4D( + const Tensor& theta, + int64_t N, + int64_t C, + int64_t H, + int64_t W, + bool align_corners) { + Tensor base_grid = make_base_grid_4D(theta, N, C, H, W, align_corners); + auto grid = base_grid.view({N, H * W, 3}).bmm(theta.transpose(1, 2)); + return grid.view({N, H, W, 2}); +} + +static Tensor affine_grid_generator_5D( + const Tensor& theta, + int64_t N, + int64_t C, + int64_t D, + int64_t H, + int64_t W, + bool align_corners) { + Tensor base_grid = make_base_grid_5D(theta, N, C, D, H, W, align_corners); + auto grid = base_grid.view({N, D * H * W, 4}).bmm(theta.transpose(1, 2)); + return grid.view({N, D, H, W, 3}); +} + +Tensor affine_grid_generator(const Tensor& theta, IntArrayRef size, bool align_corners) { + TORCH_CHECK( + size.size() == 4 || size.size() == 5, + "AffineGridGenerator needs 4d (spatial) or 5d (volumetric) inputs."); + if (size.size() == 4) { + return affine_grid_generator_4D( + theta, size[0], size[1], size[2], size[3], align_corners); + } else { + return affine_grid_generator_5D( + theta, size[0], size[1], size[2], size[3], size[4], align_corners); + } +} + +static Tensor affine_grid_generator_4D_backward( + const Tensor& grad_grid, + int64_t N, + int64_t C, + int64_t H, + int64_t W, + bool align_corners) { + auto base_grid = make_base_grid_4D(grad_grid, N, C, H, W, align_corners); + AT_ASSERT(grad_grid.sizes() == IntArrayRef({N, H, W, 2})); + auto grad_theta = base_grid.view({N, H * W, 3}) + .transpose(1, 2) + .bmm(grad_grid.reshape({N, H * W, 2})); + return grad_theta.transpose(1, 2); +} + +static Tensor affine_grid_generator_5D_backward( + const Tensor& grad_grid, + int64_t N, + int64_t C, + int64_t D, + int64_t H, + int64_t W, + bool align_corners) { + auto base_grid = make_base_grid_5D(grad_grid, N, C, D, H, W, align_corners); + AT_ASSERT(grad_grid.sizes() == IntArrayRef({N, D, H, W, 3})); + auto grad_theta = base_grid.view({N, D * H * W, 4}) + .transpose(1, 2) + .bmm(grad_grid.reshape({N, D * H * W, 3})); + return grad_theta.transpose(1, 2); +} + +Tensor affine_grid_generator_backward(const Tensor& grad, IntArrayRef size, bool align_corners) { + TORCH_CHECK( + size.size() == 4 || size.size() == 5, + "AffineGridGenerator needs 4d (spatial) or 5d (volumetric) inputs."); + if (size.size() == 4) { + return affine_grid_generator_4D_backward( + grad, size[0], size[1], size[2], size[3], align_corners); + } else { + return affine_grid_generator_5D_backward( + grad, size[0], size[1], size[2], size[3], size[4], align_corners); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AmpKernels.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AmpKernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2f48faf3f62e16293bf3a6d74b397b2a4dce96a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AmpKernels.cpp @@ -0,0 +1,41 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { + +void _amp_foreach_non_finite_check_and_unscale_cpu_( + TensorList scaled_grads, + at::Tensor& found_inf, + const at::Tensor& inv_scale) { + _amp_foreach_non_finite_check_and_unscale_cpu_stub( + found_inf.device().type(), scaled_grads, found_inf, inv_scale); +} + +at::Tensor& _amp_update_scale_cpu_ ( + at::Tensor& current_scale, + at::Tensor& growth_tracker, + const at::Tensor& found_inf, + double growth_factor, + double backoff_factor, + int64_t growth_interval) { + return _amp_update_scale_cpu_stub( + growth_tracker.device().type(), current_scale, growth_tracker, + found_inf, growth_factor, backoff_factor, growth_interval); +} + +DEFINE_DISPATCH(_amp_foreach_non_finite_check_and_unscale_cpu_stub); +DEFINE_DISPATCH(_amp_update_scale_cpu_stub); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AmpKernels.h b/western_ai/usa/pytorch/aten/src/ATen/native/AmpKernels.h new file mode 100644 index 0000000000000000000000000000000000000000..665a65259218c322a5b19f008a5c273bac61472c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AmpKernels.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +namespace at { +class Tensor; + +namespace native { + +using _amp_foreach_non_finite_check_and_unscale_cpu__fn = void (*)( + TensorList, + Tensor&, + const Tensor&); + +using _amp_update_scale_cpu__fn = Tensor& (*)( + Tensor&, + Tensor&, + const Tensor&, + double, + double, + int64_t); + +DECLARE_DISPATCH(_amp_foreach_non_finite_check_and_unscale_cpu__fn, _amp_foreach_non_finite_check_and_unscale_cpu_stub) +DECLARE_DISPATCH(_amp_update_scale_cpu__fn, _amp_update_scale_cpu_stub) + +} // namespace native +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AutogradComposite.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AutogradComposite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1872d378c14fceb76cb4d994830d5fe0909adcb6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AutogradComposite.cpp @@ -0,0 +1,109 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +// We expect this code to only be reached in inference mode and when all inputs are inference tensors +Tensor _make_dual(const Tensor& primal, const Tensor& tangent, int64_t level) { + TORCH_INTERNAL_ASSERT( + InferenceMode::is_enabled() && primal.is_inference() && tangent.is_inference(), + "Expected this function to only be reached in inference mode and when all the " + "inputs are inference tensors. You should NOT call this function directly as " + "native::_make_dual. Please use the dispatcher, i.e., at::_make_dual. Please " + "file an issue if you come across this error otherwise."); + return at::alias(primal); +} + +/// This function can be used to unpack a given dual Tensor to get its primal and tangent. The returned primal +/// is a view of the dual and the tangent is returned as is. +/// This function is backward differentiable. +std::tuple _unpack_dual(const at::Tensor& tensor, int64_t level) { + return std::tuple(tensor._fw_primal(level), tensor._fw_grad(level)); +} + +// NB: This function can be called directly from _set_fw_grad or +// if self is batched, from this function's batching rule. +// See NOTE: [_new_zeros_with_same_feature_meta] for more information. +Tensor _new_zeros_with_same_feature_meta( + const at::Tensor& self, + const at::Tensor& other, + int64_t self_num_batch_dims) { + auto other_sizes = other.sym_sizes(); + auto other_strides = other.sym_strides(); + auto other_storage_offset = other.storage_offset(); + auto other_storage_numel = other.storage().sym_nbytes() / c10::SymInt(other.itemsize()); + + if (self_num_batch_dims == 0) { + auto new_tensor = at::zeros_symint({other_storage_numel}, other.options()); + return new_tensor.as_strided_symint(other_sizes, other_strides, other_storage_offset); + } + + auto self_sizes = self.sym_sizes(); + + // NB: We don't check that the sizes of self is the same as that of other + // because this function is also used in the inplace over view case + // In the inplace over view case we cannot rely on self and other being + // the same size. So we will use the size of other, and simply tack on + // the batch dims from self. For example: If self.sizes: [B, 2, 3], + // and other.size: [6], we return [B, 6]. + // Also see the test test_inplace_on_view_not_same_layout, for when we reach + // this case. + constexpr int64_t kSmallBufferSizeHint = 8; + + auto out_sizes = c10::SmallVector(other.dim() + self_num_batch_dims); + std::copy(self_sizes.begin(), self_sizes.begin() + self_num_batch_dims, out_sizes.begin()); + std::copy(other_sizes.begin(), other_sizes.end(), out_sizes.begin() + self_num_batch_dims); + + // We use the strides of other, and tack on the strides computed with + // the batch dims of self, so that the slices are arranged contiguously + auto out_strides = c10::SmallVector(other.dim() + self_num_batch_dims); + auto prod = other_storage_numel; + + for (int64_t i = self_num_batch_dims - 1; i >= 0; --i) { + out_strides[i] = prod; + prod *= self_sizes[i]; + } + std::copy(other_strides.begin(), other_strides.end(), out_strides.begin() + self_num_batch_dims); + + auto storage_numel = prod; + + // Inherit the TensorOptions of the primal + auto new_tensor = at::zeros_symint({storage_numel}, other.options()); + return new_tensor.as_strided_symint(out_sizes, out_strides, other_storage_offset); +} + +bool _has_same_storage_numel(const at::Tensor& base, const at::Tensor& other) { + return base.storage().sym_nbytes() / c10::SymInt(base.itemsize()) == other.storage().sym_nbytes() / c10::SymInt(other.itemsize()); +} + +Tensor _lazy_clone(Tensor const& self) { + c10::StorageImpl* self_storage = self.storage().unsafeGetStorageImpl(); + c10::intrusive_ptr storage = + c10::impl::cow::lazy_clone_storage(*self_storage); + TORCH_CHECK(storage != nullptr); + auto tensor = c10::make_intrusive( + c10::Storage(std::move(storage)), + self.key_set(), + self.dtype()); + tensor->set_sizes_and_strides(self.sym_sizes(), + self.sym_strides(), + self.sym_storage_offset()); + return Tensor(std::move(tensor)); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AveragePool2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AveragePool2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24579e007b5d9f7c6205b3ccc64ec938f96fc7bd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AveragePool2d.cpp @@ -0,0 +1,223 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::meta { +using namespace ::at::native; + +TORCH_PRECOMPUTE_META_FUNC(avg_pool2d) +(const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override) { + // checked_convert below only guards against int overflow; non-positive + // kernel/stride and negative padding are caught downstream in + // pooling_output_shape / pool2d_shape_check with more specific messages. + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 2, + "avg_pool2d: kernel_size must either be a single int, or a tuple of two ints"); + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 2, + "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints"); + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 2, + "avg_pool2d: padding must either be a single int, or a tuple of two ints"); + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, + "divisor must be not zero"); + + const int64_t nbatch = input.ndimension() == 4 ? input.size(-4) : 1; + const int64_t nInputPlane = input.size(-3); + const int64_t inputHeight = input.size(-2); + const int64_t inputWidth = input.size(-1); + + const int64_t outputHeight = pooling_output_shape( + inputHeight, kH, padH, dH, 1, ceil_mode); + const int64_t outputWidth = + pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode); + + auto memory_format = input.suggest_memory_format(); + pool2d_shape_check( + input, + kH, + kW, + dH, + dW, + padH, + padW, + 1, + 1, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + memory_format); + + /* resize output */ + if (input.ndimension() == 3) { + set_output_raw_strided( + 0, + {nInputPlane, + outputHeight, + outputWidth}, + {}, + input.options()); + } + else { + set_output_raw_strided( + 0, + {nbatch, + nInputPlane, + outputHeight, + outputWidth}, + {}, + input.options().memory_format(memory_format)); + } + + return TORCH_PRECOMPUTE_STRUCT(avg_pool2d)().set_kH(kH).set_kW(kW).set_dH(dH).set_dW(dW).set_padH(padH).set_padW(padW); +} + +TORCH_META_FUNC(avg_pool2d_backward) ( + const Tensor& gradOutput_, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override +) { + // checked_convert below only guards against int overflow; non-positive + // kernel/stride and negative padding are caught downstream in + // pooling_output_shape / avg_pool2d_backward_shape_check with more specific messages. + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 2, + "avg_pool2d: kernel_size must either be a single int, or a tuple of two ints"); + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 2, + "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints"); + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 2, + "avg_pool2d: padding must either be a single int, or a tuple of two ints"); + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, "divisor must be not zero"); + + /* sizes */ + const int64_t nbatch = input.ndimension() == 4 ? input.size(-4) : 1; + const int64_t nInputPlane = input.size(-3); // number of channels (or colors) + const int64_t inputHeight = input.size(-2); + const int64_t inputWidth = input.size(-1); + const int64_t outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode); + const int64_t outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode); + + auto memory_format = input.suggest_memory_format(); + avg_pool2d_backward_shape_check( + input, + gradOutput_, + nbatch, + kH, kW, dH, dW, padH, padW, + nInputPlane, + inputHeight, inputWidth, + outputHeight, outputWidth, + memory_format); + + /* resize output */ + set_output_raw_strided(0, input.sizes(), {}, input.options().memory_format(memory_format)); +} + +} // namespace at::meta + +namespace at::native { + +TORCH_IMPL_FUNC(avg_pool2d_out_cpu) +(const Tensor& input, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& output) { + avg_pool2d_kernel( + kCPU, + output, + input, + kW, + kH, + dW, + dH, + padW, + padH, + count_include_pad, + divisor_override); +} + +TORCH_IMPL_FUNC(avg_pool2d_backward_out_cpu) ( + const Tensor& gradOutput, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& gradInput +) { + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, "divisor must be not zero"); + + TORCH_CHECK(input.dtype() == gradOutput.dtype(), + "expected dtype ", input.dtype(), " for `gradOutput` but got dtype ", gradOutput.dtype()); + + /* zero the gradient */ + gradInput.zero_(); + + avg_pool2d_backward_kernel( + kCPU, gradInput, gradOutput, + kW, kH, dW, dH, padW, padH, + count_include_pad, divisor_override); +} + +DEFINE_DISPATCH(avg_pool2d_kernel); +DEFINE_DISPATCH(avg_pool2d_backward_kernel); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/AveragePool3d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/AveragePool3d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0add930f7f8d8ec3739decc890994654580aeaa3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/AveragePool3d.cpp @@ -0,0 +1,510 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::meta { +using namespace ::at::native; + +TORCH_META_FUNC(avg_pool3d) ( + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override +) { + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, + "avg_pool3d: kernel_size must be a single int, or a tuple of three ints"); + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, + "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints"); + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 3, + "avg_pool3d: padding must be a single int, or a tuple of three ints"); + const int padT = c10::checked_convert(padding[0], "int"); + const int padH = padding.size() == 1 ? padT : c10::checked_convert(padding[1], "int"); + const int padW = padding.size() == 1 ? padT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK((input.ndimension() == 4 || input.ndimension() == 5), + "non-empty 4D or 5D (batch mode) tensor expected for input"); + + TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, + "divisor must be not zero"); + + /* sizes */ + const int64_t nbatch = input.size(0); + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + const int64_t otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode); + const int64_t oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode); + const int64_t owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode); + + pool3d_shape_check( + input, + nslices, + kT, kH, kW, + dT, dH, dW, + padT, padH, padW, + 1, 1, 1, + itime, iheight, iwidth, + otime, oheight, owidth, + "avg_pool3d()", + /*check_input_size=*/ true); + + /* resize output */ + if (input.ndimension() == 4) { + set_output_raw_strided(0, {nslices, otime, oheight, owidth}, {}, input.options()); + } + else { + set_output_raw_strided(0, {nbatch, nslices, otime, oheight, owidth}, {}, input.options()); + } +} + +TORCH_META_FUNC(avg_pool3d_backward) ( + const Tensor& gradOutput_, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override +) { + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, + "avg_pool3d: kernel_size must be a single int, or a tuple of three ints"); + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, + "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints"); + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 3, + "avg_pool3d: padding must be a single int, or a tuple of three ints"); + const int padT = c10::checked_convert(padding[0], "int"); + const int padH = padding.size() == 1 ? padT : c10::checked_convert(padding[1], "int"); + const int padW = padding.size() == 1 ? padT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK((input.ndimension() == 4 || input.ndimension() == 5), + "non-empty 4D or 5D (batch mode) tensor expected for input"); + + TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, "divisor must be not zero"); + + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + /* XXX shape check behavior from TH */ + const int64_t otime_for_shape_check = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode); + const int64_t oheight_for_shape_check = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode); + const int64_t owidth_for_shape_check = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode); + + avg_pool3d_backward_shape_check( + input, + gradOutput_, + nslices, + kT, kH, kW, + dT, dH, dW, + padT, padH, padW, + itime, iheight, iwidth, + otime_for_shape_check, oheight_for_shape_check, owidth_for_shape_check, + "avg_pool3d_backward()"); + + /* resize output */ + set_output_raw_strided(0, input.sizes(), {}, input.options()); +} + +} // namespace at::meta + +namespace at::native { + +namespace { + +template +void avg_pool3d_out_frame( + const scalar_t *input_p, + scalar_t *output_p, + int64_t nslices, + int64_t itime, + int64_t iwidth, + int64_t iheight, + int64_t otime, + int64_t owidth, + int64_t oheight, + int kT, + int kW, + int kH, + int dT, + int dW, + int dH, + int padT, + int padW, + int padH, + bool count_include_pad, + std::optional divisor_override) +{ + at::parallel_for(0, nslices, 0, [&](int64_t start, int64_t end) { + for (const auto k : c10::irange(start, end)) { + /* local pointers. */ + const scalar_t *ip = input_p + k * itime * iwidth * iheight; + scalar_t *op = output_p + k * otime * owidth * oheight; + for (int64_t i = 0; i < otime * oheight * owidth; ++i) + *(op + i) = 0; + + /* loop over output */ + for (int64_t ti = 0; ti < otime; ti++) + { + for (int64_t i = 0; i < oheight; i++) + { + for (int64_t j = 0; j < owidth; j++) + { + /* compute pool range. */ + int64_t tstart = ti * dT - padT; + int64_t hstart = i * dH - padH; + int64_t wstart = j * dW - padW; + int64_t tend = std::min(tstart + kT, itime + padT); + int64_t hend = std::min(hstart + kH, iheight + padH); + int64_t wend = std::min(wstart + kW, iwidth + padW); + int64_t pool_size = (tend - tstart) * (hend - hstart) * (wend - wstart); + tstart = std::max(tstart, static_cast(0)); + hstart = std::max(hstart, static_cast(0)); + wstart = std::max(wstart, static_cast(0)); + tend = std::min(tend, itime); + hend = std::min(hend, iheight); + wend = std::min(wend, iwidth); + + if (tstart >= tend || hstart >= hend || wstart >= wend) { + ++op; + continue; + } + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (tend - tstart) * (hend - hstart) * (wend - wstart); + } + } + + /* compute local sum: */ + scalar_t sum = 0.0; + for (int64_t z = tstart; z < tend; z++) + { + for (int64_t y = hstart; y < hend; y++) + { + for (int64_t x = wstart; x < wend; x++) + { + sum += *(ip + z * iwidth * iheight + y * iwidth + x); + } + } + } + + /* set output to local max */ + *op++ += sum / divide_factor; + } + } + } + } + }); +} + +} // anonymous namespace + +TORCH_IMPL_FUNC(avg_pool3d_out_cpu) ( + const Tensor& input_, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& output +) { + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + const int padT = c10::checked_convert(padding[0], "int"); + const int padH = padding.size() == 1 ? padT : c10::checked_convert(padding[1], "int"); + const int padW = padding.size() == 1 ? padT : c10::checked_convert(padding[2], "int"); + + const int64_t nslices = input_.size(-4); + const int64_t itime = input_.size(-3); + const int64_t iheight = input_.size(-2); + const int64_t iwidth = input_.size(-1); + + const int64_t otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode); + const int64_t oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode); + const int64_t owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode); + + /* get contiguous input */ + Tensor input = input_.contiguous(); + + if (input.ndimension() == 4) /* non-batch mode */ + { + AT_DISPATCH_FLOATING_TYPES_AND(at::ScalarType::Long, input.scalar_type(), + "avg_pool3d_out_frame", + [&] { + const scalar_t *input_data = input.const_data_ptr(); + scalar_t *output_data = output.data_ptr(); + + avg_pool3d_out_frame( + input_data, output_data, nslices, + itime, iwidth, iheight, + otime, owidth, oheight, + kT, kW, kH, + dT, dW, dH, + padT, padW, padH, + count_include_pad, + divisor_override); + }); + } + else /* batch mode */ + { + const int64_t nbatch = input.size(0); + const int64_t istride = nslices * itime * iwidth * iheight; + const int64_t ostride = nslices * otime * owidth * oheight; + + AT_DISPATCH_FLOATING_TYPES_AND(at::ScalarType::Long, input.scalar_type(), + "avg_pool3d_out_frame", + [&] { + const scalar_t *input_data = input.const_data_ptr(); + scalar_t *output_data = output.data_ptr(); + + at::parallel_for(0, nbatch, 0, [&](int64_t start, int64_t end) { + for (const auto p : c10::irange(start, end)) { + avg_pool3d_out_frame( + input_data + p * istride, output_data + p * ostride, nslices, + itime, iwidth, iheight, + otime, owidth, oheight, + kT, kW, kH, + dT, dW, dH, + padT, padW, padH, + count_include_pad, + divisor_override + ); + } + }); + }); + } +} + +namespace { + +template +void avg_pool3d_backward_out_frame( + scalar_t *gradInput_p, + const scalar_t *gradOutput_p, + int64_t nslices, + int64_t itime, + int64_t iwidth, + int64_t iheight, + int64_t otime, + int64_t owidth, + int64_t oheight, + int kT, + int kW, + int kH, + int dT, + int dW, + int dH, + int padT, + int padW, + int padH, + bool count_include_pad, + std::optional divisor_override) +{ + at::parallel_for(0, nslices, 0, [&](int64_t start, int64_t end) { + for (const auto k : c10::irange(start, end)) { + /* local pointers */ + scalar_t *ip = gradInput_p + k * itime * iwidth * iheight; + const scalar_t *op = gradOutput_p + k * otime * owidth * oheight; + for (int64_t i = 0; i < itime*iwidth*iheight; i++) + *(ip + i) = 0; + + /* loop over output */ + for (int64_t ti = 0; ti < otime; ti++) + { + for (int64_t i = 0; i < oheight; i++) + { + for (int64_t j = 0; j < owidth; j++) + { + int64_t tstart = ti * dT - padT; + int64_t hstart = i * dH - padH; + int64_t wstart = j * dW - padW; + int64_t tend = std::min(tstart + kT, itime + padT); + int64_t hend = std::min(hstart + kH, iheight + padH); + int64_t wend = std::min(wstart + kW, iwidth + padW); + int64_t pool_size = (tend -tstart) * (hend - hstart) * (wend - wstart); + tstart = std::max(tstart, static_cast(0)); + hstart = std::max(hstart, static_cast(0)); + wstart = std::max(wstart, static_cast(0)); + tend = std::min(tend, itime); + hend = std::min(hend, iheight); + wend = std::min(wend, iwidth); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (tend - tstart) * (hend - hstart) * (wend - wstart); + } + } + + /* scatter gradients out to footprint: */ + scalar_t val = *op++; + + for (auto z = tstart; z < tend; z++) + { + for (auto y = hstart; y < hend; y++) + { + for (auto x = wstart; x < wend; x++) + { + *(ip + z * iheight * iwidth + y * iwidth + x) += val / divide_factor; + } + } + } + } + } + } + } + }); +} + +} // anonymous namespace + +TORCH_IMPL_FUNC(avg_pool3d_backward_out_cpu) ( + const Tensor& gradOutput_, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& gradInput +) { + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + const int padT = c10::checked_convert(padding[0], "int"); + const int padH = padding.size() == 1 ? padT : c10::checked_convert(padding[1], "int"); + const int padW = padding.size() == 1 ? padT : c10::checked_convert(padding[2], "int"); + + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + /* get contiguous gradOutput */ + Tensor gradOutput = gradOutput_.contiguous(); + + const int64_t otime = gradOutput.size(-3); + const int64_t oheight = gradOutput.size(-2); + const int64_t owidth = gradOutput.size(-1); + + gradInput.zero_(); + + /* backprop */ + if (input.ndimension() == 4) /* non-batch mode*/ + { + AT_DISPATCH_FLOATING_TYPES_AND(at::ScalarType::Long, input.scalar_type(), + "avg_pool3d_backward_out_frame", + [&] { + scalar_t *gradInput_data = gradInput.data_ptr(); + const scalar_t *gradOutput_data = gradOutput.const_data_ptr(); + + avg_pool3d_backward_out_frame( + gradInput_data, gradOutput_data, + nslices, + itime, iwidth, iheight, + otime, owidth, oheight, + kT, kW, kH, + dT, dW, dH, + padT, padW, padH, + count_include_pad, + divisor_override); + }); + } + else /* batch mode */ + { + const int64_t nbatch = input.size(0); + const int64_t istride = nslices * itime * iwidth * iheight; + const int64_t ostride = nslices * otime * owidth * oheight; + + AT_DISPATCH_FLOATING_TYPES_AND(at::ScalarType::Long, input.scalar_type(), + "avg_pool3d_backward_out_frame", + [&] { + scalar_t *gradInput_data = gradInput.data_ptr(); + const scalar_t *gradOutput_data = gradOutput.const_data_ptr(); + + at::parallel_for(0, nbatch, 0, [&](int64_t start, int64_t end) { + for (const auto p : c10::irange(start, end)) { + avg_pool3d_backward_out_frame( + gradInput_data + p * istride, gradOutput_data + p * ostride, nslices, + itime, iwidth, iheight, + otime, owidth, oheight, + kT, kW, kH, + dT, dW, dH, + padT, padW, padH, + count_include_pad, + divisor_override + ); + } + }); + }); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebra.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cea45177f0cef8123b190930331de257ef943235 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebra.cpp @@ -0,0 +1,4070 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +// First the required LAPACK implementations are registered here. +// A comment above the registered LAPACK routine suggest which batched +// linear algebra function uses that routine +#if AT_BUILD_WITH_LAPACK() + +#ifndef _ARMPL_H // ArmPL's `cblas.h` pulls in these prototypes. +// getrf +extern "C" void zgetrf_(int *m, int *n, std::complex *a, int *lda, int *ipiv, int *info); +extern "C" void cgetrf_(int *m, int *n, std::complex *a, int *lda, int *ipiv, int *info); +extern "C" void dgetrf_(int *m, int *n, double *a, int *lda, int *ipiv, int *info); +extern "C" void sgetrf_(int *m, int *n, float *a, int *lda, int *ipiv, int *info); +#endif + +// potrs +#if defined(_WIN32) && defined(_M_ARM64) + +// The functions zpotrs, cpotrs, dpotrs, and spotrs are not directly available in LAPACKE on Windows on ARM, +// so we need to have wrapper functions to call them. +// The issue on ARM platform can be found below: +// https://community.arm.com/support-forums/f/high-performance-computing-forum/56512/unable-to-use-lapack---potrs-functions + +#define LAPACK_COL_MAJOR 102 +#define LAPACK_ROW_MAJOR 101 + +extern "C" int LAPACKE_zpotrs(int matrix_layout, char uplo, int n, int nrhs, const std::complex *a, int lda, std::complex *b, int ldb); +extern "C" int LAPACKE_cpotrs(int matrix_layout, char uplo, int n, int nrhs, const std::complex *a, int lda, std::complex *b, int ldb); +extern "C" int LAPACKE_dpotrs(int matrix_layout, char uplo, int n, int nrhs, const double *a, int lda, double *b, int ldb); +extern "C" int LAPACKE_spotrs(int matrix_layout, char uplo, int n, int nrhs, const float *a, int lda, float *b, int ldb); + +static inline void zpotrs_(char *uplo, int *n, int *nrhs, std::complex *a, int *lda, std::complex *b, int *ldb, int *info) { + *info = LAPACKE_zpotrs(LAPACK_COL_MAJOR, *uplo, *n, *nrhs, a, *lda, b, *ldb); +} + +static inline void cpotrs_(char *uplo, int *n, int *nrhs, std::complex *a, int *lda, std::complex *b, int *ldb, int *info) { + *info = LAPACKE_cpotrs(LAPACK_COL_MAJOR, *uplo, *n, *nrhs, a, *lda, b, *ldb); +} + +static inline void dpotrs_(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info){ + *info = LAPACKE_dpotrs(LAPACK_COL_MAJOR, *uplo, *n, *nrhs, a, *lda, b, *ldb); +} + +static inline void spotrs_(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info) { + *info = LAPACKE_spotrs(LAPACK_COL_MAJOR, *uplo, *n, *nrhs, a, *lda, b, *ldb); +} + +#else + +#ifndef _ARMPL_H // ArmPL's `cblas.h` pulls in these prototypes. +extern "C" void zpotrs_(char *uplo, int *n, int *nrhs, std::complex *a, int *lda, std::complex *b, int *ldb, int *info); +extern "C" void cpotrs_(char *uplo, int *n, int *nrhs, std::complex *a, int *lda, std::complex *b, int *ldb, int *info); +extern "C" void dpotrs_(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info); +extern "C" void spotrs_(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info); +#endif + +#endif + +#ifndef _ARMPL_H // ArmPL's `cblas.h` pulls in these prototypes. +// potrf +extern "C" void zpotrf_(char *uplo, int *n, std::complex *a, int *lda, int *info); +extern "C" void cpotrf_(char *uplo, int *n, std::complex *a, int *lda, int *info); +extern "C" void dpotrf_(char *uplo, int *n, double *a, int *lda, int *info); +extern "C" void spotrf_(char *uplo, int *n, float *a, int *lda, int *info); + +// potri +extern "C" void zpotri_(char *uplo, int *n, std::complex *a, int *lda, int *info); +extern "C" void cpotri_(char *uplo, int *n, std::complex *a, int *lda, int *info); +extern "C" void dpotri_(char *uplo, int *n, double *a, int *lda, int *info); +extern "C" void spotri_(char *uplo, int *n, float *a, int *lda, int *info); + +// sytrf +extern "C" void dsytrf_( + char* uplo, + int* n, + double* a, + int* lda, + int* ipiv, + double* work, + int* lwork, + int* info); +extern "C" void ssytrf_( + char* uplo, + int* n, + float* a, + int* lda, + int* ipiv, + float* work, + int* lwork, + int* info); +extern "C" void zsytrf_( + char* uplo, + int* n, + std::complex* a, + int* lda, + int* ipiv, + std::complex* work, + int* lwork, + int* info); +extern "C" void csytrf_( + char* uplo, + int* n, + std::complex* a, + int* lda, + int* ipiv, + std::complex* work, + int* lwork, + int* info); + +// hetrf +extern "C" void zhetrf_( + char* uplo, + int* n, + std::complex* a, + int* lda, + int* ipiv, + std::complex* work, + int* lwork, + int* info); +extern "C" void chetrf_( + char* uplo, + int* n, + std::complex* a, + int* lda, + int* ipiv, + std::complex* work, + int* lwork, + int* info); + +// sytrs +extern "C" void dsytrs_( + char* uplo, + int* n, + int* nrhs, + double* a, + int* lda, + int* ipiv, + double* b, + int* ldb, + int* info); +extern "C" void ssytrs_( + char* uplo, + int* n, + int* nrhs, + float* a, + int* lda, + int* ipiv, + float* b, + int* ldb, + int* info); +extern "C" void zsytrs_( + char* uplo, + int* n, + int* nrhs, + std::complex* a, + int* lda, + int* ipiv, + std::complex* b, + int* ldb, + int* info); +extern "C" void csytrs_( + char* uplo, + int* n, + int* nrhs, + std::complex* a, + int* lda, + int* ipiv, + std::complex* b, + int* ldb, + int* info); + +// hetrs +extern "C" void zhetrs_( + char* uplo, + int* n, + int* nrhs, + std::complex* a, + int* lda, + int* ipiv, + std::complex* b, + int* ldb, + int* info); +extern "C" void chetrs_( + char* uplo, + int* n, + int* nrhs, + std::complex* a, + int* lda, + int* ipiv, + std::complex* b, + int* ldb, + int* info); + +// geqrf +extern "C" void zgeqrf_(int *m, int *n, std::complex *a, int *lda, std::complex *tau, std::complex *work, int *lwork, int *info); +extern "C" void cgeqrf_(int *m, int *n, std::complex *a, int *lda, std::complex *tau, std::complex *work, int *lwork, int *info); +extern "C" void dgeqrf_(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +extern "C" void sgeqrf_(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info); + +// orgqr +extern "C" void zungqr_(int *m, int *n, int *k, std::complex *a, int *lda, std::complex *tau, std::complex *work, int *lwork, int *info); +extern "C" void cungqr_(int *m, int *n, int *k, std::complex *a, int *lda, std::complex *tau, std::complex *work, int *lwork, int *info); +extern "C" void dorgqr_(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info); +extern "C" void sorgqr_(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info); +#endif + +// ormqr +#if defined(_WIN32) && defined(_M_ARM64) + +// The functions zunmqr, cunmqr, dormqr, and sormqr are not directly available in LAPACKE on Windows on ARM, +// so we need to have wrapper functions to call them. +// The issue on ARM platform can be found below: +// https://community.arm.com/support-forums/f/high-performance-computing-forum/56512/unable-to-use-lapack---potrs-functions + +extern "C" int LAPACKE_zunmqr_work(int matrix_layout, char side, char trans, int m, int n, int k, const std::complex *a, int lda, const std::complex *tau, std::complex *c, int ldc, std::complex *work, int lwork); +extern "C" int LAPACKE_cunmqr_work(int matrix_layout, char side, char trans, int m, int n, int k, const std::complex *a, int lda, const std::complex *tau, std::complex *c, int ldc, std::complex *work, int lwork); +extern "C" int LAPACKE_dormqr_work(int matrix_layout, char side, char trans, int m, int n, int k, const double *a, int lda, const double *tau, double *c, int ldc, double *work, int lwork); +extern "C" int LAPACKE_sormqr_work(int matrix_layout, char side, char trans, int m, int n, int k, const float *a, int lda, const float *tau, float *c, int ldc, float *work, int lwork); + +static inline void zunmqr_(char *side, char *trans, int *m, int *n, int *k, std::complex *a, int *lda, std::complex *tau, std::complex *c, int *ldc, std::complex *work, int *lwork, int *info) { + *info = LAPACKE_zunmqr_work(LAPACK_COL_MAJOR, *side, *trans, *m, *n, *k, a, *lda, tau, c, *ldc, work, *lwork); +} + +static inline void cunmqr_(char *side, char *trans, int *m, int *n, int *k, std::complex *a, int *lda, std::complex *tau, std::complex *c, int *ldc, std::complex *work, int *lwork, int *info) { + *info = LAPACKE_cunmqr_work(LAPACK_COL_MAJOR, *side, *trans, *m, *n, *k, a, *lda, tau, c, *ldc, work, *lwork); +} + +static inline void dormqr_(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info) { + *info = LAPACKE_dormqr_work(LAPACK_COL_MAJOR, *side, *trans, *m, *n, *k, a, *lda, tau, c, *ldc, work, *lwork); +} + +static inline void sormqr_(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info) { + *info = LAPACKE_sormqr_work(LAPACK_COL_MAJOR, *side, *trans, *m, *n, *k, a, *lda, tau, c, *ldc, work, *lwork); +} +#else +#ifndef _ARMPL_H // ArmPL's `cblas.h` pulls in these prototypes. +extern "C" void zunmqr_(char *side, char *trans, int *m, int *n, int *k, std::complex *a, int *lda, std::complex *tau, std::complex *c, int *ldc, std::complex *work, int *lwork, int *info); +extern "C" void cunmqr_(char *side, char *trans, int *m, int *n, int *k, std::complex *a, int *lda, std::complex *tau, std::complex *c, int *ldc, std::complex *work, int *lwork, int *info); +extern "C" void dormqr_(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info); +extern "C" void sormqr_(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info); +#endif +#endif +#ifndef _ARMPL_H // ArmPL's `cblas.h` pulls in these prototypes. +// syevd +extern "C" void zheevd_(char *jobz, char *uplo, int *n, std::complex *a, int *lda, double *w, std::complex *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info); +extern "C" void cheevd_(char *jobz, char *uplo, int *n, std::complex *a, int *lda, float *w, std::complex *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info); +extern "C" void dsyevd_(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info); +extern "C" void ssyevd_(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info); + +// geev +extern "C" void dgeev_(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *wr, double *wi, double* vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info); +extern "C" void sgeev_(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *wr, float *wi, float* vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info); +extern "C" void cgeev_(char *jobvl, char *jobvr, int *n, + std::complex *a, int *lda, + std::complex *w, + std::complex *vl, int *ldvl, + std::complex *vr, int *ldvr, + std::complex *work, int *lwork, + float *rwork, + int *info); +extern "C" void zgeev_(char *jobvl, char *jobvr, int *n, + std::complex *a, int *lda, + std::complex *w, + std::complex *vl, int *ldvl, + std::complex *vr, int *ldvr, + std::complex *work, int *lwork, + double *rwork, + int *info); + +// gesdd +extern "C" void zgesdd_(char *jobz, int *m, int *n, std::complex *a, int *lda, + double *s, std::complex *u, int *ldu, std::complex *vt, int *ldvt, std::complex *work, int *lwork, double *rwork, int *iwork, int *info); +extern "C" void cgesdd_(char *jobz, int *m, int *n, std::complex *a, int *lda, + float *s, std::complex *u, int *ldu, std::complex *vt, int *ldvt, std::complex *work, int *lwork, float *rwork, int *iwork, int *info); +extern "C" void dgesdd_(char *jobz, int *m, int *n, double *a, int *lda, + double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *iwork, int *info); +extern "C" void sgesdd_(char *jobz, int *m, int *n, float *a, int *lda, + float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info); + +// getrs +extern "C" void zgetrs_(char *trans, int *n, int *nrhs, std::complex *a, int *lda, int *ipiv, std::complex *b, int *ldb, int *info); +extern "C" void cgetrs_(char *trans, int *n, int *nrhs, std::complex *a, int *lda, int *ipiv, std::complex *b, int *ldb, int *info); +extern "C" void dgetrs_(char *trans, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info); +extern "C" void sgetrs_(char *trans, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info); + +// gels +extern "C" void zgels_(char *trans, int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + std::complex *work, int *lwork, int *info); +extern "C" void cgels_(char *trans, int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + std::complex *work, int *lwork, int *info); +extern "C" void dgels_(char *trans, int *m, int *n, int *nrhs, + double *a, int *lda, double *b, int *ldb, + double *work, int *lwork, int *info); +extern "C" void sgels_(char *trans, int *m, int *n, int *nrhs, + float *a, int *lda, float *b, int *ldb, + float *work, int *lwork, int *info); + +// gelsd +extern "C" void zgelsd_(int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + double *s, double *rcond, int *rank, + std::complex *work, int *lwork, double *rwork, int *iwork, int *info); +extern "C" void cgelsd_(int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + float *s, float *rcond, int *rank, + std::complex *work, int *lwork, float *rwork, int *iwork, int *info); +extern "C" void dgelsd_(int *m, int *n, int *nrhs, + double *a, int *lda, double *b, int *ldb, + double *s, double *rcond, int *rank, + double *work, int *lwork, int *iwork, int *info); +extern "C" void sgelsd_(int *m, int *n, int *nrhs, + float *a, int *lda, float *b, int *ldb, + float *s, float *rcond, int *rank, + float *work, int *lwork, int *iwork, int *info); + +// gelsy +extern "C" void zgelsy_(int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + int *jpvt, double *rcond, int *rank, + std::complex *work, int *lwork, + double *rwork, int *info); +extern "C" void cgelsy_(int *m, int *n, int *nrhs, + std::complex * a, int *lda, std::complex *b, int *ldb, + int *jpvt, float *rcond, int *rank, + std::complex *work, int *lwork, + float *rwork, int *info); +extern "C" void dgelsy_(int *m, int *n, int *nrhs, + double *a, int *lda, double *b, int *ldb, + int *jpvt, double *rcond, int *rank, + double *work, int *lwork, int *info); +extern "C" void sgelsy_(int *m, int *n, int *nrhs, + float *a, int *lda, float *b, int *ldb, + int *jpvt, float *rcond, int *rank, + float *work, int *lwork, int *info); + +// gelss +extern "C" void zgelss_(int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + double *s, double *rcond, int *rank, + std::complex *work, int *lwork, + double *rwork, int *info); +extern "C" void cgelss_(int *m, int *n, int *nrhs, + std::complex *a, int *lda, std::complex *b, int *ldb, + float *s, float *rcond, int *rank, + std::complex *work, int *lwork, + float *rwork, int *info); +extern "C" void dgelss_(int *m, int *n, int *nrhs, + double *a, int *lda, double *b, int *ldb, + double *s, double *rcond, int *rank, + double *work, int *lwork, int *info); +extern "C" void sgelss_(int *m, int *n, int *nrhs, + float *a, int *lda, float *b, int *ldb, + float *s, float *rcond, int *rank, + float *work, int *lwork, int *info); +#endif +#endif + +#if AT_BUILD_WITH_BLAS() +// trsm +#ifndef _ARMPL_H // ArmPL's `cblas.h` pulls in these prototypes. +extern "C" void ztrsm_(char *side, char *uplo, char *trans, char *diag, int *n, int *nrhs, std::complex *alpha, std::complex *a, int *lda, std::complex *b, int *ldb); +extern "C" void ctrsm_(char *side, char *uplo, char *trans, char *diag, int *n, int *nrhs, std::complex *alpha, std::complex *a, int *lda, std::complex *b, int *ldb); +extern "C" void dtrsm_(char *side, char *uplo, char *trans, char *diag, int *n, int *nrhs, double *alpha, double *a, int *lda, double *b, int *ldb); +extern "C" void strsm_(char *side, char *uplo, char *trans, char *diag, int *n, int *nrhs, float *alpha, float *a, int *lda, float *b, int *ldb); +#endif +#endif + +namespace at::meta { + +TORCH_META_FUNC(linalg_ldl_factor_ex) +(const Tensor& self, bool hermitian, bool check_errors) { + at::native::squareCheckInputs(self, "torch.linalg.ldl_factor_ex"); + at::native::checkFloatingOrComplex(self, "torch.linalg.ldl_factor_ex"); + + auto shape = self.sizes(); + auto ndim = shape.size(); + + // prefer column major strides + auto ld_strides = at::native::batched_matrix_contiguous_strides(shape, /*f-contig=*/true); + set_output_strided(0, shape, ld_strides, self.options()); // LD + + set_output_contiguous( + 1, shape.slice(0, ndim - 1), self.options().dtype(ScalarType::Int)); // pivots + + set_output_contiguous( + 2, shape.slice(0, ndim - 2), self.options().dtype(ScalarType::Int)); // info +} + +TORCH_META_FUNC(linalg_ldl_solve) +(const Tensor& LD, + const Tensor& pivots, + const Tensor& B, + bool hermitian) { + at::native::squareCheckInputs(LD, "torch.linalg.ldl_solve"); + at::native::checkFloatingOrComplex(LD, "torch.linalg.ldl_solve"); + at::native::linearSolveCheckInputs(B, LD, "torch.linalg.ldl_solve"); + TORCH_CHECK( + B.dim() >= 2, + "torch.linalg.ldl_solve: Expected B to have at least 2 dimensions, but it has ", + B.dim(), + " dimensions instead"); + auto expected_pivots_shape = LD.sizes().slice(0, LD.dim() - 1); + TORCH_CHECK( + expected_pivots_shape.equals(pivots.sizes()), + "torch.linalg.ldl_solve: Expected LD.shape[:-1] and pivots.shape to be the same, but got pivots with shape ", + pivots.sizes(), + " instead"); + // pivots is allowed to be any integer type + // LAPACK we use is 32-bit interface while cuSOLVER uses 64-bit interface for integers + TORCH_CHECK( + at::isIntegralType(pivots.scalar_type(), /*includeBool=*/false), + "torch.linalg.ldl_solve: Expected pivots to be integers. Got ", + pivots.scalar_type()); + TORCH_CHECK( + LD.scalar_type() == B.scalar_type(), + "torch.linalg.ldl_solve: ", + "LD dtype", + LD.scalar_type(), + " does not match b dtype ", + B.scalar_type()); + + auto [B_broadcast_size, _] = at::native::_linalg_broadcast_batch_dims(B, LD); + + // prefer column major strides + auto result_strides = at::native::batched_matrix_contiguous_strides(B_broadcast_size, /*f_contig=*/true); + set_output_strided(0, B_broadcast_size, result_strides, B.options()); +} + +TORCH_META_FUNC(triangular_solve)(const Tensor& self, const Tensor& A, bool upper, bool transpose, bool unitriangular) { + TORCH_CHECK(self.dim() >= 2, + "torch.triangular_solve: Expected b to have at least 2 dimensions, but it has ", self.dim(), " dimensions instead"); + TORCH_CHECK(A.dim() >= 2, + "torch.triangular_solve: Expected A to have at least 2 dimensions, but it has ", A.dim(), " dimensions instead"); + + at::native::linearSolveCheckInputs(self, A, "triangular_solve"); + + if (A.layout() == Layout::Strided) { + auto [self_broadcast_size, A_broadcast_size] = at::native::_linalg_broadcast_batch_dims(self, A); + + // make column major strides for BLAS + const auto solution_strides = at::native::batched_matrix_contiguous_strides(self_broadcast_size, /*f-contig=*/true); + set_output_raw_strided(0, self_broadcast_size, solution_strides, self.options()); + + // make column major strides for BLAS + auto clone_A_strides = at::native::batched_matrix_contiguous_strides(A_broadcast_size, /*f_contig=*/true); + set_output_raw_strided(1, A_broadcast_size, clone_A_strides, A.options()); + } else if (A.layout() == Layout::SparseCsr || A.layout() == Layout::SparseBsr) { + // no broadcasting for non-strided layout + set_output_raw_strided(0, self.sizes(), {}, self.options()); // make row major strides for Sparse BLAS + set_output_raw_strided(1, {0}, {}, self.options()); // return 0-sized tensor + } else if (A.layout() == Layout::SparseCsc) { + TORCH_CHECK_VALUE(false, "triangular_solve: unsupported sparse layout."); + } else { + TORCH_INTERNAL_ASSERT(false, "triangular_solve: Got an unexpected layout."); + } +} + +TORCH_META_FUNC(_linalg_solve_ex)(const Tensor& A, + const Tensor& B, + bool left, + bool check_errors) { + // dtype + at::native::checkFloatingOrComplex(A, "linalg.solve"); + TORCH_CHECK(A.scalar_type() == B.scalar_type(), + "linalg.solve: Expected A and B to have the same dtype, but found A of type ", + A.scalar_type(), " and B of type ", B.scalar_type(), " instead"); + + // NumPy compat: Two types of 'B' tensors are supported: + // - 1D tensor or batch of 1D tensors (vector case) + // - 2D tensor or batch of 2D tensors (matrix case) + const bool vector_case = at::native::linalg_solve_is_vector_rhs(A, B); + auto B_ = vector_case ? B.unsqueeze(-1) : B; + + // matrix shapes + at::native::checkInputsSolver(A, B_, /*left=*/left, "linalg.solve"); + + // Check that B can be broadcasted to the shape of A + auto B_broad_shape = std::get<0>(at::native::_linalg_broadcast_batch_dims(B_, A)); + // We disallow the broadcasting of B as a vector when left=False as, in that case, A.shape = (*, 1, 1) + TORCH_CHECK(left || !vector_case, "linalg.solve: Vector broadcasting of the left hand side is not supported for left=False. In this case linalg.solve is equivalent to B / A.squeeze(-1)"); + auto result_shape = vector_case ? IntArrayRef(B_broad_shape.data(), B_broad_shape.size() - 1) + : B_broad_shape; + // row major for mps implementation + auto result_strides = at::native::batched_matrix_contiguous_strides(result_shape, /*f_contig=*/A.device().type() != at::kMPS? left : false); + + set_output_strided(0, result_shape, result_strides, B.options()); + + auto shape = A.sizes(); + auto ndim = shape.size(); + + // LU, row major for mps + auto LU_strides = at::native::batched_matrix_contiguous_strides(shape, /*f-contig*=*/A.device().type() != at::kMPS? true : false); + set_output_strided(1, shape, LU_strides, A.options()); + + // pivots + set_output_contiguous(2, shape.slice(0, ndim - 1), A.options().dtype(kInt)); + + // info + set_output_contiguous(3, shape.slice(0, ndim - 2), A.options().dtype(kInt)); +} + +TORCH_META_FUNC(linalg_inv_ex)(const Tensor& A, bool check_errors) { + at::native::squareCheckInputs(A, "linalg.inv"); + at::native::checkFloatingOrComplex(A, "linalg.inv", /*allow_low_precision_dtypes*/false); + + auto shape = A.sizes(); + + auto result_strides = at::native::batched_matrix_contiguous_strides(shape, /*f-contig*=*/true); + set_output_strided(0, shape, result_strides, A.options()); + set_output_contiguous( + 1, shape.slice(0, shape.size() - 2), A.options().dtype(ScalarType::Int)); // info +} + +TORCH_META_FUNC(linalg_lu_factor_ex)(const Tensor& A, bool pivot, bool check_errors) { + TORCH_CHECK(A.dim() >= 2, "torch.lu_factor: Expected tensor with 2 or more dimensions. Got size: ", A.sizes(), " instead"); + + auto sizes = A.sizes().vec(); + const auto m = sizes.cend()[-2]; + const auto n = sizes.cend()[-1]; + + // row major for MPS device, otherwise column major strides for BLAS + auto LU_strides = at::native::batched_matrix_contiguous_strides(sizes, /*f-contig*=*/A.device().type() != at::kMPS); + set_output_strided(0, sizes, LU_strides, A.options()); + + // Set sizes to the size of pivots + sizes.pop_back(); + sizes.back() = std::min(m, n); + set_output_contiguous(1, sizes, A.options().dtype(kInt)); + + // Set sizes to the size of info + sizes.pop_back(); + set_output_contiguous(2, sizes, A.options().dtype(kInt)); +} + +TORCH_META_FUNC(linalg_lu_solve)(const Tensor& LU, + const Tensor& pivots, + const Tensor& B, + bool left, + bool adjoint) { + // dtype + at::native::checkFloatingOrComplex(LU, "torch.linalg.lu_solve"); + TORCH_CHECK(LU.scalar_type() == B.scalar_type(), + "linalg.lu_solve: Expected LU and B to have the same dtype, but found LU of type ", + LU.scalar_type(), " and B of type ", B.scalar_type(), " instead"); + TORCH_CHECK(pivots.dtype() == at::kInt, + "linalg.lu_solve: pivots should be a Tensor of scalar type torch.int32"); + + // matrix shapes + at::native::squareCheckInputs(LU, "torch.linalg.lu_solve"); + at::native::checkInputsSolver(LU, B, left, "linalg.lu_solve"); + // + TORCH_CHECK(LU.size(-1) == pivots.size(-1), + "linalg.lu_solve: Number of pivots per batch should be same as the dimension of the matrix"); + + // batches + TORCH_CHECK( + LU.sizes().slice(0, LU.dim() - 1).equals(pivots.sizes()), + "linalg.lu_solve: Expected LU.shape[:-1] and pivots.shape to be the same, but got pivots with shape ", + pivots.sizes(), " instead"); + + // This one checks that B can be broadcasted to the shape of A + auto B_broadcast_size = std::get<0>(at::native::_linalg_broadcast_batch_dims(B, LU)); + auto result_strides = at::native::batched_matrix_contiguous_strides(B_broadcast_size, /*f_contig=*/left); + + set_output_strided(0, B_broadcast_size, result_strides, B.options()); +} + +TORCH_META_FUNC(linalg_cholesky_ex)(const Tensor& A, + bool upper, + bool check_errors) { + at::native::squareCheckInputs(A, "linalg.cholesky"); + at::native::checkFloatingOrComplex(A, "linalg.cholesky"); + + auto A_shape = A.sizes(); + auto ndim = A_shape.size(); + + // L + auto L_strides = at::native::batched_matrix_contiguous_strides(A_shape, /*f-contig*=*/true); + set_output_strided(0, A_shape, L_strides, A.options()); + + // info + set_output_contiguous(1, A_shape.slice(0, ndim - 2), A.options().dtype(ScalarType::Int)); +} + +TORCH_META_FUNC(linalg_qr)(const Tensor& A, + std::string_view mode) { + at::native::checkIsMatrix(A, "linalg.qr"); + at::native::checkFloatingOrComplex(A, "linalg.qr"); + auto [compute_q, reduced_mode] = at::native::_parse_qr_mode(mode); + + auto A_shape = A.sizes().vec(); + const auto m = A_shape.cend()[-2]; + const auto n = A_shape.cend()[-1]; + const auto k = std::min(m, n); + + if (compute_q) { + auto Q_shape = A_shape; + Q_shape.end()[-1] = reduced_mode ? k : m; + auto Q_strides = at::native::batched_matrix_contiguous_strides(Q_shape, /*f-contig*=*/true); + set_output_strided(0, Q_shape, Q_strides, A.options()); + } else { + set_output_raw_strided(0, {0}, {}, A.options()); + } + + // For readability + auto R_shape = std::move(A_shape); + R_shape.end()[-2] = (reduced_mode || !compute_q) ? k : m; + auto R_strides = at::native::batched_matrix_contiguous_strides(R_shape, /*f-contig*=*/true); + set_output_strided(1, R_shape, R_strides, A.options()); +} + +TORCH_META_FUNC(linalg_polar)(const Tensor& A) { + at::native::checkIsMatrix(A, "linalg.polar"); + at::native::checkFloatingOrComplex(A, "linalg.polar"); + + // Use a symbolic comparison for the shape check so a dynamic (exported / + // compiled) row dimension is not specialized to a constant here. Output + // allocation below uses the concrete sizes, matching linalg_qr / _linalg_svd. + const auto sym_m = A.sym_size(-2); + const auto sym_n = A.sym_size(-1); + TORCH_SYM_CHECK( + sym_m.sym_ge(sym_n), + "linalg.polar: input must have at least as many rows as columns, but got ", + sym_m, " by ", sym_n, " matrices"); + + auto A_shape = A.sizes().vec(); + const auto n = A_shape.cend()[-1]; + + // U has the same shape as A; H is the (n x n) symmetric/Hermitian factor. + // Both are row-major contiguous: the SVD-based kernel and the CUDA override + // both materialize contiguous outputs, so the meta must promise the same + // layout (otherwise compiled/exported graphs would assume the wrong strides). + set_output_contiguous(0, A_shape, A.options()); + + auto H_shape = std::move(A_shape); + H_shape.end()[-2] = n; + set_output_contiguous(1, H_shape, A.options()); +} + +TORCH_META_FUNC(_linalg_svd)(const Tensor& A, + bool full_matrices, + bool compute_uv, + std::optional driver) { + at::native::checkIsMatrix(A, "linalg.svd"); + at::native::checkFloatingOrComplex(A, "linalg.svd"); + + auto sizes = A.sizes().vec(); + const auto m = sizes.cend()[-2]; + const auto n = sizes.cend()[-1]; + const auto k = std::min(m, n); + + // Prepare sizes for U + if (compute_uv) { + sizes.back() = full_matrices ? m : k; + auto U_strides = at::native::batched_matrix_contiguous_strides(sizes, /*f-contig*=*/true); + set_output_strided(0, sizes, U_strides, A.options()); + + // Prepare sizes for Vh + sizes.end()[-2] = full_matrices ? n : k; + sizes.end()[-1] = n; + + // We need to distinguish the cuSOLVER case, as the cuSOLVER algorithms we use + // expect F-contig matrices, but they compute V rather than Vh + const bool use_cusolver = at::native::svd_uses_cusolver(A); + auto Vh_strides = at::native::batched_matrix_contiguous_strides(sizes, /*f-contig*=*/!use_cusolver); + set_output_strided(2, sizes, Vh_strides, A.options()); + } else { + set_output_raw_strided(0, {0}, {}, A.options()); + set_output_raw_strided(2, {0}, {}, A.options()); + } + + // Prepare sizes for S. S is always real, even when A is complex. + sizes.pop_back(); + sizes.end()[-1] = k; + set_output_contiguous(1, sizes, A.options().dtype(c10::toRealValueType(A.scalar_type()))); +} + +TORCH_META_FUNC(lu_unpack)(const Tensor& LU, const Tensor& pivots, bool unpack_data, bool unpack_pivots) { + TORCH_CHECK(LU.dim() >= 2, "torch.lu_unpack: Expected tensor with 2 or more dimensions. Got size: ", LU.sizes(), " instead"); + if (unpack_pivots) { + TORCH_CHECK(pivots.scalar_type() == at::kInt, + "torch.lu_unpack: LU_pivots is expected to be a contiguous tensor of torch.int32 dtype.\n" + "Note: this function is intended to be used with the output produced by torch.linalg.lu_factor"); + } + + auto sizes = LU.sizes().vec(); + const auto m = sizes.cend()[-2]; + const auto n = sizes.cend()[-1]; + const auto k = std::min(m, n); + + if (unpack_pivots) { + // pivots is produced by lu_factor and must have shape (*LU.shape[:-2], min(m, n)). + // Without this check, a mismatched pivots tensor leads to out-of-bounds reads in + // the unpack_pivots kernel. + auto expected_pivots_sizes = LU.sizes().vec(); + expected_pivots_sizes.pop_back(); + expected_pivots_sizes.back() = k; + TORCH_CHECK_VALUE(pivots.sizes() == IntArrayRef(expected_pivots_sizes), + "Expected LU_pivots to have shape ", IntArrayRef(expected_pivots_sizes), + " but got ", pivots.sizes(), " instead."); + } + + // P.shape[-2:] == (m, m) (or size zero if pivot == False) + sizes.end()[-1] = m; + if (unpack_pivots) { + set_output_raw_strided(0, sizes, {}, LU.options()); + } else { + set_output_raw_strided(0, {0}, {}, LU.options()); + } + + if (unpack_data) { + // L.shape[-2:] == (m, k) + sizes.end()[-1] = k; + set_output_raw_strided(1, sizes, {}, LU.options()); + + // U.shape[-2:] == (k, n) + sizes.end()[-2] = k; + sizes.end()[-1] = n; + set_output_raw_strided(2, sizes, {}, LU.options()); + } else { + set_output_raw_strided(1, {0}, {}, LU.options()); + set_output_raw_strided(2, {0}, {}, LU.options()); + } +} + +TORCH_META_FUNC(_linalg_eigh)(const Tensor& A, + std::string_view uplo, + bool compute_v) { + at::native::squareCheckInputs(A, "linalg.eigh"); + at::native::checkUplo(uplo); + + auto shape = A.sizes().vec(); + if (compute_v) { + // eigenvectors + auto V_strides = at::native::batched_matrix_contiguous_strides(shape, /*f-contig*=*/true); + set_output_strided(1, shape, V_strides, A.options()); + } else { + set_output_raw_strided(1, {0}, {}, A.options()); + } + + // eigenvalues + shape.pop_back(); + set_output_contiguous(0, shape, A.options().dtype(c10::toRealValueType(A.scalar_type()))); +} + +TORCH_META_FUNC(linalg_lu)(const Tensor& A, bool pivot) { + TORCH_CHECK(A.dim() >= 2, "linalg.lu: Expected tensor with 2 or more dimensions. Got size: ", A.sizes(), " instead"); + + auto sizes = A.sizes().vec(); + const auto m = sizes.cend()[-2]; + const auto n = sizes.cend()[-1]; + const auto k = std::min(m, n); + + // P.shape[-2:] == (m, m) (or size zero if pivot == False) + sizes.end()[-1] = m; + if (pivot) { + set_output_raw_strided(0, sizes, {}, A.options()); + } else { + set_output_raw_strided(0, {0}, {}, A.options()); + } + + // L.shape[-2:] == (m, k) + sizes.end()[-1] = k; + set_output_raw_strided(1, sizes, {}, A.options()); + + // U.shape[-2:] == (k, n) + sizes.end()[-2] = k; + sizes.end()[-1] = n; + set_output_raw_strided(2, sizes, {}, A.options()); +} + +} // namespace at::meta + +namespace at::native { + +#if AT_BUILD_WITH_LAPACK() +// Define the per-batch functions to be used in the main implementation of the batched +// linear algebra operations + +template +static void lapackCholeskySolve(char uplo, int n, int nrhs, scalar_t *a, int lda, scalar_t *b, int ldb, int *info); + +template<> void lapackLu>(int m, int n, c10::complex *a, int lda, int *ipiv, int *info) { + zgetrf_(&m, &n, reinterpret_cast*>(a), &lda, ipiv, info); +} + +template<> void lapackLu>(int m, int n, c10::complex *a, int lda, int *ipiv, int *info) { + cgetrf_(&m, &n, reinterpret_cast*>(a), &lda, ipiv, info); +} + +template<> void lapackLu(int m, int n, double *a, int lda, int *ipiv, int *info) { + dgetrf_(&m, &n, a, &lda, ipiv, info); +} + +template<> void lapackLu(int m, int n, float *a, int lda, int *ipiv, int *info) { + sgetrf_(&m, &n, a, &lda, ipiv, info); +} + +template<> void lapackCholeskySolve>(char uplo, int n, int nrhs, c10::complex *a, int lda, c10::complex *b, int ldb, int *info) { + zpotrs_(&uplo, &n, &nrhs, reinterpret_cast*>(a), &lda, reinterpret_cast*>(b), &ldb, info); +} + +template<> void lapackCholeskySolve>(char uplo, int n, int nrhs, c10::complex *a, int lda, c10::complex *b, int ldb, int *info) { + cpotrs_(&uplo, &n, &nrhs, reinterpret_cast*>(a), &lda, reinterpret_cast*>(b), &ldb, info); +} + +template<> void lapackCholeskySolve(char uplo, int n, int nrhs, double *a, int lda, double *b, int ldb, int *info) { + dpotrs_(&uplo, &n, &nrhs, a, &lda, b, &ldb, info); +} + +template<> void lapackCholeskySolve(char uplo, int n, int nrhs, float *a, int lda, float *b, int ldb, int *info) { + spotrs_(&uplo, &n, &nrhs, a, &lda, b, &ldb, info); +} + +template<> void lapackCholesky>(char uplo, int n, c10::complex *a, int lda, int *info) { + zpotrf_(&uplo, &n, reinterpret_cast*>(a), &lda, info); +} + +template<> void lapackCholesky>(char uplo, int n, c10::complex *a, int lda, int *info) { + cpotrf_(&uplo, &n, reinterpret_cast*>(a), &lda, info); +} + +template<> void lapackCholesky(char uplo, int n, double *a, int lda, int *info) { + dpotrf_(&uplo, &n, a, &lda, info); +} + +template<> void lapackCholesky(char uplo, int n, float *a, int lda, int *info) { + spotrf_(&uplo, &n, a, &lda, info); +} + +template<> void lapackCholeskyInverse>(char uplo, int n, c10::complex *a, int lda, int *info) { + zpotri_(&uplo, &n, reinterpret_cast*>(a), &lda, info); +} + +template<> void lapackCholeskyInverse>(char uplo, int n, c10::complex *a, int lda, int *info) { + cpotri_(&uplo, &n, reinterpret_cast*>(a), &lda, info); +} + +template<> void lapackCholeskyInverse(char uplo, int n, double *a, int lda, int *info) { + dpotri_(&uplo, &n, a, &lda, info); +} + +template<> void lapackCholeskyInverse(char uplo, int n, float *a, int lda, int *info) { + spotri_(&uplo, &n, a, &lda, info); +} + +template<> void lapackGeqrf>(int m, int n, c10::complex *a, int lda, c10::complex *tau, c10::complex *work, int lwork, int *info) { + zgeqrf_(&m, &n, reinterpret_cast*>(a), &lda, reinterpret_cast*>(tau), reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackGeqrf>(int m, int n, c10::complex *a, int lda, c10::complex *tau, c10::complex *work, int lwork, int *info) { + cgeqrf_(&m, &n, reinterpret_cast*>(a), &lda, reinterpret_cast*>(tau), reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackGeqrf(int m, int n, double *a, int lda, double *tau, double *work, int lwork, int *info) { + dgeqrf_(&m, &n, a, &lda, tau, work, &lwork, info); +} + +template<> void lapackGeqrf(int m, int n, float *a, int lda, float *tau, float *work, int lwork, int *info) { + sgeqrf_(&m, &n, a, &lda, tau, work, &lwork, info); +} + +template<> void lapackOrgqr>(int m, int n, int k, c10::complex *a, int lda, c10::complex *tau, c10::complex *work, int lwork, int *info) { + zungqr_(&m, &n, &k, reinterpret_cast*>(a), &lda, reinterpret_cast*>(tau), reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackOrgqr>(int m, int n, int k, c10::complex *a, int lda, c10::complex *tau, c10::complex *work, int lwork, int *info) { + cungqr_(&m, &n, &k, reinterpret_cast*>(a), &lda, reinterpret_cast*>(tau), reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackOrgqr(int m, int n, int k, double *a, int lda, double *tau, double *work, int lwork, int *info) { + dorgqr_(&m, &n, &k, a, &lda, tau, work, &lwork, info); +} + +template<> void lapackOrgqr(int m, int n, int k, float *a, int lda, float *tau, float *work, int lwork, int *info) { + sorgqr_(&m, &n, &k, a, &lda, tau, work, &lwork, info); +} + +template<> void lapackOrmqr>(char side, char trans, int m, int n, int k, c10::complex *a, int lda, c10::complex *tau, c10::complex *c, int ldc, c10::complex *work, int lwork, int *info) { + zunmqr_(&side, &trans, &m, &n, &k, reinterpret_cast*>(a), &lda, reinterpret_cast*>(tau), reinterpret_cast*>(c), &ldc, reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackOrmqr>(char side, char trans, int m, int n, int k, c10::complex *a, int lda, c10::complex *tau, c10::complex *c, int ldc, c10::complex *work, int lwork, int *info) { + cunmqr_(&side, &trans, &m, &n, &k, reinterpret_cast*>(a), &lda, reinterpret_cast*>(tau), reinterpret_cast*>(c), &ldc, reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackOrmqr(char side, char trans, int m, int n, int k, double *a, int lda, double *tau, double *c, int ldc, double *work, int lwork, int *info) { + dormqr_(&side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, work, &lwork, info); +} + +template<> void lapackOrmqr(char side, char trans, int m, int n, int k, float *a, int lda, float *tau, float *c, int ldc, float *work, int lwork, int *info) { + sormqr_(&side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, work, &lwork, info); +} + +template<> void lapackSyevd, double>(char jobz, char uplo, int n, c10::complex *a, int lda, double *w, c10::complex *work, int lwork, double *rwork, int lrwork, int *iwork, int liwork, int *info) { + zheevd_(&jobz, &uplo, &n, reinterpret_cast*>(a), &lda, w, reinterpret_cast*>(work), &lwork, rwork, &lrwork, iwork, &liwork, info); +} + +template<> void lapackSyevd, float>(char jobz, char uplo, int n, c10::complex *a, int lda, float *w, c10::complex *work, int lwork, float *rwork, int lrwork, int *iwork, int liwork, int *info) { + cheevd_(&jobz, &uplo, &n, reinterpret_cast*>(a), &lda, w, reinterpret_cast*>(work), &lwork, rwork, &lrwork, iwork, &liwork, info); +} + +template<> void lapackSyevd(char jobz, char uplo, int n, double *a, int lda, double *w, double *work, int lwork, double *rwork, int lrwork, int *iwork, int liwork, int *info) { + (void)rwork; // unused + (void)lrwork; // unused + dsyevd_(&jobz, &uplo, &n, a, &lda, w, work, &lwork, iwork, &liwork, info); +} + +template<> void lapackSyevd(char jobz, char uplo, int n, float *a, int lda, float *w, float *work, int lwork, float *rwork, int lrwork, int *iwork, int liwork, int *info) { + (void)rwork; // unused + (void)lrwork; // unused + ssyevd_(&jobz, &uplo, &n, a, &lda, w, work, &lwork, iwork, &liwork, info); +} + +template<> void lapackEig(char jobvl, char jobvr, int n, double *a, int lda, double *w, double* vl, int ldvl, double *vr, int ldvr, double *work, int lwork, double *rwork, int *info) { + // lapack [sd]geev wants to separate output arrays: wr and wi for the real + // and imaginary parts + double *wr = w; + double *wi = w ? w + n : nullptr; + (void)rwork; // unused + dgeev_(&jobvl, &jobvr, &n, a, &lda, wr, wi, vl, &ldvl, vr, &ldvr, work, &lwork, info); +} + +template<> void lapackEig(char jobvl, char jobvr, int n, float *a, int lda, float *w, float* vl, int ldvl, float *vr, int ldvr, float *work, int lwork, float *rwork, int *info) { + // lapack [sd]geev wants to separate output arrays: wr and wi for the real + // and imaginary parts + float *wr = w; + float *wi = w ? w + n : nullptr; + (void)rwork; // unused + sgeev_(&jobvl, &jobvr, &n, a, &lda, wr, wi, vl, &ldvl, vr, &ldvr, work, &lwork, info); +} + +template<> void lapackEig, double>(char jobvl, char jobvr, int n, c10::complex *a, int lda, c10::complex *w, c10::complex *vl, int ldvl, c10::complex *vr, int ldvr, c10::complex *work, int lwork, double *rwork, int *info) { + zgeev_(&jobvl, &jobvr, &n, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(w), + reinterpret_cast*>(vl), &ldvl, + reinterpret_cast*>(vr), &ldvr, + reinterpret_cast*>(work), &lwork, + rwork, info); +} + +template<> void lapackEig, float>(char jobvl, char jobvr, int n, c10::complex *a, int lda, c10::complex *w, c10::complex *vl, int ldvl, c10::complex *vr, int ldvr, c10::complex *work, int lwork, float *rwork, int *info) { + cgeev_(&jobvl, &jobvr, &n, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(w), + reinterpret_cast*>(vl), &ldvl, + reinterpret_cast*>(vr), &ldvr, + reinterpret_cast*>(work), &lwork, + rwork, info); +} + +template<> void lapackSvd, double>(char jobz, int m, int n, c10::complex *a, int lda, + double *s, c10::complex *u, int ldu, c10::complex *vt, int ldvt, c10::complex *work, int lwork, double *rwork, int *iwork, int *info) { + zgesdd_(&jobz, &m, &n, reinterpret_cast*>(a), &lda, s, reinterpret_cast*>(u), &ldu, + reinterpret_cast*>(vt), &ldvt, reinterpret_cast*>(work), &lwork, rwork, iwork, info); +} + +template<> void lapackSvd, float>(char jobz, int m, int n, c10::complex *a, int lda, + float *s, c10::complex *u, int ldu, c10::complex *vt, int ldvt, c10::complex *work, int lwork, float *rwork, int *iwork, int *info) { + cgesdd_(&jobz, &m, &n, reinterpret_cast*>(a), &lda, s, reinterpret_cast*>(u), &ldu, + reinterpret_cast*>(vt), &ldvt, reinterpret_cast*>(work), &lwork, rwork, iwork, info); +} + +template<> void lapackSvd(char jobz, int m, int n, double *a, int lda, + double *s, double *u, int ldu, double *vt, int ldvt, double *work, int lwork, double *rwork, int *iwork, int *info) { + dgesdd_(&jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, iwork, info); +} + +template<> void lapackSvd(char jobz, int m, int n, float *a, int lda, + float *s, float *u, int ldu, float *vt, int ldvt, float *work, int lwork, float *rwork, int *iwork, int *info) { + sgesdd_(&jobz, &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork, iwork, info); +} + +template <> +void lapackLdlSymmetric( + char uplo, + int n, + double* a, + int lda, + int* ipiv, + double* work, + int lwork, + int* info) { + dsytrf_(&uplo, &n, a, &lda, ipiv, work, &lwork, info); +} + +template <> +void lapackLdlSymmetric( + char uplo, + int n, + float* a, + int lda, + int* ipiv, + float* work, + int lwork, + int* info) { + ssytrf_(&uplo, &n, a, &lda, ipiv, work, &lwork, info); +} + +template <> +void lapackLdlSymmetric>( + char uplo, + int n, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* work, + int lwork, + int* info) { + zsytrf_( + &uplo, + &n, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(work), + &lwork, + info); +} + +template <> +void lapackLdlSymmetric>( + char uplo, + int n, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* work, + int lwork, + int* info) { + csytrf_( + &uplo, + &n, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(work), + &lwork, + info); +} + +template <> +void lapackLdlHermitian( + char uplo, + int n, + double* a, + int lda, + int* ipiv, + double* work, + int lwork, + int* info) { + dsytrf_(&uplo, &n, a, &lda, ipiv, work, &lwork, info); +} + +template <> +void lapackLdlHermitian( + char uplo, + int n, + float* a, + int lda, + int* ipiv, + float* work, + int lwork, + int* info) { + ssytrf_(&uplo, &n, a, &lda, ipiv, work, &lwork, info); +} + +template <> +void lapackLdlHermitian>( + char uplo, + int n, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* work, + int lwork, + int* info) { + zhetrf_( + &uplo, + &n, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(work), + &lwork, + info); +} + +template <> +void lapackLdlHermitian>( + char uplo, + int n, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* work, + int lwork, + int* info) { + chetrf_( + &uplo, + &n, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(work), + &lwork, + info); +} + +template <> +void lapackLdlSolveSymmetric( + char uplo, + int n, + int nrhs, + double* a, + int lda, + int* ipiv, + double* b, + int ldb, + int* info) { + dsytrs_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, info); +} + +template <> +void lapackLdlSolveSymmetric( + char uplo, + int n, + int nrhs, + float* a, + int lda, + int* ipiv, + float* b, + int ldb, + int* info) { + ssytrs_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, info); +} + +template <> +void lapackLdlSolveSymmetric>( + char uplo, + int n, + int nrhs, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* b, + int ldb, + int* info) { + zsytrs_( + &uplo, + &n, + &nrhs, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(b), + &ldb, + info); +} + +template <> +void lapackLdlSolveSymmetric>( + char uplo, + int n, + int nrhs, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* b, + int ldb, + int* info) { + csytrs_( + &uplo, + &n, + &nrhs, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(b), + &ldb, + info); +} + +template <> +void lapackLdlSolveHermitian( + char uplo, + int n, + int nrhs, + double* a, + int lda, + int* ipiv, + double* b, + int ldb, + int* info) { + dsytrs_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, info); +} + +template <> +void lapackLdlSolveHermitian( + char uplo, + int n, + int nrhs, + float* a, + int lda, + int* ipiv, + float* b, + int ldb, + int* info) { + ssytrs_(&uplo, &n, &nrhs, a, &lda, ipiv, b, &ldb, info); +} + +template <> +void lapackLdlSolveHermitian>( + char uplo, + int n, + int nrhs, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* b, + int ldb, + int* info) { + zhetrs_( + &uplo, + &n, + &nrhs, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(b), + &ldb, + info); +} + +template <> +void lapackLdlSolveHermitian>( + char uplo, + int n, + int nrhs, + c10::complex* a, + int lda, + int* ipiv, + c10::complex* b, + int ldb, + int* info) { + chetrs_( + &uplo, + &n, + &nrhs, + reinterpret_cast*>(a), + &lda, + ipiv, + reinterpret_cast*>(b), + &ldb, + info); +} + +template<> void lapackLuSolve>(char trans, int n, int nrhs, c10::complex *a, int lda, int *ipiv, c10::complex *b, int ldb, int *info) { + zgetrs_(&trans, &n, &nrhs, reinterpret_cast*>(a), &lda, ipiv, reinterpret_cast*>(b), &ldb, info); +} + +template<> void lapackLuSolve>(char trans, int n, int nrhs, c10::complex *a, int lda, int *ipiv, c10::complex *b, int ldb, int *info) { + cgetrs_(&trans, &n, &nrhs, reinterpret_cast*>(a), &lda, ipiv, reinterpret_cast*>(b), &ldb, info); +} + +template<> void lapackLuSolve(char trans, int n, int nrhs, double *a, int lda, int *ipiv, double *b, int ldb, int *info) { + dgetrs_(&trans, &n, &nrhs, a, &lda, ipiv, b, &ldb, info); +} + +template<> void lapackLuSolve(char trans, int n, int nrhs, float *a, int lda, int *ipiv, float *b, int ldb, int *info) { + sgetrs_(&trans, &n, &nrhs, a, &lda, ipiv, b, &ldb, info); +} + +template<> void lapackGels>( + char trans, int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + c10::complex *work, int lwork, int *info) { + zgels_(&trans, &m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackGels>( + char trans, int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + c10::complex *work, int lwork, int *info) { + cgels_(&trans, &m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + reinterpret_cast*>(work), &lwork, info); +} + +template<> void lapackGels( + char trans, int m, int n, int nrhs, + double *a, int lda, double *b, int ldb, + double *work, int lwork, int *info) { + dgels_(&trans, &m, &n, &nrhs, + a, &lda, b, &ldb, work, &lwork, info); +} + +template<> void lapackGels( + char trans, int m, int n, int nrhs, + float *a, int lda, float *b, int ldb, + float *work, int lwork, int *info) { + sgels_(&trans, &m, &n, &nrhs, + a, &lda, b, &ldb, work, &lwork, info); +} + +template<> void lapackGelsd, double>( + int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + double *s, double rcond, int *rank, + c10::complex *work, int lwork, + double *rwork, int *iwork, int *info) { + zgelsd_(&m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + s, &rcond, rank, + reinterpret_cast*>(work), &lwork, + rwork, iwork, info); +} + +template<> void lapackGelsd, float>( + int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + float *s, float rcond, int *rank, + c10::complex *work, int lwork, + float *rwork, int *iwork, int *info) { + cgelsd_(&m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + s, &rcond, rank, + reinterpret_cast*>(work), &lwork, + rwork, iwork, info); +} + +template<> void lapackGelsd( + int m, int n, int nrhs, + double *a, int lda, double *b, int ldb, + double *s, double rcond, int *rank, + double *work, int lwork, + double *rwork, int *iwork, int *info) { + dgelsd_(&m, &n, &nrhs, + a, &lda, b, &ldb, + s, &rcond, rank, + work, &lwork, iwork, info); +} + +template<> void lapackGelsd( + int m, int n, int nrhs, + float *a, int lda, float *b, int ldb, + float *s, float rcond, int *rank, + float *work, int lwork, + float *rwork, int *iwork, int *info) { + sgelsd_(&m, &n, &nrhs, + a, &lda, b, &ldb, + s, &rcond, rank, + work, &lwork, iwork, info); +} + +template<> void lapackGelsy, double>( + int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + int *jpvt, double rcond, int *rank, + c10::complex *work, int lwork, double *rwork, int *info) { + zgelsy_(&m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + jpvt, &rcond, rank, + reinterpret_cast*>(work), &lwork, + rwork, info); +} + +template<> void lapackGelsy, float>( + int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + int *jpvt, float rcond, int *rank, + c10::complex *work, int lwork, float *rwork, int *info) { + cgelsy_(&m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + jpvt, &rcond, rank, + reinterpret_cast*>(work), &lwork, + rwork, info); +} + +template<> void lapackGelsy( + int m, int n, int nrhs, + double *a, int lda, double *b, int ldb, + int *jpvt, double rcond, int *rank, + double *work, int lwork, double *rwork, int *info) { + dgelsy_(&m, &n, &nrhs, + a, &lda, b, &ldb, + jpvt, &rcond, rank, + work, &lwork, info); +} + +template<> void lapackGelsy( + int m, int n, int nrhs, + float *a, int lda, float *b, int ldb, + int *jpvt, float rcond, int *rank, + float *work, int lwork, float *rwork, int *info) { + sgelsy_(&m, &n, &nrhs, + a, &lda, b, &ldb, + jpvt, &rcond, rank, + work, &lwork, info); +} + +template<> void lapackGelss, double>( + int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + double *s, double rcond, int *rank, + c10::complex *work, int lwork, + double *rwork, int *info + ) { + zgelss_(&m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + s, &rcond, rank, + reinterpret_cast*>(work), &lwork, + rwork, info); +} + +template<> void lapackGelss, float>( + int m, int n, int nrhs, + c10::complex *a, int lda, c10::complex *b, int ldb, + float *s, float rcond, int *rank, + c10::complex *work, int lwork, + float *rwork, int *info + ) { + cgelss_(&m, &n, &nrhs, + reinterpret_cast*>(a), &lda, + reinterpret_cast*>(b), &ldb, + s, &rcond, rank, + reinterpret_cast*>(work), &lwork, + rwork, info); +} + +template<> void lapackGelss( + int m, int n, int nrhs, + double *a, int lda, double *b, int ldb, + double *s, double rcond, int *rank, + double *work, int lwork, + double *rwork, int *info) { + dgelss_(&m, &n, &nrhs, + a, &lda, b, &ldb, + s, &rcond, rank, + work, &lwork, info); +} + +template<> void lapackGelss( + int m, int n, int nrhs, + float *a, int lda, float *b, int ldb, + float *s, float rcond, int *rank, + float *work, int lwork, + float *rwork, int *info) { + sgelss_(&m, &n, &nrhs, + a, &lda, b, &ldb, + s, &rcond, rank, + work, &lwork, info); +} +#endif + +#if AT_BUILD_WITH_BLAS() +template<> void blasTriangularSolve>(char side, char uplo, char trans, char diag, int n, int nrhs, c10::complex *a, int lda, c10::complex *b, int ldb) { + std::complex one{1., 0.}; + ztrsm_(&side, &uplo, &trans, &diag, &n, &nrhs, &one, reinterpret_cast*>(a), &lda, reinterpret_cast*>(b), &ldb); +} + +template<> void blasTriangularSolve>(char side, char uplo, char trans, char diag, int n, int nrhs, c10::complex *a, int lda, c10::complex *b, int ldb) { + std::complex one{1.f, 0.f}; + ctrsm_(&side, &uplo, &trans, &diag, &n, &nrhs, &one, reinterpret_cast*>(a), &lda, reinterpret_cast*>(b), &ldb); +} + +template<> void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, double *a, int lda, double *b, int ldb) { + auto one = 1.; + dtrsm_(&side, &uplo, &trans, &diag, &n, &nrhs, &one, a, &lda, b, &ldb); +} + +template<> void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, float *a, int lda, float *b, int ldb) { + auto one = 1.f; + strsm_(&side, &uplo, &trans, &diag, &n, &nrhs, &one, a, &lda, b, &ldb); +} +#endif + +void _linalg_check_errors( + const Tensor& infos, + const std::string_view api_name, + bool is_matrix) { + TORCH_INTERNAL_ASSERT(infos.scalar_type() == kInt); + TORCH_INTERNAL_ASSERT(infos.is_contiguous()); + if (infos.is_meta()) { + return; + } + + // If it's all zeros, we return early. + // We optimise for the most likely case. + if (C10_LIKELY(!infos.any().item())) { + return; + } + + int32_t info = 0; + std::string batch_str; + if (is_matrix) { + info = infos.item(); + // batch_str needn't be set for matrices + } else { + // Find the first non-zero info + auto infos_cpu = infos.to(at::kCPU); + auto ptr = infos_cpu.const_data_ptr(); + auto n = infos.numel(); + auto info_ptr = std::find_if(ptr, ptr + n, [](int32_t x) { return x != 0; }); + info = *info_ptr; + batch_str = ": (Batch element " + std::to_string(std::distance(ptr, info_ptr)) + ")"; + } + + if (info < 0) { + // Reference LAPACK 3.10+ changed `info` behavior for inputs with non-finite values + // Previously, it would return `info` > 0, but now it returns `info` = -4 + // OpenBLAS 0.3.15+ uses the Reference LAPACK 3.10+. + // MKL 2022.0+ uses the Reference LAPACK 3.10+. + // Older version of MKL and OpenBLAS follow the old behavior (return `info` > 0). + // Here we check for the case where `info` is -4 and raise an error + if (api_name.find("svd") != api_name.npos) { + TORCH_CHECK_LINALG(info != -4, api_name, batch_str, + ": The algorithm failed to converge because the input matrix contained non-finite values."); + } + TORCH_INTERNAL_ASSERT(false, api_name, batch_str, + ": Argument ", -info, " has illegal value. Most certainly there is a bug in the implementation calling the backend library."); + } else if (info > 0) { + if (api_name.find("inv") != api_name.npos) { + // inv, inverse, cholesky_inverse, etc. + TORCH_CHECK_LINALG(false, api_name, batch_str, + ": The diagonal element ", info, " is zero, the inversion could not be completed because the input matrix is singular."); + } else if (api_name.find("solve") != api_name.npos) { + // solve, linalg_solve, cholesky_solve, etc. + TORCH_CHECK_LINALG(false, api_name, batch_str, + ": The solver failed because the input matrix is singular."); + } else if (api_name.find("cholesky") != api_name.npos) { + TORCH_CHECK_LINALG(false, api_name, batch_str, + ": The factorization could not be completed because the input is not positive-definite (the leading minor of order ", info, " is not positive-definite)."); + } else if (api_name.find("svd") != api_name.npos) { + TORCH_CHECK_LINALG(false, api_name, batch_str, + ": The algorithm failed to converge because the input matrix is ill-conditioned or has too many repeated singular values (error code: ", info, ")."); + } else if (api_name.find("eig") != api_name.npos || api_name.find("syevd") != api_name.npos) { + TORCH_CHECK_LINALG(false, api_name, batch_str, + ": The algorithm failed to converge because the input matrix is ill-conditioned or has too many repeated eigenvalues (error code: ", info, ")."); + } else if (api_name.find("lstsq") != api_name.npos) { + TORCH_CHECK_LINALG(false, api_name, batch_str, + ": The least squares solution could not be computed because the input matrix does not have full rank (error code: ", info, ")."); + } else if (api_name.find("lu_factor") != api_name.npos) { + TORCH_CHECK(false, api_name, batch_str, + ": U[", info, ",", info, "] is zero and using it on lu_solve would result in a division by zero. " + "If you still want to perform the factorization, consider calling linalg.lu(A, pivot) or " + "linalg.lu_factor_ex(A, pivot)"); + } else { + TORCH_INTERNAL_ASSERT(false, api_name, ": Unknown error code: ", info, "."); + } + } + // We should never reach this point as info was non-zero + TORCH_INTERNAL_ASSERT(false); +} + +// If an input requires fw or bw grad then we need to go down a different +// (slower) path to ensure that the gradients are computable. +// That is what `_may_require_fw_or_bw_grad` is helpful for. +// +// Why is there a isTensorSubclassLike check here? +// Without it, this function can lead to composite compliance problems, which +// may lead to bugs in functorch, where a Tensor Subclass that doesn't +// require grad may wrap a Tensor subclass that requires grad. +static bool _may_require_fw_or_bw_grad(const Tensor& input) { + return ((at::GradMode::is_enabled() && input.requires_grad()) + || input._fw_grad(/*level */ 0).defined() + || isTensorSubclassLike(input)); +} + +// NOLINTBEGIN(cppcoreguidelines-pro-type-const-cast) + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg.inv ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +TORCH_IMPL_FUNC(linalg_inv_ex_out)(const Tensor& A, bool check_errors, const Tensor& result, const Tensor& info) { + // Fill result with the identity + result.zero_(); + result.diagonal(0, -2, -1).fill_(1.); + at::linalg_solve_ex_out(const_cast(result), const_cast(info), A, result, /*left*/true); + if (check_errors) { + at::_linalg_check_errors(info, "linalg.inv_ex", A.dim() == 2); + } +} + +Tensor& linalg_inv_out(const Tensor& A, Tensor& result) { + auto info = at::empty({0}, A.options().dtype(kInt)); + at::linalg_inv_ex_out(result, info, A); + at::_linalg_check_errors(info, "linalg.inv", A.dim() == 2); + return result; +} + +Tensor linalg_inv(const Tensor& A) { + auto [result, info] = at::linalg_inv_ex(A); + at::_linalg_check_errors(info, "linalg.inv", A.dim() == 2); + return result; +} + +Tensor& inverse_out(const Tensor& A, Tensor& result) { + return at::linalg_inv_out(result, A); +} + +Tensor inverse(const Tensor& A) { + return at::linalg_inv(A); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cholesky_solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +template +static void apply_cholesky_solve(Tensor& b, Tensor& A, bool upper, Tensor& infos) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK(false, "cholesky_solve: LAPACK library not found in compilation"); +#else + char uplo = upper ? 'U' : 'L'; + + auto A_data = A.const_data_ptr(); + auto b_data = b.data_ptr(); + auto infos_data = infos.data_ptr(); + auto A_mat_stride = matrixStride(A); + auto b_mat_stride = matrixStride(b); + auto batch_size = batchCount(A); + auto n = A.size(-2); + auto ldab = std::max(1, n); + auto nrhs = b.size(-1); + + for (const auto i : c10::irange(batch_size)) { + const scalar_t* A_working_ptr = &A_data[i * A_mat_stride]; + scalar_t* b_working_ptr = &b_data[i * b_mat_stride]; + int info = 0; + lapackCholeskySolve(uplo, n, nrhs, const_cast(A_working_ptr), ldab, b_working_ptr, ldab, &info); + infos_data[i] = info; + if (info != 0) { + return; + } + } +#endif +} + +Tensor _cholesky_solve_helper_cpu(const Tensor& self, const Tensor& A, bool upper) { + auto self_working_copy = cloneBatchedColumnMajor(self); + auto A_working_copy = cloneBatchedColumnMajor(A); + auto infos = at::zeros({batchCount(self)}, self.options().dtype(kInt)); + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(self.scalar_type(), "cholesky_solve_cpu", [&]{ + apply_cholesky_solve(self_working_copy, A_working_copy, upper, infos); + }); + + at::_linalg_check_errors(infos, "cholesky_solve_cpu", self.dim() == 2); + return self_working_copy; +} + +// Supports arbitrary batch dimensions for self and A +Tensor cholesky_solve(const Tensor& self, const Tensor& A, bool upper) { + TORCH_CHECK(self.dim() >= 2, + "b should have at least 2 dimensions, but has ", self.dim(), " dimensions instead"); + TORCH_CHECK(A.dim() >= 2, + "u should have at least 2 dimensions, but has ", A.dim(), " dimensions instead"); + auto [self_broadcasted, A_broadcasted] = _linalg_broadcast_batch_dims(self, A, "cholesky_solve"); + return at::_cholesky_solve_helper(self_broadcasted, A_broadcasted, upper); +} + +Tensor& cholesky_solve_out(const Tensor& self, const Tensor& A, bool upper, Tensor& result) { + checkSameDevice("cholesky_solve", result, self); + checkLinalgCompatibleDtype("cholesky_solve", result, self); + Tensor result_tmp = at::cholesky_solve(self, A, upper); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cholesky ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(cholesky_stub); + +TORCH_IMPL_FUNC(linalg_cholesky_ex_out)(const Tensor& A, + bool upper, + bool check_errors, + const Tensor& L, + const Tensor& info) { + // Nothing to do there + if (L.numel() == 0) { + info.zero_(); + return; + } + const auto cpu = A.device() == kCPU; + + // We can perform this optimisation just on CPU as it fails for MAGMA + // due to some bug + if (cpu) { + if (upper) { + at::triu_out(const_cast(L), A); + } else { + at::tril_out(const_cast(L), A); + } + } else { + L.copy_(A); + } + + cholesky_stub(L.device().type(), L, info, upper); + + // On non-CPU devices (MAGMA) the pre-copy doesn't zero the unused triangle, + // so we must clean up after. On macOS, Accelerate's LAPACK writes into the + // unreferenced triangle for matrices larger than its internal block size + // (e.g. n > 64), violating the LAPACK spec which says "not referenced" + // elements are "never read, written to, or otherwise accessed" + // (see https://www.netlib.org/lapack/lug/node121.html). + // We work around this by applying the same cleanup on macOS. + // TODO(https://github.com/pytorch/pytorch/issues/179152): always + // clean up the unused triangle on all platforms. +#if defined(__APPLE__) + constexpr bool needs_triangle_cleanup = true; +#else + const bool needs_triangle_cleanup = !cpu; +#endif + if (needs_triangle_cleanup) { + if (upper) { + L.triu_(); + } else { + L.tril_(); + } + } + + if (check_errors) { + at::_linalg_check_errors(info, "linalg.cholesky_ex", A.dim() == 2); + } +} + +Tensor linalg_cholesky(const Tensor& A, bool upper) { + auto [L, info] = at::linalg_cholesky_ex(A, upper, /*check_errors=*/false); + at::_linalg_check_errors(info, "linalg.cholesky", A.dim() == 2); + return L; +} + +Tensor& linalg_cholesky_out(const Tensor& A, bool upper, Tensor& L) { + auto info = at::empty({0}, A.options().dtype(kInt)); + at::linalg_cholesky_ex_out(L, info, A, upper, /*check_errors=*/false); + at::_linalg_check_errors(info, "linalg.cholesky", A.dim() == 2); + return L; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cholesky_inverse ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(cholesky_inverse_stub); + +static Tensor& cholesky_inverse_out_info(Tensor& result, Tensor& infos, const Tensor& input, bool upper) { + TORCH_INTERNAL_ASSERT(input.dim() >= 2); + TORCH_INTERNAL_ASSERT(input.size(-1) == input.size(-2)); + + TORCH_INTERNAL_ASSERT(result.scalar_type() == input.scalar_type()); + TORCH_INTERNAL_ASSERT(result.device() == input.device()); + + TORCH_INTERNAL_ASSERT(infos.scalar_type() == at::kInt); + TORCH_INTERNAL_ASSERT(infos.device() == at::kCPU); + TORCH_INTERNAL_ASSERT(infos.numel() == std::max(1, batchCount(input))); + + // if result has no elements we can modify it + if (result.numel() == 0) { + at::native::resize_as_(result, input.mT(), MemoryFormat::Contiguous); + result.transpose_(-2, -1); + } + + // result tensor must be in batched column major order (Fortran contiguous) + TORCH_INTERNAL_ASSERT(result.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT(result.sizes().equals(input.sizes())); + + // cholesky_inverse_stub (apply_cholesky_inverse) performs calculations in-place and result must be a copy of input + result.copy_(input); + + // infos must be contiguous + TORCH_INTERNAL_ASSERT(infos.is_contiguous()); + infos.fill_(0); + + result = cholesky_inverse_stub(result.device().type(), result, infos, upper); + return result; +} + +Tensor& cholesky_inverse_out(const Tensor &input, bool upper, Tensor &result) { + squareCheckInputs(input, "cholesky_inverse"); + checkSameDevice("cholesky_inverse", result, input); + checkLinalgCompatibleDtype("cholesky_inverse", result, input); + + // MAGMA requires 'infos' to reside in CPU memory, therefore we create 'infos' only on CPU for now. + auto infos = at::zeros({std::max(1, batchCount(input))}, input.options().dtype(kInt).device(kCPU)); + + bool result_input_same_type = (result.scalar_type() == input.scalar_type()); + bool result_equal_expected_shape = result.sizes().equals(input.sizes()); + bool is_batched_column_major = false; + if (result.dim() >= 2) { + is_batched_column_major = result.mT().is_contiguous(); + } + + // if result is not empty and not in batched column major format + bool copy_needed = (result.numel() != 0 && !is_batched_column_major); + copy_needed |= !result_input_same_type; // or result does not have the same dtype as input + copy_needed |= (result.numel() != 0 && !result_equal_expected_shape); // or result does not have the expected shape + // we have to allocate a temporary tensor + if (copy_needed) { + Tensor result_tmp = at::empty({0}, input.options()); + result_tmp = cholesky_inverse_out_info(result_tmp, infos, input, upper); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + } else { + // use result's memory directly + result = cholesky_inverse_out_info(result, infos, input, upper); + } + + // Now check LAPACK/MAGMA error codes + at::_linalg_check_errors(infos, "cholesky_inverse", result.dim() == 2); + return result; +} + +Tensor cholesky_inverse(const Tensor &input, bool upper) { + Tensor result = at::empty({0}, input.options()); + result = at::cholesky_inverse_out(result, input, upper); + return result; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg.solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// Auxiliary function that returns the LU decomposition to use it in the backward +TORCH_IMPL_FUNC(_linalg_solve_ex_out)(const Tensor& A, + const Tensor& B, + bool left, + bool check_errors, + const Tensor& result, + const Tensor& LU, + const Tensor& pivots, + const Tensor& info) { + at::linalg_lu_factor_ex_out(const_cast(LU), + const_cast(pivots), + const_cast(info), + A); + if (check_errors) { + at::_linalg_check_errors(info, "torch.linalg.solve_ex", A.dim() == 2); + } + + // [numpy-compat] Handle vectors on the rhs + const bool vector_case = at::native::linalg_solve_is_vector_rhs(LU, B); + auto result_ = vector_case ? result.unsqueeze(-1) : result; + auto B_ = vector_case ? B.unsqueeze(-1) : B; + at::linalg_lu_solve_out(result_, LU, pivots, B_, left); +} + +std::tuple linalg_solve_ex_out(const Tensor& A, + const Tensor& B, + bool left, + bool check_errors, + Tensor& result, + Tensor& info) { + auto LU = B.new_empty({0}); + auto pivots = B.new_empty({0}, kInt); + at::_linalg_solve_ex_out(result, LU, pivots, info, A, B, left, check_errors); + return std::tie(result, info); +} + +// We implement linalg_solve_ex as a composite function of _linalg_solve +std::tuple linalg_solve_ex(const Tensor& A, + const Tensor& B, + bool left, + bool check_errors) { + auto [result, LU, pivots, info] = at::_linalg_solve_ex(A, B, left, check_errors); + return std::make_tuple(std::move(result), std::move(info)); +} + +Tensor& linalg_solve_out(const Tensor& A, + const Tensor& B, + bool left, + Tensor& result) { + auto info = B.new_empty({0}, kInt); + at::linalg_solve_ex_out(result, info, A, B, left); + at::_linalg_check_errors(info, "torch.linalg.solve", A.dim() == 2); + return result; +} + +Tensor linalg_solve(const Tensor& A, + const Tensor& B, + bool left) { + if (A.layout() == kSparseCsr) { + return at::_spsolve(A, B, left); + } + auto [result, info] = at::linalg_solve_ex(A, B, left); + at::_linalg_check_errors(info, "torch.linalg.solve", A.dim() == 2); + return result; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lu_factor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(lu_factor_stub); + +TORCH_IMPL_FUNC(linalg_lu_factor_ex_out)(const Tensor& A, + bool pivot, + bool check_errors, + const Tensor& LU, + const Tensor& pivots, + const Tensor& info) { + if (A.numel() == 0) { + // zero out the infos as it will have one element if the input is a matrix of size (0, 0) + info.zero_(); + return; + } + if (!LU.is_same(A)) { + LU.copy_(A); + } + + lu_factor_stub(A.device().type(), LU, pivots, info, pivot); + + if (check_errors) { + at::_linalg_check_errors(info, "torch.linalg.lu_factor_ex", A.dim() == 2); + } +} + +std::tuple linalg_lu_factor_out(const Tensor& A, bool pivot, Tensor& LU, Tensor& pivots) { + auto info = at::empty({0}, A.options().dtype(kInt)); + // We pass check_errors as we want to use lu_factor rather than lu_factor_ex in the errors + at::linalg_lu_factor_ex_out(LU, pivots, info, A, pivot, /*check_errors=*/false); + at::_linalg_check_errors(info, "torch.linalg.lu_factor", A.dim() == 2); + return std::tie(LU, pivots); +} + +std::tuple linalg_lu_factor(const Tensor& A, bool pivot) { + auto [LU, pivots, info] = at::linalg_lu_factor_ex(A, pivot, /*check_errors=*/false); + at::_linalg_check_errors(info, "torch.linalg.lu_factor", A.dim() == 2); + return std::make_tuple(std::move(LU), std::move(pivots)); +} + +// TODO Deprecate this function in favour of linalg_lu_factor_ex +std::tuple _lu_with_info(const Tensor& self, bool compute_pivots, bool /*unused*/) { + TORCH_WARN_ONCE( + "torch.lu is deprecated in favor of torch.linalg.lu_factor / torch.linalg.lu_factor_ex and will be ", + "removed in a future PyTorch release.\n", + "LU, pivots = torch.lu(A, compute_pivots)\n", + "should be replaced with\n", + "LU, pivots = torch.linalg.lu_factor(A, compute_pivots)\n", + "and\n", + "LU, pivots, info = torch.lu(A, compute_pivots, get_infos=True)\n", + "should be replaced with\n", + "LU, pivots, info = torch.linalg.lu_factor_ex(A, compute_pivots)" + ); + return at::linalg_lu_factor_ex(self, compute_pivots, false); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_lu ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(unpack_pivots_stub); + +TORCH_IMPL_FUNC(linalg_lu_out)(const Tensor& A, + bool pivot, + const Tensor& P, + const Tensor& L, + const Tensor& U) { + const auto m = A.sizes().end()[-2]; + const auto n = A.sizes().end()[-1]; + + // A.shape[-2:] == (m, n) + // P.shape[-2:] == (m, m) + // L.shape[-2:] == (m, k) + // U.shape[-2:] == (k, n) + // with k = min(m, n) + + // Use L as it has the correct size + const bool use_L = m > n; + auto pivots = at::empty({0}, A.options().dtype(kInt)); + auto info = at::empty({0}, A.options().dtype(kInt)); + at::linalg_lu_factor_ex_out(const_cast(use_L ? L : U), + const_cast(pivots), + const_cast(info), + A, + pivot, + /*check_errors=*/false); + at::lu_unpack_out(const_cast(P), + const_cast(L), + const_cast(U), + use_L ? L : U, + pivots, + /*unpack_data=*/true, + /*unpack_pivots=*/pivot); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lu_unpack ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +TORCH_IMPL_FUNC(lu_unpack_out)(const Tensor& LU, + const Tensor& pivots, + bool unpack_lu, + bool unpack_pivots, + const Tensor& P, + const Tensor& L, + const Tensor& U) { + const auto m = LU.sizes().end()[-2]; + const auto n = LU.sizes().end()[-1]; + + // A.shape[-2:] == (m, n) + // P.shape[-2:] == (m, m) + // L.shape[-2:] == (m, k) + // U.shape[-2:] == (k, n) + // with k = min(m, n) + + if (unpack_lu) { + if (m > n || LU.is_same(L)) { + // The order of triu and tril is important as we may have LU.is_same(L) + at::triu_out(const_cast(U), m == n ? LU : LU.narrow(-2, 0, n), 0); + at::tril_out(const_cast(L), LU, -1); + L.diagonal(0, -2, -1).fill_(1.); + } else { + // The order of triu and tril is important as we may have LU.is_same(U) + at::tril_out(const_cast(L), m == n ? LU : LU.narrow(-1, 0, m), -1); + L.diagonal(0, -2, -1).fill_(1.); + at::triu_out(const_cast(U), LU, 0); + } + } + if (unpack_pivots) { + // lu_factor_ex returns an int32 1-based indexing, which is what we have in `pivots` + // We transform that to a proper permutation of the indices {0, ..., m-1} + const auto perm_sizes = IntArrayRef(P.sizes().data(), P.dim() - 1); + + // Fill `perm` with the identity permutation (perhaps batched) + const auto perm = at::arange(m, pivots.options().memory_format(at::MemoryFormat::Contiguous).dtype(kLong)) + .expand(perm_sizes) + .contiguous(); + + // Note that perm is of type kLong and pivots is a 1-indexed kInt. + // This is taken into account in the unpack_pivots kernel + auto iter = TensorIteratorConfig() + .set_check_mem_overlap(false) + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(pivots.sizes(), /*squash_dims=*/pivots.dim() - 1) + .add_output(perm) + .add_owned_const_input(pivots.contiguous()) + .build(); + + unpack_pivots_stub(pivots.device().type(), iter, std::min(m, n), m); + + // Transform the permutation into a permutation matrix + P.zero_(); + P.scatter_(-2, perm.unsqueeze(-2), 1.); + } +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_lu_solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +DEFINE_DISPATCH(lu_solve_stub); + +TORCH_IMPL_FUNC(linalg_lu_solve_out)(const Tensor& LU, + const Tensor& pivots, + const Tensor& B, + bool left, + bool adjoint, + const Tensor& result) { + // Trivial case + if (result.numel() == 0) { + return; + } + + // Solve A^H X = B^H. Then we return X^H + if (!left) { + adjoint = !adjoint; + result.transpose_(-2, -1); + } + + // Copy B (or B^H) into result + if (!result.is_same(B)) { + result.copy_(left ? B : B.mH()); + } + + // Make LU / pivots F-contiguous + auto pivots_ = pivots.expect_contiguous(); + auto LU_ = at::native::borrow_else_clone( + LU.mT().is_contiguous(), LU, LU, /*contig=*/false); + + const auto trans = !adjoint ? TransposeType::NoTranspose : + LU.is_complex() ? TransposeType::ConjTranspose + : TransposeType::Transpose; + + lu_solve_stub(LU_->device().type(), *LU_, *pivots_, result, trans); + + // Conj-transpose back in-place + if (!left) { + result.transpose_(-2, -1); + if (result.is_complex()) { + result._set_conj(!result.is_conj()); + } + } +} + +Tensor lu_solve(const Tensor& self, const Tensor& LU_data, const Tensor& LU_pivots) { + TORCH_WARN_ONCE( + "torch.lu_solve is deprecated in favor of torch.linalg.lu_solve", + "and will be removed in a future PyTorch release.\n", + "Note that torch.linalg.lu_solve has its arguments reversed.\n", + "X = torch.lu_solve(B, LU, pivots)\n", + "should be replaced with\n", + "X = torch.linalg.lu_solve(LU, pivots, B)" + ); + return at::linalg_lu_solve(LU_data, LU_pivots, self); +} + +Tensor& lu_solve_out(const Tensor& self, const Tensor& LU_data, const Tensor& LU_pivots, Tensor& result) { + TORCH_WARN_ONCE( + "torch.lu_solve is deprecated in favor of torch.linalg.lu_solve", + "and will be removed in a future PyTorch release.\n", + "Note that torch.linalg.lu_solve has its arguments reversed.\n", + "X = torch.lu_solve(B, LU, pivots)\n", + "should be replaced with\n", + "X = torch.linalg.lu_solve(LU, pivots, B)" + ); + return at::linalg_lu_solve_out(result, LU_data, LU_pivots, self); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ triangular_solve ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(triangular_solve_stub); + +/* +Solves the matrix equation 'input' @ 'result' = 'other' for the 'result'. +The result of the computation is saved in-place in 'result' tensor, +'clone_input' will be a copy of 'input', +'infos' is used to store information for possible checks for error, +'upper' controls the portion of input matrix to consider in computations, +'transpose' if true then 'input.mT()' @ 'result' = 'other' is solved, +'unitriangular' if true then the diagonal elements of 'input' are assumed to be 1 +and the actual diagonal values are not used. +*/ +static void triangular_solve_out_impl( + const Tensor& result, + const Tensor& clone_input, + const Tensor& input, + const Tensor& other, + bool upper, bool transpose, bool unitriangular) { + TORCH_WARN_ONCE( + "torch.triangular_solve is deprecated in favor of torch.linalg.solve_triangular", + "and will be removed in a future PyTorch release.\n", + "torch.linalg.solve_triangular has its arguments reversed and does not return a copy of one of the inputs.\n", + "X = torch.triangular_solve(B, A).solution\n", + "should be replaced with\n", + "X = torch.linalg.solve_triangular(A, B)."); + // These internal asserts make explicit the assumptions in the implementation + // Error check with the actual error messages are done on the higher level of + // the hierarchy of calls + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.dim() >= 2); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.size(-2) == input.size(-1)); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.device() == other.device()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.device() == result.device()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.device() == clone_input.device()); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.scalar_type() == other.scalar_type()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.scalar_type() == result.scalar_type()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.scalar_type() == clone_input.scalar_type()); + + // if 'result' has no elements we can modify it + if (result.numel() == 0) { + result.resize_(other.mT().sizes(), MemoryFormat::Contiguous); + result.transpose_(-2, -1); // make 'result' to have Fortran contiguous memory layout + } + + // if 'clone_input' has no elements we can modify it + if (clone_input.numel() == 0) { + clone_input.resize_(input.mT().sizes(), MemoryFormat::Contiguous); + clone_input.transpose_(-2, -1); // make 'clone_input' to have Fortran contiguous memory layout + } + + // 'result' and 'clone_input' must be in batched column major order (Fortran contiguous) + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(clone_input.mT().is_contiguous()); + + // triangular_solve_stub performs calculations in-place + // 'result' must be a copy of 'other' + // 'clone_input' must be a copy of 'input' + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.sizes().equals(other.sizes())); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(clone_input.sizes().equals(input.sizes())); + result.copy_(other); + clone_input.copy_(input); + + triangular_solve_stub(input.device().type(), clone_input, result, /*left=*/true, upper, transpose ? TransposeType::Transpose : TransposeType::NoTranspose, unitriangular); +} + +TORCH_IMPL_FUNC(triangular_solve_out)(const Tensor& self, const Tensor& A, bool upper, bool transpose, bool unitriangular, const Tensor& result, const Tensor& clone_A) { + auto [self_broadcast, A_broadcast] = _linalg_broadcast_batch_dims(self, A, "triangular_solve"); + + bool copy_needed = !result.transpose(-2, -1).is_contiguous(); + copy_needed |= !clone_A.transpose(-2, -1).is_contiguous(); + + if (copy_needed) { + Tensor result_tmp = at::empty({0}, self.options()); + Tensor clone_A_tmp = at::empty({0}, A.options()); + + triangular_solve_out_impl(result_tmp, clone_A_tmp, A_broadcast, self_broadcast, upper, transpose, unitriangular); + + result.copy_(result_tmp); + clone_A.copy_(clone_A_tmp); + } else { + triangular_solve_out_impl(result, clone_A, A_broadcast, self_broadcast, upper, transpose, unitriangular); + } +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ qr ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(geqrf_stub); + +static void geqrf_out_helper(const Tensor& input, const Tensor& QR, const Tensor& tau) { + TORCH_INTERNAL_ASSERT(input.dim() >= 2); + + TORCH_INTERNAL_ASSERT(input.scalar_type() == QR.scalar_type()); + TORCH_INTERNAL_ASSERT(input.device() == QR.device()); + + TORCH_INTERNAL_ASSERT(input.scalar_type() == tau.scalar_type()); + TORCH_INTERNAL_ASSERT(input.device() == tau.device()); + + // if 'QR' has no elements we can modify it + if (QR.numel() == 0) { + QR.resize_as_(input.mT(), MemoryFormat::Contiguous); + QR.transpose_(-2, -1); // make Fortran-contiguous + } + + auto expected_batch_tau_shape = IntArrayRef(input.sizes().data(), input.dim() - 2).vec(); // input.shape[:-2] + expected_batch_tau_shape.push_back(std::min(input.size(-2), input.size(-1))); + if (tau.numel() == 0) { + tau.resize_(expected_batch_tau_shape); + } + + // QR tensor must be in batched column major order (Fortran contiguous) + TORCH_INTERNAL_ASSERT(QR.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT(QR.sizes().equals(input.sizes())); + + // tau tensor must be contiguous + TORCH_INTERNAL_ASSERT(tau.is_contiguous()); + TORCH_INTERNAL_ASSERT(tau.sizes().equals(expected_batch_tau_shape)); + + // geqrf_stub (apply_geqrf) performs calculations in-place and 'QR' must be a copy of input + QR.copy_(input); + geqrf_stub(input.device().type(), QR, tau); +} + +std::tuple geqrf_out(const Tensor& input, Tensor& QR, Tensor& tau) { + TORCH_CHECK(input.dim() >= 2, "torch.geqrf: input must have at least 2 dimensions."); + + checkSameDevice("torch.geqrf", QR, input, "a"); // 'a' is used in documentation and native_functions.yml + checkSameDevice("torch.geqrf", tau, input, "tau"); + checkLinalgCompatibleDtype("torch.geqrf", QR, input, "a"); + checkLinalgCompatibleDtype("torch.geqrf", tau, input, "tau"); + + bool QR_input_same_type = (QR.scalar_type() == input.scalar_type()); + bool tau_input_same_type = (tau.scalar_type() == input.scalar_type()); + bool QR_equal_expected_shape = QR.sizes().equals(input.sizes()); + + auto expected_batch_tau_shape = IntArrayRef(input.sizes().data(), input.dim() - 2).vec(); // input.shape[:-2] + expected_batch_tau_shape.push_back(std::min(input.size(-2), input.size(-1))); + bool tau_equal_expected_shape = tau.sizes().equals(expected_batch_tau_shape); + + bool is_batched_column_major = false; + if (QR.dim() >= 2) { + is_batched_column_major = QR.mT().is_contiguous(); + } + + // if 'QR' is not empty and not in batched column major format + bool copy_needed = (QR.numel() != 0 && !is_batched_column_major); + copy_needed |= (QR.numel() != 0 && !QR_equal_expected_shape); // or 'QR' does not have the expected shape + copy_needed |= !QR_input_same_type; // or 'QR' does not have the same dtype as input + // we have to allocate a temporary tensor + + copy_needed |= (tau.numel() != 0 && !tau.is_contiguous()); + copy_needed |= (tau.numel() != 0 && !tau_equal_expected_shape); // or 'tau' does not have the expected shape + copy_needed |= !tau_input_same_type; // or 'tau' does not have the same dtype as input + + if (copy_needed) { + Tensor QR_tmp = at::empty({0}, input.options()); + Tensor tau_tmp = at::empty({0}, input.options()); + + geqrf_out_helper(input, QR_tmp, tau_tmp); + + at::native::resize_output(QR, QR_tmp.sizes()); + QR.copy_(QR_tmp); + at::native::resize_output(tau, tau_tmp.sizes()); + tau.copy_(tau_tmp); + } else { + // use "out" tensors' storage directly + geqrf_out_helper(input, QR, tau); + } + + return std::tuple(QR, tau); +} + +std::tuple geqrf(const Tensor& input) { + Tensor QR = at::empty({0}, input.options()); + Tensor tau = at::empty({0}, input.options()); + std::tie(QR, tau) = at::geqrf_outf(input, QR, tau); + return std::make_tuple(std::move(QR), std::move(tau)); +} + +/* + Computes the QR decomposition using GEQRF and ORGQR operations. + This is an in-place function and Q, R tensors must have correct shape and be Fortran contiguous. + + Args: + * `input` - [in] Input tensor for QR decomposition + * `Q` - [out] Tensor containing the Q matrices of QR decomposition + * `R` - [out] Tensor containing the R matrices of QR decomposition + * `compute_q` - controls whether the Q tensor is computed + * `reduced_mode` - controls the size of Q and R tensors + + For further details, please see the LAPACK documentation for GEQRF and ORGQR. +*/ +TORCH_IMPL_FUNC(linalg_qr_out)(const Tensor& A, + std::string_view mode, + const Tensor & Q, + const Tensor & R) { + auto m = A.size(-2); + auto n = A.size(-1); + auto k = std::min(m, n); + auto [compute_q, reduced_mode] = at::native::_parse_qr_mode(mode); + + + // We need an auxiliary tensor to call geqrf + auto tau_shape = A.sizes().vec(); + tau_shape.pop_back(); + tau_shape.back() = k; + auto tau = A.new_empty(tau_shape); + + // geqrf requires m x n workspace input that is modified in-place + // We try to use Q. If it doesn't fit, we try to use R + // If m > n and compute_q==false, it won't fit into Q or R, so we need to create an auxiliary tensor + Tensor QR; + if (compute_q && Q.size(-1) == n) { + QR = Q; + QR.copy_(A); + } else if (R.size(-2) == m) { + QR = R; + QR.copy_(A); + } else { + QR = cloneBatchedColumnMajor(A); + } + + geqrf_stub(A.device().type(), QR, tau); + + // Split QR into Q (unless compute_q == false) and R + if (QR.is_alias_of(R)) { + // Copy QR into Q + if (compute_q) { + // If the result didn't fit in Q and compute_q == true is because Q is not of size m x n (i.e. it's of size m x m) + TORCH_INTERNAL_ASSERT(Q.size(-1) == m); + if (m < n) { + Q.copy_(QR.slice(-1, 0, m)); + } else { + Q.slice(-1, 0, n).copy_(QR); + } + } + R.triu_(); + } else { + // Copy QR into R from Q or the aux tensor + at::triu_out(const_cast(R), QR.slice(-2, 0, n)); + } + + if (compute_q) { + // Next perform ORGQR for Q using the result from GEQRF + orgqr_stub(A.device().type(), const_cast(Q), tau); + } +} + +TORCH_IMPL_FUNC(linalg_polar_out)(const Tensor& A, + const Tensor& U, + const Tensor& H) { + // Polar decomposition A = U @ H via the (reduced) SVD A = Up diag(S) Vh: + // U = Up @ Vh (orthonormal columns) + // H = Vh^H diag(S) Vh (symmetric/Hermitian positive-semidefinite) + // This is the portable backend kernel. On CUDA a Python native-op override + // (cuSOLVER QDWH/Xpolar via nvmath-python) intercepts the functional op for + // supported inputs and only falls through to here when unavailable, so this + // path also serves as the CUDA fallback and the CPU/compile/out= path. + auto [Up, S, Vh] = at::linalg_svd(A, /*full_matrices=*/false); + auto Hsym = Vh.mH().matmul(S.unsqueeze(-1) * Vh); + // Symmetrize/Hermitianize to remove round-off asymmetry. + Hsym = 0.5 * (Hsym + Hsym.mH()); + U.copy_(Up.matmul(Vh)); + H.copy_(Hsym); +} + + +std::tuple qr(const Tensor& self, bool some) { + TORCH_WARN_ONCE( + "torch.qr is deprecated in favor of torch.linalg.qr and will be removed in a future PyTorch release.\n", + "The boolean parameter 'some' has been replaced with a string parameter 'mode'.\n", + "Q, R = torch.qr(A, some)\n", + "should be replaced with\n", + "Q, R = torch.linalg.qr(A, 'reduced' if some else 'complete')" + ); + const char* mode = some ? "reduced" : "complete"; + return at::linalg_qr(self, mode); +} + +std::tuple qr_out(const Tensor& self, bool some, Tensor& Q, Tensor& R) { + TORCH_WARN_ONCE( + "torch.qr is deprecated in favor of torch.linalg.qr and will be removed in a future PyTorch release.\n", + "The boolean parameter 'some' has been replaced with a string parameter 'mode'.\n", + "Q, R = torch.qr(A, some)\n", + "should be replaced with\n", + "Q, R = torch.linalg.qr(A, 'reduced' if some else 'complete')" + ); + const char* mode = some ? "reduced" : "complete"; + return at::linalg_qr_out(Q, R, self, mode); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ orgqr ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(orgqr_stub); + +/* + The householder_product (orgqr) function allows reconstruction of an orthogonal (or unitary) matrix Q, + from a sequence of elementary reflectors, such as is produced by the geqrf function. + + Args: + * `input` - Tensor with the directions of the elementary reflectors below the diagonal. + * `tau` - Tensor containing the magnitudes of the elementary reflectors. + * `result` - result Tensor, which will contain the orthogonal (or unitary) matrix Q. + + For further details, please see the LAPACK/MAGMA documentation. +*/ +static Tensor& householder_product_out_helper(const Tensor& input, const Tensor& tau, Tensor& result) { + TORCH_INTERNAL_ASSERT(input.dim() >= 2); + TORCH_INTERNAL_ASSERT(input.size(-2) >= input.size(-1)); + TORCH_INTERNAL_ASSERT(input.size(-1) >= tau.size(-1)); + + TORCH_INTERNAL_ASSERT(input.scalar_type() == tau.scalar_type()); + TORCH_INTERNAL_ASSERT(input.device() == tau.device()); + + TORCH_INTERNAL_ASSERT(result.scalar_type() == input.scalar_type()); + TORCH_INTERNAL_ASSERT(result.device() == input.device()); + + // if result has no elements we can modify it + if (result.numel() == 0) { + at::native::resize_as_(result, input.mT(), MemoryFormat::Contiguous); + result.transpose_(-2, -1); + } + + // result tensor must be in batched column major order (Fortran contiguous) + TORCH_INTERNAL_ASSERT(result.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT(result.sizes().equals(input.sizes())); + + // tau tensor must be contiguous + Tensor tau_ = tau; + if (!tau.is_contiguous()) { + tau_ = at::empty(tau.sizes(), tau.options(), MemoryFormat::Contiguous); + tau_.copy_(tau); + } + + // orgqr_stub (apply_orgqr) performs calculations in-place and result must be a copy of input + result.copy_(input); + + result = orgqr_stub(result.device().type(), result, tau_); + return result; +} + +Tensor& linalg_householder_product_out(const Tensor& input, const Tensor& tau, Tensor& result) { + TORCH_CHECK(input.dim() >= 2, "torch.linalg.householder_product: input must have at least 2 dimensions."); + TORCH_CHECK( + input.size(-2) >= input.size(-1), + "torch.linalg.householder_product: input.shape[-2] must be greater than or equal to input.shape[-1]"); + TORCH_CHECK( + input.size(-1) >= tau.size(-1), + "torch.linalg.householder_product: input.shape[-1] must be greater than or equal to tau.shape[-1]"); + + TORCH_CHECK( + input.dim() - tau.dim() == 1, + "torch.linalg.householder_product: Expected tau to have one dimension less than input, but got tau.ndim equal to ", + tau.dim(), + " and input.ndim is equal to ", + input.dim()); + if (input.dim() > 2) { + auto expected_batch_tau_shape = IntArrayRef(input.sizes().data(), input.dim() - 2); // input.shape[:-2] + auto actual_batch_tau_shape = IntArrayRef(tau.sizes().data(), tau.dim() - 1); // tau.shape[:-1] + TORCH_CHECK( + actual_batch_tau_shape.equals(expected_batch_tau_shape), + "torch.linalg.householder_product: Expected batch dimensions of tau to be equal to input.shape[:-2], but got ", + actual_batch_tau_shape); + } + + TORCH_CHECK( + tau.scalar_type() == input.scalar_type(), + "torch.linalg.householder_product: tau dtype ", + tau.scalar_type(), + " does not match input dtype ", + input.scalar_type()); + checkSameDevice("torch.linalg.householder_product", tau, input, "tau"); + checkSameDevice("torch.linalg.householder_product", result, input); + checkLinalgCompatibleDtype("torch.linalg.householder_product", result, input); + + // TODO: uncomment the following when passing incorrectly sized 'result' is not allowed + // if (result.numel() != 0) { + // // Resize messes up the strides, so let's not use at::native::resize_output + // TORCH_CHECK(result.sizes().equals(input.sizes()), + // "result shape ", result.sizes(), " does not match input shape ", input.sizes()); + // } + + bool result_input_same_type = (result.scalar_type() == input.scalar_type()); + bool result_equal_expected_shape = result.sizes().equals(input.sizes()); + bool is_batched_column_major = false; + if (result.dim() >= 2) { + is_batched_column_major = result.mT().is_contiguous(); + } + + // if result is not empty and not in batched column major format + bool copy_needed = (result.numel() != 0 && !is_batched_column_major); + copy_needed |= !result_input_same_type; // or result does not have the same dtype as input + copy_needed |= (result.numel() != 0 && !result_equal_expected_shape); // or result does not have the expected shape + // we have to allocate a temporary tensor + if (copy_needed) { + Tensor result_tmp = at::empty({0}, input.options()); + result_tmp = householder_product_out_helper(input, tau, result_tmp); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + } else { + // use result's storage directly + result = householder_product_out_helper(input, tau, result); + } + + return result; +} + +Tensor linalg_householder_product(const Tensor& input, const Tensor& tau) { + Tensor result = at::empty({0}, input.options()); + result = at::linalg_householder_product_outf(input, tau, result); + return result; +} + +// torch.orgqr is an alias of torch.linalg.householder_product +// torch.linalg.householder_product is the preferred new function +Tensor& orgqr_out(const Tensor& input, const Tensor& tau, Tensor& result) { + return at::linalg_householder_product_outf(input, tau, result); +} + +Tensor orgqr(const Tensor& input, const Tensor& tau) { + return at::linalg_householder_product(input, tau); +} + +DEFINE_DISPATCH(ormqr_stub); + +static void ormqr_out_helper(const Tensor& input, const Tensor& tau, const Tensor& other, const Tensor& result, bool left, bool transpose) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.dim() >= 2); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(other.dim() >= 2); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(other.size(left ? -2 : -1) >= tau.size(-1)); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(other.size(left ? -2 : -1) == input.size(-2)); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.scalar_type() == tau.scalar_type()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.device() == tau.device()); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.scalar_type() == other.scalar_type()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.device() == other.device()); + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.scalar_type() == input.scalar_type()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.device() == input.device()); + + // if 'result' has no elements we can modify it + if (result.numel() == 0) { + at::native::resize_as_(result, other.mT(), MemoryFormat::Contiguous); + result.transpose_(-2, -1); + } + + // 'result' tensor must be in batched column major order (Fortran contiguous) + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(result.sizes().equals(other.sizes())); + + // 'tau' tensor must be contiguous + Tensor tau_ = tau; + if (!tau.is_contiguous()) { + tau_ = at::empty(tau.sizes(), tau.options(), MemoryFormat::Contiguous); + tau_.copy_(tau); + } + + // 'input' tensor must be Fortran contiguous + Tensor input_ = input; + if (!input.mT().is_contiguous()) { + input_ = at::empty(input.mT().sizes(), input.options(), MemoryFormat::Contiguous); + input_.transpose_(-2, -1); + input_.copy_(input); + } + + // ormqr_stub (apply_ormqr) performs calculations in-place and 'result' must be a copy of 'other' + result.copy_(other); + + ormqr_stub(result.device().type(), input_, tau_, result, left, transpose); +} + +Tensor& ormqr_out(const Tensor& input, const Tensor& tau, const Tensor& other, bool left, bool transpose, Tensor& result) { + TORCH_CHECK(input.dim() >= 2, "torch.ormqr: input must have at least 2 dimensions."); + TORCH_CHECK(other.dim() >= 2, "torch.ormqr: other must have at least 2 dimensions."); + + int64_t left_size_condition = left ? -2 : -1; + TORCH_CHECK( + other.size(left_size_condition) == input.size(-2), + "torch.ormqr: other.shape[", + left_size_condition, + "] must be equal to input.shape[-2]"); + + TORCH_CHECK( + std::min(other.size(left_size_condition), input.size(-1)) == tau.size(-1), + "torch.ormqr: tau.shape[-1] must be equal to min(other.shape[", + left_size_condition, + "], input.shape[-1])"); + + TORCH_CHECK( + input.dim() - tau.dim() == 1, + "torch.ormqr: ", + "Expected tau to have one dimension less than input, but got tau.ndim equal to ", + tau.dim(), + " and input.ndim is equal to ", + input.dim()); + + TORCH_CHECK( + input.dim() == other.dim(), + "torch.ormqr: ", + "Expected other to have the same number of dimensions as input, but got other.ndim equal to ", + other.dim(), + " and input.ndim is equal to ", + input.dim()); + + if (input.dim() > 2) { + auto expected_batch_shape = IntArrayRef(input.sizes().data(), input.dim() - 2); // input.shape[:-2] + auto actual_batch_tau_shape = IntArrayRef(tau.sizes().data(), tau.dim() - 1); // tau.shape[:-1] + TORCH_CHECK( + actual_batch_tau_shape.equals(expected_batch_shape), + "torch.ormqr: Expected batch dimensions of tau to be equal to input.shape[:-2], but got ", + actual_batch_tau_shape); + + auto actual_batch_other_shape = IntArrayRef(other.sizes().data(), other.dim() - 2); // other.shape[:-2] + TORCH_CHECK( + actual_batch_other_shape.equals(expected_batch_shape), + "torch.ormqr: Expected batch dimensions of other to be equal to input.shape[:-2], but got ", + actual_batch_other_shape); + } + + TORCH_CHECK( + tau.scalar_type() == input.scalar_type(), + "torch.ormqr: Expected input and tau to have the same dtype, but input has dtype", input.scalar_type(), + " and tau has dtype ", tau.scalar_type()); + TORCH_CHECK( + other.scalar_type() == input.scalar_type(), + "torch.ormqr: Expected input and other to have the same dtype, but input has dtype", input.scalar_type(), + " and other has dtype ", other.scalar_type()); + TORCH_CHECK( + result.scalar_type() == input.scalar_type(), + "torch.ormqr: Expected input and result to have the same dtype, but input has dtype", input.scalar_type(), + " and result has dtype ", result.scalar_type()); + + checkSameDevice("torch.ormqr", tau, input, "tau"); + checkSameDevice("torch.ormqr", other, input, "other"); + checkSameDevice("torch.ormqr", result, input); + + bool result_equal_expected_shape = result.sizes().equals(other.sizes()); + bool is_batched_column_major = false; + if (result.dim() >= 2) { + is_batched_column_major = result.mT().is_contiguous(); + } + + // if result is not empty and not in batched column major format + bool copy_needed = (result.numel() != 0 && !is_batched_column_major); + copy_needed |= (result.numel() != 0 && !result_equal_expected_shape); // or result does not have the expected shape + // we have to allocate a temporary tensor + if (copy_needed) { + Tensor result_tmp = at::empty({0}, input.options()); + ormqr_out_helper(input, tau, other, result_tmp, left, transpose); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + } else { + // use result's storage directly + ormqr_out_helper(input, tau, other, result, left, transpose); + } + + return result; +} + +Tensor ormqr(const Tensor& input, const Tensor& tau, const Tensor& other, bool left, bool transpose) { + Tensor result = at::empty({0}, input.options()); + result = at::native::ormqr_out(input, tau, other, left, transpose, result); + return result; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_eigh ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(linalg_eigh_stub); + +/* + Computes eigenvalues and eigenvectors of the tensor 'input'. + + Args: + * 'input' - input Tensor for eigendecomposition + * 'values' - Tensor to store computed eigenvalues + * 'vectors' - Tensor to store computed eigenvectors + * 'infos' - Tensor to store LAPACK/MAGMA/cuSOLVER error codes + * 'compute_eigenvectors' - controls whether eigenvectors should be computed + * 'uplo' - controls the portion of input matrix to consider in computations, allowed values are "u", "U", "l", "L" + "u", "U" - upper triangular portion of the input matrix is used in computations; "l", "L" - lower. +*/ + +TORCH_IMPL_FUNC(_linalg_eigh_out)(const Tensor& A, + std::string_view uplo, + bool compute_v, + const Tensor& L, + const Tensor& V) { + if (A.numel() == 0) { + return; + } + + auto uplo_uppercase = static_cast(std::toupper(static_cast(uplo[0]))); + bool upper = (uplo_uppercase == 'U'); + + Tensor V_ = V; + if (compute_v) { + V_.copy_(A); + } else { + // We need a tensor to hold A + V_ = cloneBatchedColumnMajor(A); + } + + const auto info = at::zeros(A.sizes().slice(0, A.dim() - 2), A.options().dtype(kInt)); + linalg_eigh_stub(A.device().type(), L, V_, info, upper, compute_v); + + at::_linalg_check_errors(info, "linalg.eigh", /*is_matrix*/A.dim() == 2); +} + +std::tuple linalg_eigh(const Tensor& A, std::string_view uplo) { + // TODO (Good intro task) Implement linalg_eigh_ex_out + return at::_linalg_eigh(A, uplo, /*compute_v*/true); +} + +std::tuple linalg_eigh_out(const Tensor& A, std::string_view uplo, Tensor& L, Tensor& V) { + return at::_linalg_eigh_out(L, V, A, uplo, /*compute_v=*/true); +} + + +Tensor linalg_eigvalsh(const Tensor& A, std::string_view uplo) { + return std::get<0>(at::_linalg_eigh(A, uplo, + /*compute_v=*/_may_require_fw_or_bw_grad(A))); +} + +Tensor& linalg_eigvalsh_out(const Tensor& A, std::string_view uplo, Tensor& L) { + auto V = at::empty({0}, A.options()); + at::_linalg_eigh_out(L, V, A, uplo, /*compute_v=*/false); + return L; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_eig ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(linalg_eig_make_complex_eigenvectors_stub); + +// Converts LAPACK's real-valued eigenvector encoding to complex eigenvectors. +// This function dispatches to device-specific implementations (CPU or CUDA) based +// on the device type of the input tensors. +void linalg_eig_make_complex_eigenvectors(const Tensor& complex_vectors, const Tensor& complex_values, const Tensor& real_vectors) { + // Device consistency checks + TORCH_CHECK( + complex_vectors.device() == complex_values.device() && + complex_vectors.device() == real_vectors.device(), + "linalg_eig_make_complex_eigenvectors: all tensors must be on the same device"); + + // Dispatch to device-specific implementation + linalg_eig_make_complex_eigenvectors_stub( + complex_vectors.device().type(), + complex_vectors, + complex_values, + real_vectors); +} + +DEFINE_DISPATCH(linalg_eig_stub); + +static std::tuple linalg_eig_out_info(const Tensor& input, Tensor& values, Tensor& vectors, Tensor& infos, bool compute_eigenvectors) { + auto options = input.options(); + + // These internal asserts make explicit the assumptions in the implementation + // Error check with the actual error messages are done on the higher level of the hierarchy of calls + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.dim() >= 2); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(input.size(-2) == input.size(-1)); + + // for real-valued 'input', eigenvalues can be real-valued or complex-valued + TORCH_INTERNAL_ASSERT_DEBUG_ONLY((toComplexType(input.scalar_type()) == values.scalar_type()) || (input.scalar_type() == values.scalar_type())); + + // for real-valued 'input', eigenvectors can be real-valued or complex-valued + if (compute_eigenvectors) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY((toComplexType(input.scalar_type()) == vectors.scalar_type()) || (input.scalar_type() == vectors.scalar_type())); + } + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(infos.scalar_type() == at::kInt); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(infos.numel() == std::max(1, batchCount(input))); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(infos.is_contiguous()); + + // if 'vectors' has no elements we can modify it + if (vectors.numel() == 0 && compute_eigenvectors) { + vectors.resize_(input.sizes(), MemoryFormat::Contiguous); + vectors.transpose_(-2, -1); // make 'vectors' to have Fortran contiguous memory layout + } + + // if 'values' has no elements we can modify it + auto values_shape = IntArrayRef(input.sizes().data(), input.dim()-1); // input.shape[:-1] + if (values.numel() == 0) { + values.resize_(values_shape, MemoryFormat::Contiguous); + } + + // 'vectors' must be in batched column major order (Fortran contiguous) + if (compute_eigenvectors) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(vectors.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(vectors.sizes().equals(input.sizes())); + } + + // 'values' must be contiguous + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(values.sizes().equals(values_shape)); + + // if 'input' is complex then use 'values' directly else create a temporary to hold the real and imaginary parts + // and then use at::complex_out + Tensor real_imag_values = values; + + // if 'input' is complex then use 'vectors' directly else maybe create a temporary to hold real vectors + // and then use linalg_eig_make_complex_eigenvectors + Tensor maybe_complex_vectors = vectors; + if (!input.is_complex()) { + // first n elements to hold the real portion of the output and the last n elements to hold the imaginary portion + auto real_imag_shape = IntArrayRef(input.sizes().data(), input.dim()-2).vec(); // input.shape[:-2] + real_imag_shape.push_back(input.size(-1) * 2); + real_imag_values = at::empty(real_imag_shape, options, MemoryFormat::Contiguous); + + // linalg_eig_stub expects real-valued tensor to store eigenvectors + // output of linalg_eig_stub need to be post-processed later to produce complex-valued eigenvectors + // we do this post-processing only if 'vectors' is complex-valued + // otherwise storage of 'vectors' is used directly + if (vectors.is_complex() && compute_eigenvectors) { + maybe_complex_vectors = at::empty(input.sizes(), options, MemoryFormat::Contiguous); + maybe_complex_vectors.transpose_(-2, -1); // make 'maybe_complex_vectors' to have Fortran contiguous memory layout + } + } + + linalg_eig_stub(input.device().type(), real_imag_values, maybe_complex_vectors, infos, input, compute_eigenvectors); + + // if input is not complex we need to do some post-processing + if (!input.is_complex()) { + // extract real and imaginary parts of the output + auto real_values = real_imag_values.slice(/*dim=*/-1, /*start=*/0, /*end*/input.size(-1)); + auto imag_values = real_imag_values.slice(/*dim=*/-1, /*start=*/input.size(-1)); + + // if the imaginary part is zero we don't need to do anything + bool is_zero_imag = at::all(imag_values == 0.0).item().toBool(); + if (is_zero_imag) { + values.copy_(real_values); + if (compute_eigenvectors) { + vectors.copy_(maybe_complex_vectors); // does nothing for !vectors.is_complex() because vectors.is_same(maybe_complex_vectors) == true + } + return std::tuple(values, vectors); + } + + if (values.is_complex()) { + values = at::complex_out(values, real_values, imag_values); + } else { + TORCH_CHECK(false, "torch.linalg.eig: imaginary part of eigenvalues is non-zero, can't safely cast eigenvalues to non-complex dtype.") + } + if (compute_eigenvectors) { + if (vectors.is_complex()) { + // Decode LAPACK's real eigenvector format into complex eigenvectors + // This now dispatches to device-specific implementations (CPU/CUDA) + linalg_eig_make_complex_eigenvectors(vectors, values, maybe_complex_vectors); + } else { + TORCH_CHECK(false, "torch.linalg.eig: imaginary part of eigenvectors is non-zero, can't safely cast eigenvectors to non-complex dtype.") + } + } + } + + return std::tuple(values, vectors); +} + +std::tuple linalg_eig_out(const Tensor& input, Tensor& values, Tensor& vectors) { + TORCH_CHECK(input.isfinite().all().item(), "torch.linalg.eig: input tensor should not contain infs or NaNs."); + squareCheckInputs(input, "linalg.eig"); + + // unlike NumPy for real-valued inputs the output is always complex-valued + checkLinalgCompatibleDtype("torch.linalg.eig", values.scalar_type(), toComplexType(input.scalar_type()), "eigenvalues"); + checkLinalgCompatibleDtype("torch.linalg.eig", vectors.scalar_type(), toComplexType(input.scalar_type()), "eigenvectors"); + checkSameDevice("torch.linalg.eig", values, input, "eigenvalues"); + checkSameDevice("torch.linalg.eig", vectors, input, "eigenvectors"); + + auto options = input.options(); + auto infos = at::zeros({std::max(1, batchCount(input))}, options.dtype(kInt)); + + // if result is not empty and not in batched column major format we have to allocate a temporary tensor + bool is_batched_column_major = false; + if (vectors.dim() >= 2) { + is_batched_column_major = vectors.mT().is_contiguous(); + } + + bool values_expected_type = (values.scalar_type() == toComplexType(input.scalar_type())); + bool vectors_expected_type = (vectors.scalar_type() == toComplexType(input.scalar_type())); + + auto expected_values_shape = IntArrayRef(input.sizes().data(), input.dim()-1); // input.shape[:-1] + bool values_equal_expected_shape = values.sizes().equals(expected_values_shape); + bool vectors_equal_expected_shape = vectors.sizes().equals(input.sizes()); + + // if result is not empty and not in batched column major format + bool values_tmp_needed = (values.numel() != 0 && !values.is_contiguous()); + bool vectors_tmp_needed = (vectors.numel() != 0 && !is_batched_column_major); + // or result does not have the expected shape + values_tmp_needed |= (values.numel() != 0 && !values_equal_expected_shape); + vectors_tmp_needed |= (vectors.numel() != 0 && !vectors_equal_expected_shape); + // or result does not have the expected dtype + values_tmp_needed |= !values_expected_type; + vectors_tmp_needed |= !vectors_expected_type; + // we will allocate a temporary tensor and do the copy + + // because MAGMA's GEEV takes CPU inputs and returns CPU outputs + // "out" tensors that are on GPU device can't be used directly + values_tmp_needed |= values.is_cuda(); + vectors_tmp_needed |= vectors.is_cuda(); + + // determine the appropriate scalar_type for the temporary tensors + ScalarType values_type = input.scalar_type(); + ScalarType vectors_type = input.scalar_type(); + if (!input.is_complex()) { + // for real-valued input we can have either real- or complex-valued output + ScalarType input_complex_dtype = toComplexType(input.scalar_type()); + values_type = values.is_complex() ? input_complex_dtype : values_type; + vectors_type = vectors.is_complex() ? input_complex_dtype : vectors_type; + } + + if (values_tmp_needed && vectors_tmp_needed) { + Tensor values_tmp = at::empty({0}, options.dtype(values_type)); + Tensor vectors_tmp = at::empty({0}, options.dtype(vectors_type)); + std::tie(values_tmp, vectors_tmp) = linalg_eig_out_info(input, values_tmp, vectors_tmp, infos, true); + at::native::resize_output(values, values_tmp.sizes()); + values.copy_(values_tmp); + at::native::resize_output(vectors, vectors_tmp.sizes()); + vectors.copy_(vectors_tmp); + } else if (!values_tmp_needed && vectors_tmp_needed) { + // use 'values' storage directly + Tensor vectors_tmp = at::empty({0}, options.dtype(vectors_type)); + std::tie(values, vectors_tmp) = linalg_eig_out_info(input, values, vectors_tmp, infos, true); + at::native::resize_output(vectors, vectors_tmp.sizes()); + vectors.copy_(vectors_tmp); + } else if (values_tmp_needed && !vectors_tmp_needed) { + // use 'vectors' storage directly + Tensor values_tmp = at::empty({0}, options.dtype(values_type)); + std::tie(values_tmp, vectors) = linalg_eig_out_info(input, values_tmp, vectors, infos, true); + at::native::resize_output(values, values_tmp.sizes()); + values.copy_(values_tmp); + } else { + // use 'values' and 'vectors' storage directly + std::tie(values, vectors) = linalg_eig_out_info(input, values, vectors, infos, true); + } + + // Now check LAPACK/MAGMA error codes + at::_linalg_check_errors(infos, "torch.linalg.eig", input.dim() == 2); + return std::tuple(values, vectors); +} + +std::tuple linalg_eig(const Tensor& input) { + ScalarType complex_dtype = toComplexType(input.scalar_type()); + Tensor values = at::empty({0}, input.options().dtype(complex_dtype)); + Tensor vectors = at::empty({0}, input.options().dtype(complex_dtype)); + + at::linalg_eig_outf(input, values, vectors); + + return std::tuple(std::move(values), std::move(vectors)); +} + +Tensor& linalg_eigvals_out(const Tensor& input, Tensor& values) { + squareCheckInputs(input, "linalg.eigvals"); + + // unlike NumPy for real-valued inputs the output is always complex-valued + checkLinalgCompatibleDtype("torch.linalg.eigvals", values.scalar_type(), toComplexType(input.scalar_type()), "eigenvalues"); + checkSameDevice("torch.linalg.eigvals", values, input, "eigenvalues"); + + auto options = input.options(); + auto infos = at::zeros({std::max(1, batchCount(input))}, options.dtype(kInt)); + + bool values_expected_type = (values.scalar_type() == toComplexType(input.scalar_type())); + + auto expected_values_shape = IntArrayRef(input.sizes().data(), input.dim()-1); // input.shape[:-1] + bool values_equal_expected_shape = values.sizes().equals(expected_values_shape); + + // if result is not empty and not in batched column major format + bool values_tmp_needed = (values.numel() != 0 && !values.is_contiguous()); + // or result does not have the expected shape + values_tmp_needed |= (values.numel() != 0 && !values_equal_expected_shape); + // or result does not have the expected dtype + values_tmp_needed |= !values_expected_type; + // we will allocate a temporary tensor and do the copy + + // because MAGMA's GEEV takes CPU inputs and returns CPU outputs + // 'values' tensor that is on GPU device can't be used directly + values_tmp_needed |= (!values.is_cpu()); + + // determine the appropriate scalar_type for the temporary tensors + ScalarType values_type = input.scalar_type(); + if (!input.is_complex()) { + // for real-valued input we can have either real- or complex-valued output + ScalarType input_complex_dtype = toComplexType(input.scalar_type()); + values_type = values.is_complex() ? input_complex_dtype : values_type; + } + + Tensor vectors; + vectors = at::empty({0}, input.options()); + if (values_tmp_needed) { + Tensor values_tmp = at::empty({0}, options.dtype(values_type)); + std::tie(values_tmp, std::ignore) = linalg_eig_out_info(input, values_tmp, vectors, infos, /*compute_eigenvectors=*/false); + at::native::resize_output(values, values_tmp.sizes()); + values.copy_(values_tmp); + } else { // use 'values' storage directly + std::tie(values, std::ignore) = linalg_eig_out_info(input, values, vectors, infos, /*compute_eigenvectors=*/false); + } + + // Now check LAPACK/MAGMA error codes + at::_linalg_check_errors(infos, "torch.linalg.eigvals", input.dim() == 2); + return values; +} + +Tensor linalg_eigvals(const Tensor& input) { + // if input requires grad we must compute the eigenvectors to make this function differentiable + // the eigenvectors are not exposed to the user + if (_may_require_fw_or_bw_grad(input)) { + return std::get<0>(at::linalg_eig(input)); + } + return at::_linalg_eigvals(input); +} + +Tensor _linalg_eigvals(const Tensor& input) { + ScalarType complex_dtype = toComplexType(input.scalar_type()); + Tensor values = at::empty({0}, input.options().dtype(complex_dtype)); + linalg_eigvals_out(input, values); + return values; +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_svd ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +/* torch.svd, implemented in terms of torch.linalg.svd. There are two main + differences: + + 1. the 2nd parameter is bool some=True, which if effectively the opposite + of full_matrices=True + + 2. svd returns V, while linalg.svd returns Vh = V^H +*/ + +DEFINE_DISPATCH(svd_stub); + +TORCH_IMPL_FUNC(_linalg_svd_out)(const Tensor& A, + const bool full_matrices, + const bool compute_uv, + std::optional driver, + const Tensor & U, + const Tensor & S, + const Tensor & Vh) { + // Half optimisation half precondition for some parts of the LAPACK / cuSOLVER + // In particular, the call to lapackSvd to compute lwork fails otherwise + if (A.numel() == 0) { + // Needed in the case that we have e.g. A.shape == (3, 0) and full_matrices=True + // We fill U or Vh with the identity matrix as it's a valid SVD for the empty matrix + if (compute_uv && full_matrices) { + if (U.numel() != 0) { + U.zero_(); + U.diagonal(0, -2, -1).fill_(1.); + } + if (Vh.numel() != 0) { + Vh.zero_(); + Vh.diagonal(0, -2, -1).fill_(1.); + } + } + return; + } + + // We need to distinguish the cuSOLVER case, as cuSOLVER expects F-contig matrices, but + // it computes V rather than Vh + const bool use_cusolver = at::native::svd_uses_cusolver(A); + TORCH_CHECK(use_cusolver || !driver.has_value(), + "torch.linalg.svd: keyword argument `driver=` is only supported on CUDA inputs with cuSOLVER backend."); + + // A always needs to be copied as its contents will be destroyed during the computation of the SVD + // Now, MAGMA needs the copy to be on CPU, while cuSOLVER needs it to be on CUDA, so we'll defer + // the copy as a column major matrix to the backends. + const auto info = at::zeros(IntArrayRef(A.sizes().begin(), A.sizes().end() - 2), A.options().dtype(kInt)); + + svd_stub(A.device().type(), + A, + full_matrices, + compute_uv, + driver, + U, S, Vh, info); + + // TODO This should be removed, and the code checking for convergence should be lifted + // from svd_cusolver to this function. We should then make sure that this function + // never errors out. + at::_linalg_check_errors(info, "linalg.svd", /*is_matrix*/A.dim() == 2); +} + +std::tuple +linalg_svd_out(const Tensor& A, + bool full_matrices, + std::optional driver, + Tensor & U, + Tensor & S, + Tensor & Vh) { + // This function does not have an _ex variant as we always check errors inside + // to assure the convergence of the algorithm anyway. See + // https://github.com/pytorch/pytorch/issues/28293 + // https://github.com/pytorch/pytorch/issues/64237 + // + // We must delegate both linalg_svd and linalg_svdvals to + // _linalg_svd (rather than delegating linalg_svdvals to linalg_svd) because + // 1. We don't want to expose the `compute_uv` parameter in svd + // 2. We would like to make use of the `compute_uv=False` optimisation within svdvals + // The only way to achieve these two things and still abide by the compositionality rules + // is by dispatching to another function. + return at::_linalg_svd_out(U, S, Vh, A, full_matrices, /*compute_uv=*/true, driver); +} + +std::tuple linalg_svd(const Tensor& A, bool full_matrices, + std::optional driver) { + return at::_linalg_svd(A, full_matrices, /*compute_uv=*/true, driver); +} + +// See note in linalg_svd for why this function does not have an _ex variant +Tensor& linalg_svdvals_out(const Tensor& A, std::optional driver, Tensor & S) { + // Dummies + auto U = at::empty({0}, A.options()); + auto Vh = at::empty({0}, A.options()); + at::_linalg_svd_out(U, S, Vh, A, /*full_matrices=*/false, /*compute_uv=*/false, /*driver=*/driver); + return S; +} + +Tensor linalg_svdvals(const Tensor& A, std::optional driver) { + return std::get<1>(at::_linalg_svd(A, /*full_matrices=*/false, + /*compute_uv=*/_may_require_fw_or_bw_grad(A), + /*driver=*/driver)); +} + +std::tuple svd_out(const Tensor& self, bool some, bool compute_uv, + Tensor& U, Tensor& S, Tensor& V) { + + if (compute_uv) { + if (V.dim() >= 2) { + V.transpose_(-2, -1); + } + at::linalg_svd_out(U, S, V, self, /*full_matrices=*/!some); + V.transpose_(-2, -1); + if (V.is_complex()) { + // We cannot use `_set_conj` as it does not play well with backwards + V.conj_physical_(); + } + } else { + TORCH_CHECK(self.scalar_type() == U.scalar_type(), + "torch.svd: Expected out tensor to have dtype ", self.scalar_type(), " but got ", U.scalar_type(), " instead"); + + TORCH_CHECK(self.scalar_type() == V.scalar_type(), + "torch.svd: Expected out tensor to have dtype ", self.scalar_type(), " but got ", V.scalar_type(), " instead"); + + at::linalg_svdvals_out(S, self); + // some == false returns U, Vh of size (m, m), (n, n) full of zeros + const auto m = self.size(-2); + const auto n = self.size(-1); + auto sizes = self.sizes().vec(); + + sizes.end()[-1] = m; + at::native::resize_output(U, sizes); + U.zero_(); + + sizes.end()[-2] = n; + sizes.end()[-1] = n; + at::native::resize_output(V, sizes); + V.zero_(); + } + + return std::tie(U, S, V); +} + +std::tuple svd(const Tensor& self, bool some, bool compute_uv) { + // TODO: uncomment the following when svd is deprecated not only in docs + // torch/xla is blocking the transition from at::svd to at::linalg_svd in at::linalg_pinv code + // see https://github.com/pytorch/xla/issues/2755 + // TORCH_WARN_ONCE( + // "torch.svd is deprecated in favor of torch.linalg.svd and will be ", + // "removed in a future PyTorch release.\n", + // "U, S, V = torch.svd(A, some=some, compute_uv=True) (default)\n", + // "should be replaced with\n", + // "U, S, Vh = torch.linalg.svd(A, full_matrices=not some)\n", + // "V = Vh.mH\n", + // "and\n", + // "_, S, _ = torch.svd(A, some=some, compute_uv=False)\n", + // "should be replaced with\n", + // "S = torch.linalg.svdvals(A)"); + TORCH_CHECK(self.dim() >= 2, "linalg.svd: input should have at least 2 dimensions, but has ", self.dim(), " dimensions instead"); + Tensor U, S, Vh; + if (compute_uv) { + std::tie(U, S, Vh) = at::linalg_svd(self, /*full_matrices=*/!some); + } else { + S = at::linalg_svdvals(self); + // some == false returns U, Vh of size (m, m), (n, n) full of zeros + const auto m = self.size(-2); + const auto n = self.size(-1); + + auto sizes = self.sizes().vec(); + sizes.end()[-1] = m; + U = at::zeros(sizes, self.options()); + sizes.end()[-2] = n; + sizes.end()[-1] = n; + Vh = at::zeros(sizes, self.options()); + } + return std::make_tuple(std::move(U), std::move(S), Vh.mH()); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lstsq ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +DEFINE_DISPATCH(lstsq_stub); + +/* + Solves a least squares problem. That is minimizing the squared Frobenius norm of |B - A X|. + + Input args: + * 'input' - Tensor containing batches of m-by-n matrix A. + * 'other' - Tensor containing batches of max(m, n)-by-nrhs matrix B. + * 'cond' - relative tolerance for determining rank of A. + * 'driver' - the name of the LAPACK driver that is used to compute the solution. + Output args (modified in-place): + * 'solution' - Tensor to store the solution matrix X. + * 'residuals' - Tensor to store values of the residual sum of squares for each column of the solution. + * 'rank' - Tensor to store the rank of A. + * 'singular_values' - Tensor to store the singular values of A. + * 'infos' - Tensor to store error codes of linear algebra math library. + + For further details, please see the LAPACK documentation for GELS/GELSY/GELSS/GELSD routines. +*/ +static void linalg_lstsq_out_info( + Tensor& solution, + Tensor& residuals, + Tensor& rank, + Tensor& singular_values, + Tensor& infos, + const Tensor& input, + const Tensor& other, + double rcond, + std::string& driver) { + // These internal asserts make explicit the assumptions in the implementation + // Error check with the actual error messages are done on the higher level of + // the hierarchy of calls + TORCH_INTERNAL_ASSERT(input.dim() >= 2); + TORCH_INTERNAL_ASSERT(other.dim() >= 1); + + auto dim_diff = input.dim() - other.dim(); + TORCH_INTERNAL_ASSERT(0 <= dim_diff && dim_diff <= 1); + + TORCH_INTERNAL_ASSERT(input.scalar_type() == other.scalar_type()); + TORCH_INTERNAL_ASSERT(input.device() == other.device()); + + TORCH_INTERNAL_ASSERT(solution.scalar_type() == input.scalar_type()); + TORCH_INTERNAL_ASSERT(solution.device() == input.device()); + + TORCH_INTERNAL_ASSERT(residuals.device() == input.device()); + + TORCH_INTERNAL_ASSERT(rank.scalar_type() == at::kLong); + TORCH_INTERNAL_ASSERT(rank.device() == input.device()); + + auto real_dtype = toRealValueType(input.scalar_type()); + TORCH_INTERNAL_ASSERT(singular_values.scalar_type() == real_dtype); + TORCH_INTERNAL_ASSERT(singular_values.device() == input.device()); + + TORCH_INTERNAL_ASSERT(infos.scalar_type() == at::kInt); + TORCH_INTERNAL_ASSERT(infos.device() == input.device()); + TORCH_INTERNAL_ASSERT(infos.numel() == std::max(1, batchCount(input))); + TORCH_INTERNAL_ASSERT(infos.is_contiguous()); + + bool vector_case = linalg_solve_is_vector_rhs(input, other); + // we need to unsqueeze 'other' because 2-dimensional tensors are expected in the implementation + Tensor other_2d = vector_case ? other.unsqueeze(-1) : other; + + TORCH_INTERNAL_ASSERT(input.size(-2) == other_2d.size(-2)); + + std::vector expected_solution_shape = broadcast_batch_size(input, other_2d, input.dim() - 2); + // the actual shape of the solution returned is (*, n,) or (*, n, nrhs) + // but LAPACK requires extra dimensions to store raw residuals + // so the expected shape is (*, max(m, n),) or (*, max(m, n), nrhs) + auto m = input.size(-2); + auto n = input.size(-1); + auto nrhs = other.size(-1); + expected_solution_shape.push_back(std::max(m, n)); + if (!vector_case) { + expected_solution_shape.push_back(nrhs); + } + + // if 'solution' has no elements we can modify it + if (solution.numel() == 0) { + if (vector_case) { + solution.resize_(expected_solution_shape, MemoryFormat::Contiguous); + } else { + auto shape_transposed = expected_solution_shape; + std::swap(shape_transposed.end()[-1], shape_transposed.end()[-2]); + solution.resize_(shape_transposed, MemoryFormat::Contiguous); + solution.transpose_(-2, -1); + } + } + + // if 'solution' is non-empty it must have the expected shape + TORCH_INTERNAL_ASSERT(solution.sizes().equals(expected_solution_shape)); + + // 'solution' must be in batched column major order (Fortran contiguous) for 2D inputs + // or C contiguous for 1D input + if (vector_case) { + TORCH_INTERNAL_ASSERT(solution.is_contiguous()); + } else { + TORCH_INTERNAL_ASSERT(solution.mT().is_contiguous()); + } + + // for 1-dimensional 'other', we need to unsqueeze the 'solution' before passing to "apply_solve" + if (vector_case) { + solution = solution.unsqueeze_(-1); + } + + // _linalg_lstsq_helper_ performs calculations in-place and 'solution' must be a copy of other_2d + solution.narrow(-2, 0, other_2d.size(-2)).copy_(other_2d); + + // if 'rank' is empty we might resize it + auto input_batch_shape = IntArrayRef(input.sizes().cbegin(), input.sizes().cend() - 2); + if (rank.numel() == 0 && driver != "gels") { // gels driver doesn't set 'rank' + rank.resize_(input_batch_shape, MemoryFormat::Contiguous); + } + + // if 'rank' is non-empty it must have the expected shape and be contiguous + if (driver != "gels") { + TORCH_INTERNAL_ASSERT(rank.sizes().equals(input_batch_shape)); + TORCH_INTERNAL_ASSERT(rank.is_contiguous()); + } + + // if 'singular_values' is empty we might resize it + auto singular_values_shape = input_batch_shape.vec(); + singular_values_shape.push_back(std::min(m, n)); + if (singular_values.numel() == 0 && (driver == "gelsd" || driver == "gelss")) { + singular_values.resize_(singular_values_shape, MemoryFormat::Contiguous); + } + + // if 'singular_values' is non-empty it must have the expected shape and be contiguous + if (driver == "gelsd" || driver == "gelss") { + TORCH_INTERNAL_ASSERT(singular_values.sizes().equals(singular_values_shape)); + TORCH_INTERNAL_ASSERT(singular_values.is_contiguous()); + } + + // 'input' is modified in-place so we need a column-major copy + auto input_working_copy = copyBatchedColumnMajor(input); + + // now the actual call that computes the result in-place (apply_lstsq) + lstsq_stub(input.device().type(), input_working_copy, solution, rank, singular_values, infos, rcond, driver); + + // residuals are available only if m > n and drivers other than gelsy used + if (m > n && driver != "gelsy") { + // if the driver is gelss or gelsd then the residuals are available only if rank == n + bool compute_residuals = true; + if (driver == "gelss" || driver == "gelsd") { + if (input.dim() == 2) { + compute_residuals = (rank.item().toInt() == n); + } else { + // it is not clear what to do if some matrices have rank < n in case of batched input + // For now let's compute the residuals only if all matrices have rank equal to n + // This behaviour may be changed in the future + // See https://github.com/pytorch/pytorch/issues/56483 + compute_residuals = at::all(rank == n).item().toBool(); + } + } + if (compute_residuals) { + // LAPACK stores residuals data for postprocessing in rows n:(m-n) + auto raw_residuals = solution.narrow(/*dim=*/-2, /*start=*/n, /*length*/m - n); + if (raw_residuals.is_complex()) { + raw_residuals.mul_(raw_residuals.conj()); + raw_residuals = at::real(raw_residuals); + } else { + raw_residuals.pow_(2); + } + at::sum_out(residuals, raw_residuals, /*dim=*/-2, /*keepdim=*/false, /*dtype*/real_dtype); + } + } + auto solution_view = solution.narrow(/*dim=*/-2, /*start=*/0, /*length*/n); + // manually restride original + solution.set_(solution.storage(), solution_view.storage_offset(), solution_view.sizes(), solution_view.strides()); + if (m == 0) { + solution.zero_(); + } + + // for 1-dimensional 'other', we need to squeeze the solution after "apply_lstsq" + if (vector_case) { + solution.squeeze_(-1); + } +} + +static std::string get_default_lstsq_driver(std::optional driver, const Tensor& input) { + // if `driver` is empty, we set driver_str to "gels" if working with CUDA tensors, + // otherwise to "gelsy" driver. + std::string driver_str; + // check whether the user provided name is a valid driver name + if (driver.has_value()) { + driver_str = std::string(driver.value()); + // convert `driver_str` to lower case inplace. + std::transform(driver_str.begin(), driver_str.end(), driver_str.begin(), + [](unsigned char c) { return std::tolower(c); }); + static std::unordered_set allowed_drivers = { + "gels", "gelsy", "gelsd", "gelss" + }; + // CUDA supports only the 'gels' driver; CPU and MPS support all four. + if (input.is_cuda()) { + TORCH_CHECK( + driver_str == "gels", + "torch.linalg.lstsq: `driver` other than `gels` is not supported on CUDA" + ); + } else { // CPU and MPS + TORCH_CHECK( + allowed_drivers.find(driver_str) != allowed_drivers.end(), + "torch.linalg.lstsq: parameter `driver` should be one of " + "(gels, gelsy, gelsd, gelss)" + ); + } + } else { + // if driver name is not provided, set to default 'gelsy' if on CPU, + // or to `gels` if on CUDA. + driver_str = input.is_cuda() ? "gels" : "gelsy"; + } + return driver_str; +} + +std::tuple linalg_lstsq_out( + const Tensor& input, + const Tensor& other, + std::optional rcond, + std::optional driver, + Tensor& solution, + Tensor& residuals, + Tensor& rank, + Tensor& singular_values) { + TORCH_CHECK(input.dim() >= 2, "torch.linalg.lstsq: input must have at least 2 dimensions."); + TORCH_CHECK(other.dim() >= 1, "torch.linalg.lstsq: other must have at least 1 dimension."); + TORCH_CHECK( + input.scalar_type() == other.scalar_type(), + "torch.linalg.lstsq: Expected input and other to have the same dtype, but got input's dtype ", + input.scalar_type(), + " and other's dtype ", + other.scalar_type()); + + auto dim_diff = input.dim() - other.dim(); + TORCH_CHECK( + 0 <= dim_diff && dim_diff <= 1, + "torch.linalg.lstsq: input.dim() must be greater or equal to other.dim() and (input.dim() - other.dim()) <= 1"); + + // now check whether the provided output tensors can be used directly + + // Two types of 'other' tensors are supported: + // - 1-dimensional (1D) tensor or batch of 1D tensors (vector case) + // - 2-dimensional (2D) tensor or batch of 2D tensors (matrix case) + // original torch.lstsq supported only the matrix case, while NumPy works for both cases + // for the batched input we need to be able to distinguish them + // auto expected_batched_rhs_shape = IntArrayRef(input.sizes().data(), input.dim() - 1); // input.shape[:-1] + // bool vector_case = other.dim() == 1 || (input.dim() - 1 == other.dim() && other.sizes().equals(expected_batched_rhs_shape)); + + bool vector_case = linalg_solve_is_vector_rhs(input, other); + Tensor other_2d = vector_case ? other.unsqueeze(-1) : other; + TORCH_CHECK( + input.size(-2) == other_2d.size(-2), + vector_case ? "torch.linalg.lstsq: input.size(-2) should match other.size(-1)" + : "torch.linalg.lstsq: input.size(-2) should match other.size(-2)"); + + checkSameDevice("torch.linalg.lstsq", other, input, "other"); + checkSameDevice("torch.linalg.lstsq", solution, input, "solution"); + checkSameDevice("torch.linalg.lstsq", residuals, input, "residuals"); + checkSameDevice("torch.linalg.lstsq", rank, input, "rank"); + checkSameDevice("torch.linalg.lstsq", singular_values, input, "singular_values"); + + // 'solution' is expected to have same dtype as input + checkLinalgCompatibleDtype("torch.linalg.lstsq", solution, input, "solution"); + + // 'residuals' is expected to have real float dtype + ScalarType real_dtype = c10::toRealValueType(input.scalar_type()); + checkLinalgCompatibleDtype("torch.linalg.lstsq", residuals.scalar_type(), real_dtype, "solution"); + + // 'rank' is expected to have integer dtype + // actual LAPACK calls use int32_t type for rank, but we promote it to int64_t + // to be consistent with torch.linalg.matrix_rank output dtype + ScalarType rank_expected_type = ScalarType::Long; + checkLinalgCompatibleDtype("torch.linalg.lstsq", rank.scalar_type(), rank_expected_type, "rank"); + + // 'singular_values' is expected to have real float dtype + checkLinalgCompatibleDtype("torch.linalg.lstsq", singular_values.scalar_type(), real_dtype, "singular_values"); + + std::string driver_name = get_default_lstsq_driver(driver, input); + + // set default rcond value + double rcond_value = rcond.has_value() + ? rcond.value() + : _get_epsilon(c10::toRealValueType(input.scalar_type())) * static_cast(std::max(input.size(-2), input.size(-1))); + + auto infos = at::zeros({std::max(1, batchCount(input))}, input.options().dtype(kInt)); + + // provided output tensor can be used directly if: + // 1. the shape matches the expected shape + // 2. the dtype matches the expected dtype + // 3. the tensor is contiguous + + // Checks for the 'solution' tensor + std::vector expected_solution_shape = broadcast_batch_size(input, other_2d, input.dim() - 2); + // the actual shape of the shape of the solution returned in (*, n,) or (*, n, nrhs) + // but LAPACK requires extra dimensions so the expected shape is (*, max(m, n),) or (*, max(m, n), nrhs) + expected_solution_shape.push_back(std::max(input.size(-1), input.size(-2))); + if (!vector_case && other.dim() > 2) { + expected_solution_shape.push_back(other.size(-1)); + } + + bool solution_equal_expected_shape = solution.sizes().equals(expected_solution_shape); + bool solution_input_same_type = (solution.scalar_type() == input.scalar_type()); + + bool is_solution_batched_column_major = false; + if (vector_case) { + is_solution_batched_column_major = solution.is_contiguous(); + } else if (!vector_case && solution.dim() >= 2) { + is_solution_batched_column_major = solution.mT().is_contiguous(); + } + + // 'residuals' is not checked here because at::sum_out(residuals, ...) does that + + auto input_batch_shape = IntArrayRef(input.sizes().cbegin(), input.sizes().cend() - 2); + + // Checks for the 'rank' tensor + // rank is a scalar value for each matrix in the batch so + // rank's expected shape is equal to input.shape[0:input.ndim-2] + bool rank_equal_expected_shape = true; + bool rank_equal_expected_type = true; + bool rank_is_contiguous = true; + if (driver_name != "gels") { // gels driver doesn't set 'rank' + rank_equal_expected_shape = rank.sizes().equals(input_batch_shape); + rank_equal_expected_type = (rank.scalar_type() == at::kLong); + rank_is_contiguous = rank.is_contiguous(); + } + + // Checks for the 'singular_values' tensor + // singular values are computed only with "gelsd" and "gelss" drivers currently + bool singular_values_equal_expected_shape = true; + bool singular_values_equal_expected_type = true; + bool singular_values_is_contiguous = true; + if (driver_name == "gelsd" || driver_name == "gelss") { + auto singular_values_shape = input_batch_shape.vec(); + singular_values_shape.push_back(std::min(input.size(-1), input.size(-2))); + singular_values_equal_expected_shape = singular_values.sizes().equals(singular_values_shape); + singular_values_equal_expected_type = (singular_values.scalar_type() == real_dtype); + singular_values_is_contiguous = singular_values.is_contiguous(); + } + + // if solution is not empty and not in batched column major format + bool copy_needed = (solution.numel() != 0 && !is_solution_batched_column_major); + copy_needed |= !solution_input_same_type; // or solution does not have the same dtype as input + copy_needed |= (solution.numel() != 0 && !solution_equal_expected_shape); // or solution does not have the expected shape + + copy_needed |= !rank_equal_expected_type; + copy_needed |= (rank.numel() != 0 && !rank_equal_expected_shape); + copy_needed |= (rank.numel() != 0 && !rank_is_contiguous); + + copy_needed |= !singular_values_equal_expected_type; + copy_needed |= (singular_values.numel() != 0 && !singular_values_equal_expected_shape); + copy_needed |= (singular_values.numel() != 0 && !singular_values_is_contiguous); + + if (copy_needed) { // we have to allocate temporary tensors + Tensor solution_tmp = at::empty({0}, input.options()); + Tensor residuals_tmp = at::empty({0}, input.options().dtype(real_dtype)); + Tensor rank_tmp = at::empty({0}, input.options().dtype(at::kLong)); + Tensor singular_values_tmp = at::empty({0}, input.options().dtype(real_dtype)); + + linalg_lstsq_out_info(solution_tmp, residuals_tmp, rank_tmp, singular_values_tmp, infos, input, other, rcond_value, driver_name); + + at::native::resize_output(solution, solution_tmp.sizes()); + solution.copy_(solution_tmp); + + at::native::resize_output(residuals, residuals_tmp.sizes()); + residuals.copy_(residuals_tmp); + + at::native::resize_output(rank, rank_tmp.sizes()); + rank.copy_(rank_tmp); + + at::native::resize_output(singular_values, singular_values_tmp.sizes()); + singular_values.copy_(singular_values_tmp); + } else { + // else use the provided output storage directly + linalg_lstsq_out_info(solution, residuals, rank, singular_values, infos, input, other, rcond_value, driver_name); + } + + at::_linalg_check_errors(infos, "torch.linalg.lstsq", infos.numel() <= 1); + return std::tuple(solution, residuals, rank, singular_values); +} + +std::tuple linalg_lstsq( + const Tensor& input, const Tensor& other, + std::optional rcond, + std::optional driver) { + Tensor solution = at::empty({0}, input.options()); + Tensor residuals = at::empty({0}, input.options().dtype(toRealValueType(input.scalar_type()))); + Tensor rank = at::empty({0}, input.options().dtype(at::kLong)); + Tensor singular_values = at::empty({0}, input.options().dtype(toRealValueType(input.scalar_type()))); + std::tie(solution, residuals, rank, singular_values) = + at::linalg_lstsq_outf(input, other, rcond, driver, solution, residuals, rank, singular_values); + return std::make_tuple(std::move(solution), std::move(residuals), std::move(rank), std::move(singular_values)); +} + +DEFINE_DISPATCH(ldl_factor_stub); + +TORCH_IMPL_FUNC(linalg_ldl_factor_ex_out) +(const Tensor& self, + bool hermitian, + bool check_errors, + const Tensor& LD, + const Tensor& pivots, + const Tensor& info) { + // LAPACK workspace query segfalts if the input has 0 in batch dimensions. + if (self.numel() == 0) { + info.zero_(); + return; + } + + // We decided not to include upper flag in the API. + // https://github.com/pytorch/pytorch/pull/69828#issuecomment-1015143819 + // We can revisit this decision later and remove upper completely + // also from low level functions or add it to the public API. + constexpr bool upper = false; + if constexpr (upper) { + at::triu_out(const_cast(LD), self); + } else { + at::tril_out(const_cast(LD), self); + } + + // call ldl_factor_stub that fills the result tensors + ldl_factor_stub( + self.device().type(), LD, pivots, info, upper, hermitian); + + if (check_errors) { + at::_linalg_check_errors( + info, "torch.linalg.ldl_factor_ex", self.dim() == 2); + } +} + +std::tuple linalg_ldl_factor_out( + const Tensor& self, + bool hermitian, + Tensor& LD, + Tensor& pivots) { + auto info = at::empty({0}, self.options().dtype(kInt)); + // We pass check_errors as we want to use lu_factor rather than lu_factor_ex + // in the errors + at::linalg_ldl_factor_ex_outf( + self, hermitian, /*check_errors=*/false, LD, pivots, info); + at::_linalg_check_errors(info, "torch.linalg.ldl_factor", self.dim() == 2); + return std::tie(LD, pivots); +} + +std::tuple linalg_ldl_factor( + const Tensor& self, + bool hermitian) { + auto [LD, pivots, info] = + at::linalg_ldl_factor_ex(self, hermitian, /*check_errors=*/false); + at::_linalg_check_errors(info, "torch.linalg.ldl_factor", self.dim() == 2); + return std::make_tuple(std::move(LD), std::move(pivots)); +} + +DEFINE_DISPATCH(ldl_solve_stub); + +TORCH_IMPL_FUNC(linalg_ldl_solve_out) +(const Tensor& LD, + const Tensor& pivots, + const Tensor& B, + bool hermitian, + const Tensor& result) { + if (LD.numel() == 0 || pivots.numel() == 0) { + return; + } + + auto pivots_ = pivots.expect_contiguous(); + + auto LD_ = at::native::borrow_else_clone( + LD.mT().is_contiguous(), LD, LD, /*contig=*/false); + result.copy_(B); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(batchCount(result) == batchCount(result)); + + ldl_solve_stub( + B.device().type(), *LD_, *pivots_, result, false, hermitian); +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ solve_triangular ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tensor& linalg_vecdot_out(const Tensor& x, const Tensor& y, int64_t dim, Tensor& out) { + checkFloatingOrComplex(x, "linalg.vecdot"); + TORCH_CHECK(x.scalar_type() == y.scalar_type(), + "linalg.vecdot: Expected x and y to have the same dtype, but found x of type ", + x.scalar_type(), " and y of type ", y.scalar_type(), " instead"); + // out checks + TORCH_CHECK(out.scalar_type() == x.scalar_type(), + "linalg.vecdot: Expected out of dtype", x.scalar_type(), + " but found ", out.scalar_type()); + checkSameDevice("linalg.vecdot", x, out); + + // Computes x^H y + if (x.dim() == 1 && y.dim() == 1) { + at::native::resize_output(out, {}); + return at::vdot_out(out, x, y); + } else { + return at::sum_out(out, x.conj() * y, /*dim=*/dim); + } +} + +Tensor linalg_vecdot(const Tensor& x, const Tensor& y, int64_t dim) { + checkFloatingOrComplex(x, "linalg.vecdot"); + TORCH_CHECK(x.scalar_type() == y.scalar_type(), + "linalg.vecdot: Expected x and y to have the same dtype, but found x of type ", + x.scalar_type(), " and y of type ", y.scalar_type(), " instead"); + // Computes x^H y + if (x.dim() == 1 && y.dim() == 1) { + return at::vdot(x, y); + } else { + return x.conj().mul(y).sum(/*dim=*/dim); + } +} + +/* +Solves the matrix equation AX = B for A triangular. +'left' If true solves AX = B, if false solves XA = B +'upper' controls the portion of input matrix to consider in computations, +'unitriangular' if true then we assume diag(A) to be ones +'out' The tensor with the result. If A == out, A will be modified in place +*/ +Tensor& linalg_solve_triangular_out( + const Tensor& A, + const Tensor& B, + bool upper, + bool left, + bool unitriangular, + Tensor& out) { + checkInputsSolver(A, B, left, "linalg.solve_triangular"); + auto [B_, A_] = _linalg_broadcast_batch_dims(B, A, /*don't check errors*/nullptr); + + // We'll write F-contig / F-transpose for FORTRAN contiguous / FORTRAN transpose etc + // We say that a matrix is F-ready if it's F-contig OR F-transpose + // At this point, A, B have been broadcasted but may or may not be F-ready + + // The following algorithm minimises copies and allocations. In pseudocode: + // if out is wrong size: + // resize_output(out) + // # Invariant: out is the right size + // Tensor out_f; # Tensor that we will pass to FORTRAN + // if out is F-ready: + // out_f = out; + // else: + // Allocate out_f F-ready + // if B != out_f: + // copy B into out_f + // # Invariant: out_f F-ready and has B copied into it + // if out_f is F-transposed: + // transpose equation + // if out_f is conj: + // conjugate equation + // # Invariant: out_f is not conjugated and F-contig + // Tensor A_f; # Tensor that will be sent to FORTRAN + // if A is F-ready: + // if A is conj and A is not transposed: + // # We need to clone A in this case. See [Cloning A] + // clone A F-contig into A_f + // else: + // A_f = A; + // else: + // clone A F-contig into A_f + // # Invariant: out_f is F-contig and A_f is F-ready + // # We pass FORTRAN the flags indicating if A_f is transposed and or conjugated + // + // # Here we undo the conjugations / transposes on out_f if needed + // + // if out_f not same out: + // copy out_f into out + // return out + // + // Note: The logic for the negative bit is the same as that for the conjugate bit + // + // Note: [Cloning A] If we are careful when allocating B when it needs to be allocated at the + // beginning of the algorithm, it is possible to always elide the copy of A here. + // Via this trick, the algorithm will copy at most one of A or B (never both) whenever A + // and B are F-ready and not A.is_neg() (which happens almost always in practice). + // When called as f(A, B, out=B) in most practical cases it'll perform no copies. + + const bool avoid_copy_A = A_.transpose(-2, -1).is_contiguous() && A_.is_conj(); + if (avoid_copy_A) { + // See Note: [Cloning A] + at::native::resize_output(out, B_.sizes()); + } + else { + // poorman's reimplementation of resize_output with result F-contig + if (resize_output_check(out, B_.sizes())) { + out.resize_(B_.transpose(-2, -1).sizes(), MemoryFormat::Contiguous); + out.transpose_(-2, -1); // make 'out' have Fortran contiguous memory layout + } + } + // Invariant: out has the right size, so we'll be able to copy into it later on + + Tensor out_f; // the out that will go into fortran + // We use C10_LIKELY mostly for documentation as it helps following what's the most likely path + if C10_LIKELY (is_row_or_column_contiguous(out)) { + out_f = out; + if C10_LIKELY (!out.is_same(B_)) { + out_f.copy_(B_); + } + } else { + if (avoid_copy_A) { + // See Note: [Cloning A] + out_f = B_.clone(at::MemoryFormat::Contiguous); + } + else { + out_f = cloneBatchedColumnMajor(B_); + } + } + // Invariant: out_f F-ready and has B copied into it + + // out_f is F-transposed + bool transpose_A = false; + bool transpose_out_f = false; + if (out_f.stride(-1) == 1) { + left = !left; + transpose_A = true; + transpose_out_f = true; + out_f.transpose_(-2 ,-1); + } + + // No need to conjugate anything if out_f is conj as AX = conj(B) <=> conj(A)conj(X) = B + // and X = B after the algorithm. We just annotate that A is conjugated later on + // The solution will be written into out_f, so it'll be conjugated already + + Tensor A_f = std::move(A_); // The A that will go into fortran + + bool A_is_conj = A_f.is_conj() != out_f.is_conj(); + bool A_is_neg = A_f.is_neg() != out_f.is_neg(); + bool A_is_f_contig = (A_f.stride(-1) == 1) == transpose_A; + if C10_UNLIKELY (!is_row_or_column_contiguous(A_f)) { + // We first annotate with flags on A_f all the conj / transpose / neg coming from out + // and then we clone the resulting tensor to resolve all of them in memory + if (out_f.is_conj()) { + A_f = A_f.conj(); + } + A_is_conj = false; + + if (out_f.is_neg()) { + A_f = A_f._neg_view(); + } + A_is_neg = false; + + // This choice is to be consistent with how we flip `upper` later on + // Note that this is the same reasoning we apply for neg and conj below + // If B has neg or out or transpose, then we need to resolve it in memory + A_f = transpose_A ? A_f.clone(at::MemoryFormat::Contiguous) + : cloneBatchedColumnMajor(A_f); + A_is_f_contig = true; + } else if C10_UNLIKELY (A_is_f_contig && A_is_conj) { + if C10_UNLIKELY (A_f.is_neg() || out_f.is_neg()) { + // Cases A_is_neg (remember that B.is_neg() iff out_f.is_same(B)) + // -AX = -B => A(-X) = B. Swap neg of A_f. Nothing to do on X as X.is_same(B). + // -AX = B. We resolve the neg in memory + // AX = -B => -A -X = B. We resolve the neg in memory for A, + // Since X.is_same(B), we already have that X.is_neg() == true + + // We do the neg with a view, as this will be resolved in the clone below + if (out_f.is_neg()) { + A_f = A_f._neg_view(); + } + A_is_neg = false; + } + // We resolve the transpose if necessary and then leave A_f F-transposed, + // as BLAS can handle the case F-transposed and conjugated + A_f = at::clone(transpose_A ? A_f.mT() : A_f, at::MemoryFormat::Contiguous); + A_is_f_contig = false; + if (transpose_A) { + upper = !upper; + } + // As we've already resolved the conj of A in the clone + A_is_conj = out_f.is_conj(); + } else if C10_UNLIKELY (A_is_neg) { + // We follow the same logic as above, only that in this case we need to perform the + // negation in memory + if (out_f.is_neg()) { + A_f = -A_f; + } else { + A_f = A_f.resolve_neg(); + } + A_is_neg = false; + // As we've already resolved the conj of A in the negationa bove + A_is_conj = out_f.is_conj(); + } + // Invariant: out_f is F-contig and A_f is F-ready + // neg has been resolved + + // If we pass the matrix physically F-transposed, we need to change the parity of upper + if (A_f.stride(-1) == 1) { + upper = !upper; + } + + triangular_solve_stub( + A_f.device().type(), A_f, out_f, + /*left=*/left, + /*upper=*/upper, + /*transpose*/to_transpose_type(A_is_f_contig, A_is_conj), + /*unitriangular=*/unitriangular); + + if (transpose_out_f) { + out_f.transpose_(-2, -1); + } + + if (!out_f.is_same(out)) { + out.copy_(out_f); + } + return out; +} + +Tensor linalg_solve_triangular( + const Tensor& A, + const Tensor& B, + bool upper, + bool left, + bool unitriangular) { + Tensor out = at::empty({0}, A.options()); + linalg_solve_triangular_out(A, B, upper, left, unitriangular, out); + return out; +} + +Tensor linalg_vander_symint( + const Tensor& x, + std::optional N) { + auto t = x.scalar_type(); + TORCH_CHECK(t == ScalarType::Float || + t == ScalarType::Double || + t == ScalarType::ComplexFloat || + t == ScalarType::ComplexDouble || + c10::isIntegralType(t, false), + "linalg.vander supports floating point, complex, and integer tensors, but got ", t); + const auto x_ = x.dim() == 0 ? x.unsqueeze(-1) : x; + + auto shape = x_.sym_sizes().vec(); + const auto n = N.value_or(shape.back()); + TORCH_CHECK(n > 1, "N must be greater than 1."); + + // Append cumprod of the other 0...n-1 powers + shape.push_back(n - 1); + auto result = at::cumprod(x_.unsqueeze(-1).expand_symint(shape), -1); + // The row of ones + shape.back() = 1LL; + auto ones = result.new_ones_symint(shape); + return at::cat({std::move(ones), std::move(result)}, /*dim=*/ -1); +} +// NOLINTEND(cppcoreguidelines-pro-type-const-cast) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebra.h b/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebra.h new file mode 100644 index 0000000000000000000000000000000000000000..1568a03624376701ee56308c99652de847e17e69 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebra.h @@ -0,0 +1,332 @@ +#pragma once + +#include +#include +#include +#include + +// Forward declare TI +namespace at { +class Tensor; +struct TensorIterator; + +namespace native { +enum class TransposeType; +} + +} + +namespace at::native { + +enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss}; + +#if AT_BUILD_WITH_LAPACK() +// Define per-batch functions to be used in the implementation of batched +// linear algebra operations + +template +void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info); + +template +void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info); + +template +void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info); + +template +void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info); + +template +void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info); + +template +void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info); + +template +void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info); + +template +void lapackGels(char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info); + +template +void lapackGelsd(int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + value_t *s, value_t rcond, int *rank, + scalar_t* work, int lwork, + value_t *rwork, int* iwork, int *info); + +template +void lapackGelsy(int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + int *jpvt, value_t rcond, int *rank, + scalar_t *work, int lwork, value_t* rwork, int *info); + +template +void lapackGelss(int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + value_t *s, value_t rcond, int *rank, + scalar_t *work, int lwork, + value_t *rwork, int *info); + +template +struct lapackLstsq_impl; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGels( + trans, m, n, nrhs, + a, lda, b, ldb, + work, lwork, info); + } +}; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGelsy( + m, n, nrhs, + a, lda, b, ldb, + jpvt, rcond, rank, + work, lwork, rwork, info); + } +}; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGelsd( + m, n, nrhs, + a, lda, b, ldb, + s, rcond, rank, + work, lwork, + rwork, iwork, info); + } +}; + +template +struct lapackLstsq_impl { + static void call( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackGelss( + m, n, nrhs, + a, lda, b, ldb, + s, rcond, rank, + work, lwork, + rwork, info); + } +}; + +template +void lapackLstsq( + char trans, int m, int n, int nrhs, + scalar_t *a, int lda, scalar_t *b, int ldb, + scalar_t *work, int lwork, int *info, // Gels flavor + int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor + value_t *s, // Gelss flavor + int *iwork // Gelsd flavor + ) { + lapackLstsq_impl::call( + trans, m, n, nrhs, + a, lda, b, ldb, + work, lwork, info, + jpvt, rcond, rank, rwork, + s, + iwork); +} + +template +void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info); + +template +void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info); + +template +void lapackLdlHermitian( + char uplo, + int n, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* work, + int lwork, + int* info); + +template +void lapackLdlSymmetric( + char uplo, + int n, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* work, + int lwork, + int* info); + +template +void lapackLdlSolveHermitian( + char uplo, + int n, + int nrhs, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* b, + int ldb, + int* info); + +template +void lapackLdlSolveSymmetric( + char uplo, + int n, + int nrhs, + scalar_t* a, + int lda, + int* ipiv, + scalar_t* b, + int ldb, + int* info); + +template +void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info); +#endif + +#if AT_BUILD_WITH_BLAS() +template +void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb); +#endif + +using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/); +DECLARE_DISPATCH(cholesky_fn, cholesky_stub) + +using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/); + +DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub) + +using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/); + +DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub) + +// Converts LAPACK's real-valued eigenvector encoding to complex eigenvectors +TORCH_API void linalg_eig_make_complex_eigenvectors( + const Tensor& complex_vectors, + const Tensor& complex_values, + const Tensor& real_vectors); + +DECLARE_DISPATCH( + void(*)(const Tensor&, const Tensor&, const Tensor&), + linalg_eig_make_complex_eigenvectors_stub) + + +using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/); +DECLARE_DISPATCH(geqrf_fn, geqrf_stub) + +using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/); +DECLARE_DISPATCH(orgqr_fn, orgqr_stub) + +using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/); +DECLARE_DISPATCH(ormqr_fn, ormqr_stub) + +using linalg_eigh_fn = void (*)( + const Tensor& /*eigenvalues*/, + const Tensor& /*eigenvectors*/, + const Tensor& /*infos*/, + bool /*upper*/, + bool /*compute_eigenvectors*/); +DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub) + +using lstsq_fn = void (*)( + const Tensor& /*a*/, + Tensor& /*b*/, + Tensor& /*rank*/, + Tensor& /*singular_values*/, + Tensor& /*infos*/, + double /*rcond*/, + std::string /*driver_name*/); +DECLARE_DISPATCH(lstsq_fn, lstsq_stub) + +using triangular_solve_fn = void (*)( + const Tensor& /*A*/, + const Tensor& /*B*/, + bool /*left*/, + bool /*upper*/, + TransposeType /*transpose*/, + bool /*unitriangular*/); +DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub) + +using lu_factor_fn = void (*)( + const Tensor& /*input*/, + const Tensor& /*pivots*/, + const Tensor& /*infos*/, + bool /*compute_pivots*/); +DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub) + +using unpack_pivots_fn = void(*)( + TensorIterator& iter, + const int64_t dim_size, + const int64_t max_pivot); +DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub) + +using lu_solve_fn = void (*)( + const Tensor& /*LU*/, + const Tensor& /*pivots*/, + const Tensor& /*B*/, + TransposeType /*trans*/); +DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub) + +using ldl_factor_fn = void (*)( + const Tensor& /*LD*/, + const Tensor& /*pivots*/, + const Tensor& /*info*/, + bool /*upper*/, + bool /*hermitian*/); +DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub) + +using svd_fn = void (*)( + const Tensor& /*A*/, + const bool /*full_matrices*/, + const bool /*compute_uv*/, + const std::optional& /*driver*/, + const Tensor& /*U*/, + const Tensor& /*S*/, + const Tensor& /*Vh*/, + const Tensor& /*info*/); +DECLARE_DISPATCH(svd_fn, svd_stub) + +using ldl_solve_fn = void (*)( + const Tensor& /*LD*/, + const Tensor& /*pivots*/, + const Tensor& /*result*/, + bool /*upper*/, + bool /*hermitian*/); +DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebraKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebraKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a38a657eb7e386505e9ac7c3f30121851c9dbad --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BatchLinearAlgebraKernel.cpp @@ -0,0 +1,1244 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include + +#include +#endif +namespace at::native { + +namespace { +/* + Computes the Cholesky decomposition of matrices stored in `input`. + This is an in-place routine and the content of 'input' is overwritten with the result. + + Args: + * `input` - [in] Input tensor for the Cholesky decomposition + [out] Cholesky decomposition result + * `info` - [out] Tensor filled with LAPACK error codes, + positive values indicate that the matrix is not positive definite. + * `upper` - controls whether the upper (true) or lower (false) triangular portion of `input` is used + + For further details, please see the LAPACK documentation for POTRF. +*/ +template +void apply_cholesky(const Tensor& input, const Tensor& info, bool upper) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.linalg.cholesky on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + char uplo = upper ? 'U' : 'L'; + auto input_data = input.data_ptr(); + auto info_data = info.data_ptr(); + auto input_matrix_stride = matrixStride(input); + auto batch_size = batchCount(input); + auto n = input.size(-2); + auto lda = std::max(1, n); + + for (const auto i : c10::irange(batch_size)) { + scalar_t* input_working_ptr = &input_data[i * input_matrix_stride]; + int* info_working_ptr = &info_data[i]; + lapackCholesky(uplo, n, input_working_ptr, lda, info_working_ptr); + } +#endif +} + +// This is a type dispatching helper function for 'apply_cholesky' +void cholesky_kernel(const Tensor& input, const Tensor& infos, bool upper) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "cholesky_cpu", [&]{ + apply_cholesky(input, infos, upper); + }); +} + +/* +Copies the lower (or upper) triangle of the square matrix to the other half and conjugates it. +This operation is performed in-place. +*/ +template +void apply_reflect_conj_tri_single(scalar_t* self, int64_t n, int64_t stride, bool upper) { + std::function loop = [](int64_t, int64_t){}; + if (upper) { + loop = [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + for (int64_t j = i + 1; j < n; j++) { + self[i * stride + j] = conj_impl(self[j * stride + i]); + } + } + }; + } else { + loop = [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + for (const auto j : c10::irange(i)) { + self[i * stride + j] = conj_impl(self[j * stride + i]); + } + } + }; + } + // For small matrices OpenMP overhead is too large + if (n < 256) { + loop(0, n); + } else { + at::parallel_for(0, n, 0, loop); + } +} + +/* +Computes the inverse of a symmetric (Hermitian) positive-definite matrix n-by-n matrix 'input' using the Cholesky factorization +This is an in-place routine, content of 'input' is overwritten. +'infos' is an int Tensor containing error codes for each matrix in the batched input. +For more information see LAPACK's documentation for POTRI routine. +*/ +template +void apply_cholesky_inverse(Tensor& input, Tensor& infos, bool upper) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK(false, "cholesky_inverse: LAPACK library not found in compilation"); +#else + char uplo = upper ? 'U' : 'L'; + + auto input_data = input.data_ptr(); + auto infos_data = infos.data_ptr(); + auto input_matrix_stride = matrixStride(input); + auto batch_size = batchCount(input); + auto n = input.size(-2); + auto lda = std::max(1, n); + + for (const auto i : c10::irange(batch_size)) { + scalar_t* input_working_ptr = &input_data[i * input_matrix_stride]; + int* info_working_ptr = &infos_data[i]; + lapackCholeskyInverse(uplo, n, input_working_ptr, lda, info_working_ptr); + // LAPACK writes to only upper/lower part of the matrix leaving the other side unchanged + apply_reflect_conj_tri_single(input_working_ptr, n, lda, upper); + } +#endif +} + +// This is a type dispatching helper function for 'apply_cholesky_inverse' +Tensor& cholesky_inverse_kernel_impl(Tensor& result, Tensor& infos, bool upper) { + // This function calculates the inverse matrix in-place + // result should be in column major order and contain matrices to invert + // the content of result is overwritten by 'apply_cholesky_inverse' + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(result.scalar_type(), "cholesky_inverse_out_cpu", [&]{ + apply_cholesky_inverse(result, infos, upper); + }); + return result; +} + +// This function returns complex-valued eigenvectors that is obtained from LAPACK GEEV's real-valued output +// This function is also used for the MAGMA path because intermediate MAGMA's results live on CPU +template +static void linalg_eig_make_complex_eigenvectors_cpu_impl(const Tensor& result, const Tensor& complex_values, const Tensor& real_vectors) { + // From GEEV documentation: + // Complex conjugate pairs of eigenvalues appear consecutively with the eigenvalue having the positive imaginary part first + // If the j-th eigenvalue is real, then v(j) = VR(:,j), the j-th column of VR. + // If the j-th and (j+1)-st eigenvalues form a complex conjugate pair, then v(j) = VR(:,j) + i*VR(:,j+1) and v(j+1) = VR(:,j) - i*VR(:,j+1). + + auto batch_size = batchCount(real_vectors); + auto n = real_vectors.size(-1); + auto matrix_stride = matrixStride(real_vectors); + + auto result_data = result.data_ptr>(); + auto real_vectors_data = real_vectors.const_data_ptr(); + auto values_data = complex_values.const_data_ptr>(); + + for (auto b = decltype(batch_size){0}; b < batch_size; b++) { + const scalar_t* vecs = &real_vectors_data[b * matrix_stride]; + c10::complex* res = &result_data[b * matrix_stride]; + const c10::complex* vals = &values_data[b * n]; + for (auto j = decltype(n){0}; j < n; j++) { + if (vals[j].imag() == 0.0) { // eigenvalue is real, then v(j) = VR(:,j) + for (auto i = decltype(n){0}; i < n; i++) { + res[j * n + i] = c10::complex(vecs[j * n + i], 0); + } + } else { + for (auto i = decltype(n){0}; i < n; i++) { + res[j * n + i] = c10::complex(vecs[j * n + i], vecs[(j+1) * n + i]); // v(j) = VR(:,j) + i*VR(:,j+1) + res[(j+1) * n + i] = c10::complex(vecs[j * n + i], -vecs[(j+1) * n + i]); // v(j+1) = VR(:,j) - i*VR(:,j+1) + } + j++; + } + } + } +} + +// CPU dispatch kernel +void linalg_eig_make_complex_eigenvectors_cpu(const Tensor& complex_vectors, const Tensor& complex_values, const Tensor& real_vectors) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(complex_vectors.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(complex_values.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(real_vectors.mT().is_contiguous()); + + AT_DISPATCH_V2( + real_vectors.scalar_type(), + "linalg_eig_make_complex_eigenvectors_cpu", + AT_WRAP([&] { + linalg_eig_make_complex_eigenvectors_cpu_impl( + complex_vectors, complex_values, real_vectors); + }), + AT_EXPAND(AT_FLOATING_TYPES)); +} + +/* + LAPACK query functions return workspace size as floating point value, which means + that it might not be accurately represented if it's size exceed mantissa of the + corresponding type. Fix it by adding 1ULP to the value before casting to it + For more info see https://github.com/pytorch/pytorch/issues/145801#issuecomment-2631781776 +*/ +template +inline +std::enable_if_t, int> lapack_work_to_int(const T val) { + const auto next_after = std::nextafter(val, std::numeric_limits::infinity()); + return std::max(1, std::ceil(next_after)); +} +template +inline +std::enable_if_t::value, int> lapack_work_to_int(const T val) { + return lapack_work_to_int(val.real()); +} + + +/* + Computes the eigenvalues and eigenvectors of n-by-n matrix 'input'. + This is an in-place routine, content of 'input', 'values', 'vectors' is overwritten. + 'infos' is an int Tensor containing error codes for each matrix in the batched input. + For more information see LAPACK's documentation for GEEV routine. +*/ +template +void apply_linalg_eig(Tensor& values, Tensor& vectors, Tensor& input, Tensor& infos, bool compute_eigenvectors) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK(false, "Calling torch.linalg.eig on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + using value_t = typename c10::scalar_value_type::type; + + char jobvr = compute_eigenvectors ? 'V' : 'N'; + char jobvl = 'N'; // only right eigenvectors are computed + auto n = input.size(-1); + auto lda = std::max(1, n); + auto batch_size = batchCount(input); + auto input_matrix_stride = matrixStride(input); + auto values_stride = values.size(-1); + auto input_data = input.data_ptr(); + auto values_data = values.data_ptr(); + auto infos_data = infos.data_ptr(); + auto rvectors_data = compute_eigenvectors ? vectors.data_ptr() : nullptr; + scalar_t* lvectors_data = nullptr; // only right eigenvectors are computed + int64_t ldvr = compute_eigenvectors ? lda : 1; + int64_t ldvl = 1; + + Tensor rwork; + value_t* rwork_data = nullptr; + if (input.is_complex()) { + ScalarType real_dtype = toRealValueType(input.scalar_type()); + rwork = at::empty({lda * 2}, input.options().dtype(real_dtype)); + rwork_data = rwork.mutable_data_ptr(); + } + + // call lapackEig once to get the optimal size for work data + scalar_t work_query; + lapackEig(jobvl, jobvr, n, input_data, lda, values_data, + lvectors_data, ldvl, rvectors_data, ldvr, &work_query, -1, rwork_data, &infos_data[0]); + + int lwork = lapack_work_to_int(work_query); + Tensor work = at::empty({lwork}, input.dtype()); + auto work_data = work.mutable_data_ptr(); + + for (const auto i : c10::irange(batch_size)) { + scalar_t* input_working_ptr = &input_data[i * input_matrix_stride]; + scalar_t* values_working_ptr = &values_data[i * values_stride]; + scalar_t* rvectors_working_ptr = compute_eigenvectors ? &rvectors_data[i * input_matrix_stride] : nullptr; + int* info_working_ptr = &infos_data[i]; + lapackEig(jobvl, jobvr, n, input_working_ptr, lda, values_working_ptr, + lvectors_data, ldvl, rvectors_working_ptr, ldvr, work_data, lwork, rwork_data, info_working_ptr); + } +#endif +} + +// This is a type dispatching helper function for 'apply_linalg_eig' +void linalg_eig_kernel(Tensor& eigenvalues, Tensor& eigenvectors, Tensor& infos, const Tensor& input, bool compute_eigenvectors) { + // This function calculates the non-symmetric eigendecomposition in-place + // tensors should be in batched column major memory format + // the content of eigenvalues, eigenvectors and infos is overwritten by 'apply_linalg_eig' + + // apply_linalg_eig modifies in-place provided input matrix, therefore we need a copy + Tensor input_working_copy = at::empty(input.mT().sizes(), input.options()); + input_working_copy.transpose_(-2, -1); // make input_working_copy to have Fortran contiguous memory layout + input_working_copy.copy_(input); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "linalg_eig_out_cpu", [&]{ + apply_linalg_eig(eigenvalues, eigenvectors, input_working_copy, infos, compute_eigenvectors); + }); +} + +/* + Computes eigenvalues and eigenvectors of the input that is stored initially in 'vectors'. + The computation is done in-place: 'vectors' stores the input and will be overwritten, + 'values' should be an allocated empty array. + 'infos' is used to store information for possible checks for error. + 'upper' controls the portion of input matrix to consider in computations + 'compute_eigenvectors' controls whether eigenvectors should be computed. + This function doesn't do any error checks and it's assumed that every argument is valid. +*/ + + +template +void apply_lapack_eigh(const Tensor& values, const Tensor& vectors, const Tensor& infos, bool upper, bool compute_eigenvectors) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.linalg.eigh or eigvalsh on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + using value_t = typename c10::scalar_value_type::type; + + char uplo = upper ? 'U' : 'L'; + char jobz = compute_eigenvectors ? 'V' : 'N'; + + auto n = vectors.size(-1); + auto lda = std::max(1, n); + auto batch_size = batchCount(vectors); + + auto vectors_stride = matrixStride(vectors); + auto values_stride = values.size(-1); + + auto vectors_data = vectors.data_ptr(); + auto values_data = values.data_ptr(); + auto infos_data = infos.data_ptr(); + + // Using 'int' instead of int32_t or int64_t is consistent with the current LAPACK interface + // It really should be changed in the future to something like lapack_int that depends on the specific LAPACK library that is linked + // or switch to supporting only 64-bit indexing by default. + int lwork = -1; + int lrwork = -1; + int liwork = -1; + scalar_t lwork_query; + value_t rwork_query; + int iwork_query = 0; + + // call lapackSyevd once to get the optimal size for work data + lapackSyevd(jobz, uplo, n, vectors_data, lda, values_data, + &lwork_query, lwork, &rwork_query, lrwork, &iwork_query, liwork, infos_data); + + lwork = lapack_work_to_int(lwork_query); + + Tensor work = at::empty({lwork}, vectors.options()); + auto work_data = work.mutable_data_ptr(); + + liwork = std::max(1, iwork_query); + Tensor iwork = at::empty({liwork}, vectors.options().dtype(at::kInt)); + auto iwork_data = iwork.mutable_data_ptr(); + + Tensor rwork; + value_t* rwork_data = nullptr; + if (vectors.is_complex()) { + lrwork = lapack_work_to_int(rwork_query); + rwork = at::empty({lrwork}, values.options()); + rwork_data = rwork.mutable_data_ptr(); + } + + // Now call lapackSyevd for each matrix in the batched input + for (const auto i : c10::irange(batch_size)) { + scalar_t* vectors_working_ptr = &vectors_data[i * vectors_stride]; + value_t* values_working_ptr = &values_data[i * values_stride]; + int* info_working_ptr = &infos_data[i]; + lapackSyevd(jobz, uplo, n, vectors_working_ptr, lda, values_working_ptr, + work_data, lwork, rwork_data, lrwork, iwork_data, liwork, info_working_ptr); + // The current behaviour for Linear Algebra functions to raise an error if something goes wrong + // or input doesn't satisfy some requirement + // therefore return early since further computations will be wasted anyway + if (*info_working_ptr != 0) { + return; + } + } +#endif +} + +// This is a type dispatching helper function for 'apply_lapack_eigh' +void linalg_eigh_kernel(const Tensor& eigenvalues, const Tensor& eigenvectors, const Tensor& infos, bool upper, bool compute_eigenvectors) { + // This function calculates the symmetric/hermitian eigendecomposition + // in-place tensors should be in batched column major memory format the + // content of eigenvalues, eigenvectors and infos is overwritten by + // 'apply_lapack_eigh' + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES( + eigenvectors.scalar_type(), "linalg_eigh_cpu", [&] { + apply_lapack_eigh( + eigenvalues, eigenvectors, infos, upper, compute_eigenvectors); + }); +} + +/* + The geqrf function computes the QR decomposition of matrices stored in `input`. + However, rather than producing a Q matrix directly, it produces a sequence of + elementary reflectors which may later be composed to construct Q - for example + with the orgqr or ormqr functions. + + Args: + * `input` - [in] Input tensor for QR decomposition + [out] QR decomposition result which contains: + i) The elements of R, on and above the diagonal. + ii) Directions of the reflectors implicitly defining Q. + Tensor with the directions of the elementary reflectors below the diagonal, + it will be overwritten with the result + * `tau` - [out] Tensor which will contain the magnitudes of the reflectors + implicitly defining Q. + + For further details, please see the LAPACK documentation for GEQRF. +*/ +template +void apply_geqrf(const Tensor& input, const Tensor& tau) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.geqrf on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + auto input_data = input.data_ptr(); + auto tau_data = tau.data_ptr(); + auto input_matrix_stride = matrixStride(input); + auto tau_stride = tau.size(-1); + auto batch_size = batchCount(input); + auto m = input.size(-2); + auto n = input.size(-1); + auto lda = std::max(1, m); + + int info = 0; + // Run once, first to get the optimum work size. + // Since we deal with batches of matrices with the same dimensions, doing this outside + // the loop saves (batch_size - 1) workspace queries which would provide the same result + // and (batch_size - 1) calls to allocate and deallocate workspace using at::empty() + int lwork = -1; + scalar_t wkopt; + lapackGeqrf(m, n, input_data, lda, tau_data, &wkopt, lwork, &info); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + + // if lwork is less than 'n' then a warning is printed: + // Intel MKL ERROR: Parameter 7 was incorrect on entry to SGEQRF. + lwork = std::max(static_cast(n), lapack_work_to_int(wkopt)); + Tensor work = at::empty({lwork}, input.options()); + + for (const auto i : c10::irange(batch_size)) { + scalar_t* input_working_ptr = &input_data[i * input_matrix_stride]; + scalar_t* tau_working_ptr = &tau_data[i * tau_stride]; + + // now compute the actual QR and tau + lapackGeqrf(m, n, input_working_ptr, lda, tau_working_ptr, work.data_ptr(), lwork, &info); + + // info from lapackGeqrf only reports if the i-th parameter is wrong + // so we don't need to check it all the time + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + } +#endif +} + +// This is a type dispatching helper function for 'apply_geqrf' +void geqrf_kernel(const Tensor& input, const Tensor& tau) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "geqrf_cpu", [&]{ + apply_geqrf(input, tau); + }); +} + +/* + The orgqr function allows reconstruction of an orthogonal (or unitary) matrix Q, + from a sequence of elementary reflectors, such as produced by the geqrf function. + + Args: + * `self` - Tensor with the directions of the elementary reflectors below the diagonal, + it will be overwritten with the result + * `tau` - Tensor containing the magnitudes of the elementary reflectors + + For further details, please see the LAPACK documentation for ORGQR and UNGQR. +*/ +template +inline void apply_orgqr(Tensor& self, const Tensor& tau) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK(false, "Calling torch.orgqr on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + // Some LAPACK implementations might not work well with empty matrices: + // workspace query might return lwork as 0, which is not allowed (requirement is lwork >= 1) + // We don't need to do any calculations in this case, so let's return early + if (self.numel() == 0) { + return; + } + + auto self_data = self.data_ptr(); + auto tau_data = tau.const_data_ptr(); + auto self_matrix_stride = matrixStride(self); + auto tau_stride = tau.size(-1); + auto batch_size = batchCount(self); + auto m = self.size(-2); + auto n = self.size(-1); + auto k = tau.size(-1); + auto lda = std::max(1, m); + int info = 0; + + // LAPACK's requirement + TORCH_INTERNAL_ASSERT(m >= n); + TORCH_INTERNAL_ASSERT(n >= k); + + // Run once, first to get the optimum work size. + // Since we deal with batches of matrices with the same dimensions, doing this outside + // the loop saves (batch_size - 1) workspace queries which would provide the same result + // and (batch_size - 1) calls to allocate and deallocate workspace using at::empty() + int lwork = -1; + scalar_t wkopt; + lapackOrgqr(m, n, k, self_data, lda, const_cast(tau_data), &wkopt, lwork, &info); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + lwork = lapack_work_to_int(wkopt); + Tensor work = at::empty({lwork}, self.options()); + + for (const auto i : c10::irange(batch_size)) { + scalar_t* self_working_ptr = &self_data[i * self_matrix_stride]; + const scalar_t* tau_working_ptr = &tau_data[i * tau_stride]; + + // now compute the actual Q + lapackOrgqr(m, n, k, self_working_ptr, lda, const_cast(tau_working_ptr), work.data_ptr(), lwork, &info); + + // info from lapackOrgqr only reports if the i-th parameter is wrong + // so we don't need to check it all the time + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + } +#endif +} + +// This is a type dispatching helper function for 'apply_orgqr' +Tensor& orgqr_kernel_impl(Tensor& result, const Tensor& tau) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(result.scalar_type(), "orgqr_cpu", [&]{ + apply_orgqr(result, tau); + }); + return result; +} + +/* + Solves a least squares problem. That is minimizing ||B - A X||. + + Input args: + * 'input' - Tensor containing batches of m-by-n matrix A. + * 'other' - Tensor containing batches of max(m, n)-by-nrhs matrix B. + * 'cond' - relative tolerance for determining rank of A. + * 'driver' - the name of the LAPACK driver that is used to compute the solution. + Output args (modified in-place): + * 'solution' - Tensor to store the solution matrix X. + * 'residuals' - Tensor to store values of ||B - A X||. + * 'rank' - Tensor to store the rank of A. + * 'singular_values' - Tensor to store the singular values of A. + * 'infos' - Tensor to store error codes of linear algebra math library. + + For further details, please see the LAPACK documentation for GELS/GELSY/GELSS/GELSD routines. +*/ +template +void apply_lstsq(const Tensor& A, Tensor& B, Tensor& rank, Tensor& singular_values, Tensor& infos, double rcond, LapackLstsqDriverType driver_type) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.linalg.lstsq on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + using value_t = typename c10::scalar_value_type::type; + using driver_t = at::native::LapackLstsqDriverType; + + auto lapack_func = lapackLstsq; + static auto driver_type_to_func + = std::unordered_map({ + {driver_t::Gels, lapackLstsq}, + {driver_t::Gelsy, lapackLstsq}, + {driver_t::Gelsd, lapackLstsq}, + {driver_t::Gelss, lapackLstsq} + }); + lapack_func = driver_type_to_func[driver_type]; + + char trans = 'N'; + + auto A_data = A.data_ptr(); + auto B_data = B.data_ptr(); + auto m = A.size(-2); + auto n = A.size(-1); + auto nrhs = B.size(-1); + auto lda = std::max(1, m); + auto ldb = std::max({static_cast(1), m, n}); + auto infos_data = infos.data_ptr(); + + // only 'gels' driver does not compute the rank + int rank_32 = 0; + int64_t* rank_data = nullptr; + int64_t* rank_working_ptr = nullptr; + if (driver_t::Gels != driver_type) { + rank_data = rank.data_ptr(); + rank_working_ptr = rank_data; + } + + // 'gelsd' and 'gelss' are SVD-based algorithms + // so we can get singular values + value_t* s_data = nullptr; + value_t* s_working_ptr = nullptr; + int64_t s_stride = 0; + if (driver_t::Gelsd == driver_type || driver_t::Gelss == driver_type) { + s_data = singular_values.data_ptr(); + s_working_ptr = s_data; + s_stride = singular_values.size(-1); + } + + // 'jpvt' workspace array is used only for 'gelsy' which uses QR factorization with column pivoting + Tensor jpvt; + int* jpvt_data = nullptr; + if (driver_t::Gelsy == driver_type) { + jpvt = at::zeros({std::max(1, n)}, A.options().dtype(at::kInt)); + jpvt_data = jpvt.mutable_data_ptr(); + } + + // Run once the driver, first to get the optimal workspace size + int lwork = -1; // default value to decide the opt size for workspace arrays + scalar_t work_opt; + value_t rwork_opt; + int iwork_opt = 0; + lapack_func(trans, m, n, nrhs, + A_data, lda, + B_data, ldb, + &work_opt, lwork, + infos_data, + jpvt_data, + static_cast(rcond), + &rank_32, + &rwork_opt, + s_working_ptr, + &iwork_opt); + + lwork = lapack_work_to_int(work_opt); + Tensor work = at::empty({lwork}, A.options()); + scalar_t* work_data = work.mutable_data_ptr(); + + // 'rwork' only used for complex inputs and 'gelsy', 'gelsd' and 'gelss' drivers + Tensor rwork; + value_t* rwork_data = nullptr; + if (A.is_complex() && driver_t::Gels != driver_type) { + int64_t rwork_len = 0; + switch (driver_type) { + case driver_t::Gelsy: + rwork_len = std::max(1, 2 * n); + break; + case driver_t::Gelss: + rwork_len = std::max(1, 5 * std::min(m, n)); + break; + // case driver_t::Gelsd: + default: + rwork_len = std::max(1, rwork_opt); + } + rwork = at::empty({rwork_len}, A.options().dtype(c10::toRealValueType(A.scalar_type()))); + rwork_data = rwork.mutable_data_ptr(); + } + + // 'iwork' workspace array is relevant only for 'gelsd' + Tensor iwork; + int* iwork_data = nullptr; + if (driver_t::Gelsd == driver_type) { + iwork = at::empty({std::max(1, iwork_opt)}, A.options().dtype(at::kInt)); + iwork_data = iwork.mutable_data_ptr(); + } + + at::native::batch_iterator_with_broadcasting(A, B, + [&](scalar_t* A_working_ptr, scalar_t* B_working_ptr, int64_t A_linear_batch_idx) { + rank_working_ptr = rank_working_ptr ? &rank_data[A_linear_batch_idx] : nullptr; + s_working_ptr = s_working_ptr ? &s_data[A_linear_batch_idx * s_stride] : nullptr; + int* infos_working_ptr = &infos_data[A_linear_batch_idx]; + + // JPVT is an input/output argument for *gelsy. Non-zero values on + // input mark fixed columns, so reset it before each call. + if (jpvt_data != nullptr) { + jpvt.zero_(); + } + + lapack_func(trans, m, n, nrhs, + A_working_ptr, lda, + B_working_ptr, ldb, + work_data, lwork, + infos_working_ptr, + jpvt_data, + static_cast(rcond), + &rank_32, + rwork_data, + s_working_ptr, + iwork_data); + + // we want the output `rank` Tensor to be of type int64_t, + // however LAPACK accepts int. That is why we use an integer + // variable that then gets promoted and written into `rank`. + // We use this approach over a tensor cast for better performance. + if (rank_working_ptr) { + *rank_working_ptr = static_cast(rank_32); + } + } + ); +#endif +} + +// This is a type and driver dispatching helper function for 'apply_lstsq' +void lstsq_kernel(const Tensor& a, Tensor& b, Tensor& rank, Tensor& singular_values, Tensor& infos, double rcond, std::string driver_name) { + + static auto driver_string_to_type = std::unordered_map({ + {"gels", at::native::LapackLstsqDriverType::Gels}, + {"gelsy", at::native::LapackLstsqDriverType::Gelsy}, + {"gelsd", at::native::LapackLstsqDriverType::Gelsd}, + {"gelss", at::native::LapackLstsqDriverType::Gelss} + }); + auto driver_type = driver_string_to_type[driver_name]; + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(a.scalar_type(), "linalg_lstsq_cpu", [&]{ + apply_lstsq(a, b, rank, singular_values, infos, rcond, driver_type); + }); +} + +/* + The ormqr function multiplies Q with another matrix from a sequence of + elementary reflectors, such as is produced by the geqrf function. + + Args: + * `input` - Tensor with elementary reflectors below the diagonal, + encoding the matrix Q. + * `tau` - Tensor containing the magnitudes of the elementary + reflectors. + * `other` - [in] Tensor containing the matrix to be multiplied. + [out] result of the matrix multiplication with Q. + * `left` - bool, determining whether `other` is left- or right-multiplied with Q. + * `transpose` - bool, determining whether to transpose (or conjugate transpose) Q before multiplying. + + For further details, please see the LAPACK documentation. +*/ +template +void apply_ormqr(const Tensor& input, const Tensor& tau, const Tensor& other, bool left, bool transpose) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK(false, "Calling torch.ormqr on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + using value_t = typename c10::scalar_value_type::type; + + char side = left ? 'L' : 'R'; + char trans = transpose ? (input.is_complex() ? 'C' : 'T') : 'N'; + + auto input_data = input.const_data_ptr(); + auto tau_data = tau.const_data_ptr(); + auto other_data = other.data_ptr(); + + auto input_matrix_stride = matrixStride(input); + auto other_matrix_stride = matrixStride(other); + auto tau_stride = tau.size(-1); + auto batch_size = batchCount(input); + auto m = other.size(-2); + auto n = other.size(-1); + auto k = tau.size(-1); + auto lda = std::max(1, left ? m : n); + auto ldc = std::max(1, m); + int info = 0; + + // LAPACK's requirement + TORCH_INTERNAL_ASSERT_DEBUG_ONLY((left ? m : n) >= k); + + // Query for the optimal size of the workspace tensor + int lwork = -1; + scalar_t wkopt; + lapackOrmqr(side, trans, m, n, k, const_cast(input_data), lda, const_cast(tau_data), other_data, ldc, &wkopt, lwork, &info); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + lwork = std::max(1, real_impl(wkopt)); + Tensor work = at::empty({lwork}, input.options()); + + for (const auto i : c10::irange(batch_size)) { + const scalar_t* input_working_ptr = &input_data[i * input_matrix_stride]; + scalar_t* other_working_ptr = &other_data[i * other_matrix_stride]; + const scalar_t* tau_working_ptr = &tau_data[i * tau_stride]; + + // now compute the actual result + lapackOrmqr( + side, trans, m, n, k, + const_cast(input_working_ptr), lda, + const_cast(tau_working_ptr), + other_working_ptr, ldc, + work.data_ptr(), lwork, &info); + + // info from lapackOrmqr only reports if the i-th parameter is wrong + // so we don't need to check it all the time + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + } +#endif +} + +// This is a type dispatching helper function for 'apply_ormqr' +void ormqr_kernel(const Tensor& input, const Tensor& tau, const Tensor& other, bool left, bool transpose) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "ormqr_cpu", [&]{ + apply_ormqr(input, tau, other, left, transpose); + }); +} + +/* +Solves the matrix equation op(A) X = B +X and B are n-by-nrhs matrices, A is a unit, or non-unit, upper or lower triangular matrix +and op(A) is one of op(A) = A or op(A) = A^T or op(A) = A^H. +This is an in-place routine, content of 'B' is overwritten. +'upper' controls the portion of input matrix to consider in computations, +'transpose' chooses op(A) +'unitriangular' if true then the diagonal elements of A are assumed to be 1 +and the actual diagonal values are not used. +*/ +template +void apply_triangular_solve(const Tensor& A, const Tensor& B, bool left, bool upper, TransposeType transpose, bool unitriangular) { +#if !AT_BUILD_WITH_BLAS() + TORCH_CHECK( + false, + "Calling torch.triangular_solve on a CPU tensor requires compiling ", + "PyTorch with BLAS. Please use PyTorch built with BLAS support."); +#else + char uplo = upper ? 'U' : 'L'; + char diag = unitriangular ? 'U' : 'N'; + char side = left ? 'L' : 'R'; + const char trans = to_blas(transpose); + + auto A_data = A.const_data_ptr(); + auto B_data = B.data_ptr(); + auto A_mat_stride = matrixStride(A); + auto B_mat_stride = matrixStride(B); + auto batch_size = batchCount(A); + // This allows to pass rectangular A and B when left = True + auto m = left ? A.size(-1) : B.size(-2); + auto n = B.size(-1); + auto lda = std::max(1, A.size(-2)); + auto ldb = std::max(1, B.size(-2)); + + for (const auto i : c10::irange(batch_size)) { + const scalar_t* A_working_ptr = &A_data[i * A_mat_stride]; + scalar_t* B_working_ptr = &B_data[i * B_mat_stride]; + blasTriangularSolve(side, uplo, trans, diag, m, n, const_cast(A_working_ptr), lda, B_working_ptr, ldb); + } +#endif +} + +void triangular_solve_kernel(const Tensor& A, const Tensor& B, bool left, bool upper, TransposeType transpose, bool unitriangular) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(A.scalar_type(), "triangular_solve_cpu", [&]{ + apply_triangular_solve(A, B, left, upper, transpose, unitriangular); + }); +} + +template +void apply_ldl_factor( + const Tensor& A, + const Tensor& pivots, + const Tensor& info, + bool upper, + bool hermitian) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.linalg.ldl_factor on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(batchCount(A) > 0); + auto batch_size = batchCount(A); + auto n = A.size(-2); + auto leading_dim = A.stride(-1); + auto uplo = upper ? 'U' : 'L'; + + auto a_stride = A.dim() > 2 ? A.stride(-3) : 0; + auto pivots_stride = pivots.dim() > 1 ? pivots.stride(-2) : 0; + + auto a_data = A.data_ptr(); + auto pivots_data = pivots.data_ptr(); + auto info_data = info.data_ptr(); + + auto ldl_func = + hermitian ? lapackLdlHermitian : lapackLdlSymmetric; + + scalar_t wkopt; + ldl_func(uplo, n, a_data, leading_dim, pivots_data, &wkopt, -1, info_data); + using value_t = typename c10::scalar_value_type::type; + int lwork = std::max(1, real_impl(wkopt)); + Tensor work = at::empty({lwork}, A.dtype()); + auto work_data = work.mutable_data_ptr(); + + for (const auto i : c10::irange(batch_size)) { + scalar_t* a_working_ptr = &a_data[i * a_stride]; + auto* pivots_working_ptr = &pivots_data[i * pivots_stride]; + auto* info_working_ptr = &info_data[i]; + ldl_func( + uplo, + n, + a_working_ptr, + leading_dim, + pivots_working_ptr, + work_data, + lwork, + info_working_ptr); + } +#endif +} + +void ldl_factor_kernel( + const Tensor& LD, + const Tensor& pivots, + const Tensor& info, + bool upper, + bool hermitian) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES( + LD.scalar_type(), "ldl_factor_kernel_cpu", [&] { + apply_ldl_factor(LD, pivots, info, upper, hermitian); + }); +} + +template +void apply_ldl_solve( + const Tensor& A, + const Tensor& pivots, + const Tensor& B, + bool upper, + bool hermitian) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.linalg.ldl_factor on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(batchCount(A) > 0); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(batchCount(pivots.unsqueeze(-1)) > 0); + auto batch_size = batchCount(B); + auto n = A.size(-2); + auto nrhs = B.size(-1); + auto lda = A.stride(-1); + auto ldb = B.stride(-1); + auto uplo = upper ? 'U' : 'L'; + + auto a_stride = A.dim() > 2 ? A.stride(-3) : 0; + auto b_stride = B.dim() > 2 ? B.stride(-3) : 0; + auto pivots_stride = pivots.dim() > 1 ? pivots.stride(-2) : 0; + + auto a_data = A.const_data_ptr(); + auto b_data = B.data_ptr(); + auto pivots_ = pivots.to(kInt); + auto pivots_data = pivots_.const_data_ptr(); + + auto ldl_solve_func = hermitian ? lapackLdlSolveHermitian + : lapackLdlSolveSymmetric; + + int info = 0; + for (const auto i : c10::irange(batch_size)) { + const scalar_t* a_working_ptr = &a_data[i * a_stride]; + scalar_t* b_working_ptr = &b_data[i * b_stride]; + const auto* pivots_working_ptr = &pivots_data[i * pivots_stride]; + ldl_solve_func( + uplo, + n, + nrhs, + const_cast(a_working_ptr), + lda, + const_cast(pivots_working_ptr), + b_working_ptr, + ldb, + &info); + } + TORCH_INTERNAL_ASSERT(info == 0); +#endif +} + +void ldl_solve_kernel( + const Tensor& LD, + const Tensor& pivots, + const Tensor& result, + bool upper, + bool hermitian) { + // Lapack SYTRS writes into unrelated memory if |IPIV(k)| is outside [1, N] + // (negative values encode 2x2 block pivots), so sanity-check user-provided + // pivots before dispatch on CPU. + TORCH_CHECK(pivots.abs().ge(1).all().item(), + "Pivots given to ldl_solve must all satisfy |pivot| >= 1. " + "Did you properly pass the result of ldl_factor?"); + TORCH_CHECK(pivots.abs().le(LD.size(-2)).all().item(), + "Pivots given to ldl_solve must all satisfy |pivot| <= LD.size(-2). " + "Did you properly pass the result of ldl_factor?"); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES( + LD.scalar_type(), "ldl_solve_kernel_cpu", [&] { + apply_ldl_solve(LD, pivots, result, upper, hermitian); + }); +} + +/* + Computes the LU decomposition of a m×n matrix or batch of matrices in 'input' tensor. + This is an in-place routine, content of 'input', 'pivots', and 'infos' is overwritten. + + Args: + * `input` - [in] the input matrix for LU decomposition + [out] the LU decomposition + * `pivots` - [out] the pivot indices + * `infos` - [out] error codes, positive values indicate singular matrices + * `compute_pivots` - should always be true (can be false only for CUDA) + + For further details, please see the LAPACK documentation for GETRF. +*/ +template +void apply_lu_factor(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling torch.linalg.lu_factor on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + TORCH_CHECK(compute_pivots, "linalg.lu_factor: LU without pivoting is not implemented on the CPU"); + + auto input_data = input.data_ptr(); + auto pivots_data = pivots.data_ptr(); + auto infos_data = infos.data_ptr(); + auto input_matrix_stride = matrixStride(input); + auto pivots_stride = pivots.size(-1); + auto batch_size = batchCount(input); + auto m = input.size(-2); + auto n = input.size(-1); + auto leading_dimension = std::max(1, m); + + const auto loop = [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + scalar_t* input_working_ptr = &input_data[i * input_matrix_stride]; + int* pivots_working_ptr = &pivots_data[i * pivots_stride]; + int* infos_working_ptr = &infos_data[i]; + lapackLu( + m, + n, + input_working_ptr, + leading_dimension, + pivots_working_ptr, + infos_working_ptr); + } + }; + // avoid overflow + auto matrix_rank = std::min(m, n); + // A heuristic tested on a 32 core/socket ICX system + // https://github.com/pytorch/pytorch/pull/93037#discussion_r1090112948 + int64_t chunk_size_per_thread = static_cast( + std::min(1.0, 3200.0 / (matrix_rank * matrix_rank * matrix_rank))); + int64_t grain_size = chunk_size_per_thread * at::get_num_threads(); + at::parallel_for(0, batch_size, grain_size, loop); +#endif +} + +// This is a type dispatching helper function for 'apply_lu' +void lu_factor_kernel(const Tensor& input, const Tensor& pivots, const Tensor& infos, bool compute_pivots) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(input.scalar_type(), "lu_cpu", [&]{ + apply_lu_factor(input, pivots, infos, compute_pivots); + }); +} + +/* + Solves the matrix equation A X = B + X and B are n-by-nrhs matrices, A is represented using the LU factorization. + This is an in-place routine, content of `b` is overwritten. + + Args: + * `b` - [in] the right hand side matrix B + [out] the solution matrix X + * `lu` - [in] the LU factorization of matrix A (see at::linalg_lu_factor) + * `pivots` - [in] the pivot indices (see at::linalg_lu_factor) + + For further details, please see the LAPACK documentation for GETRS. +*/ +template +void apply_lu_solve(const Tensor& LU, const Tensor& pivots, const Tensor& B, TransposeType transpose) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK( + false, + "Calling linalg.lu_solve on a CPU tensor requires compiling ", + "PyTorch with LAPACK. Please use PyTorch built with LAPACK support."); +#else + auto b_data = B.data_ptr(); + auto lu_data = LU.const_data_ptr(); + const auto trans = to_blas(transpose); + auto pivots_data = pivots.const_data_ptr(); + auto b_stride = matrixStride(B); + auto lu_stride = LU.dim() > 2 ? LU.stride(-3) : 0; + auto pivots_stride = pivots.dim() > 1 ? pivots.stride(-2) : 0; + auto batch_size = batchCount(B); + + auto n = LU.size(-2); + auto nrhs = B.size(-1); + auto leading_dimension = std::max(1, n); + + int info = 0; + + // lu and pivots tensors can be broadcast to B + // here we construct a helper indexing tensor to linearly index into LU and pivots + IntArrayRef lu_batch_shape(LU.sizes().data(), LU.dim() - 2); + IntArrayRef b_batch_shape(B.sizes().data(), B.dim() - 2); + BroadcastLinearIndices lu_index( + batchCount(LU), lu_batch_shape, b_batch_shape); + + for (const auto i : c10::irange(batch_size)) { + int64_t lu_index_i = lu_index(i); + scalar_t* b_working_ptr = &b_data[i * b_stride]; + const scalar_t* lu_working_ptr = &lu_data[lu_index_i * lu_stride]; + const int* pivots_working_ptr = &pivots_data[lu_index_i * pivots_stride]; + + lapackLuSolve(trans, n, nrhs, const_cast(lu_working_ptr), leading_dimension, const_cast(pivots_working_ptr), + b_working_ptr, leading_dimension, &info); + + // info from lapackLuSolve only reports if the i-th parameter is wrong + // so we don't need to check it all the time + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(info == 0); + } +#endif +} + +// This is a type dispatching helper function for 'apply_lu_solve' +void lu_solve_kernel(const Tensor& LU, const Tensor& pivots, const Tensor& B, TransposeType trans) { + // Lapack will write into unrelated memory if pivots are not in the right range so we do + // some simple sanity checks here for the CPU version + TORCH_CHECK(pivots.gt(0).all().item(), + "Pivots given to lu_solve must all be greater or equal to 1. " + "Did you properly pass the result of lu_factor?"); + TORCH_CHECK(pivots.le(LU.size(-2)).all().item(), + "Pivots given to lu_solve must all be smaller or equal to LU.size(-2). " + "Did you properly pass the result of lu_factor?"); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(LU.scalar_type(), "linalg.lu_solve_cpu", [&]{ + apply_lu_solve(LU, pivots, B, trans); + }); +} + +template +void apply_svd(const Tensor& A, + const bool full_matrices, + const bool compute_uv, + const Tensor& U, + const Tensor& S, + const Tensor& Vh, + const Tensor& info) { +#if !AT_BUILD_WITH_LAPACK() + TORCH_CHECK(false, "svd: LAPACK library not found in compilation"); +#else + using value_t = typename c10::scalar_value_type::type; + const auto A_data = A.data_ptr(); + const auto U_data = compute_uv ? U.data_ptr() : nullptr; + const auto S_data = S.data_ptr(); + const auto info_data = info.data_ptr(); + const auto Vh_data = compute_uv ? Vh.data_ptr() : nullptr; + const auto A_stride = matrixStride(A); + const auto S_stride = S.size(-1); + const auto U_stride = compute_uv ? matrixStride(U) : 1; + const auto Vh_stride = compute_uv ? matrixStride(Vh) : 1; + const auto batchsize = batchCount(A); + const char jobz = compute_uv ? (full_matrices ? 'A' : 'S') : 'N'; + + const auto m = A.size(-2); + const auto n = A.size(-1); + const auto lda = A.stride(-1); + const auto ldu= compute_uv ? U.stride(-1) : 1; + const auto ldvh = compute_uv ? Vh.stride(-1) : 1; + + auto iwork = std::vector(8 * std::min(m, n)); + auto* const iwork_data = iwork.data(); + + // rwork is just used for the complex decomposition + auto rwork = std::vector{}; + if (A.is_complex()) { + rwork.resize(std::max(computeLRWorkDim(jobz, m, n), int64_t{1})); + } + auto* const rwork_data = rwork.data(); + + // Query svd for the optimal lwork size + int lwork = -1; + { + scalar_t wkopt; + lapackSvd(jobz, m, n, A_data, lda, S_data, U_data, ldu, Vh_data, ldvh, &wkopt, lwork, rwork_data, iwork_data, info_data); + lwork = lapack_work_to_int(wkopt); + } + auto work = std::vector(lwork); + auto* const work_data = work.data(); + + for (const auto i : c10::irange(batchsize)) { + auto* const A_working_ptr = &A_data[i * A_stride]; + auto* const S_working_ptr = &S_data[i * S_stride]; + auto* const U_working_ptr = compute_uv ? &U_data[i * U_stride] : nullptr; + auto* const Vh_working_ptr = compute_uv ? &Vh_data[i * Vh_stride] : nullptr; + + // Compute S, U (optionally) and Vh (optionally) + lapackSvd(jobz, m, n, A_working_ptr, lda, + S_working_ptr, U_working_ptr, ldu, Vh_working_ptr, ldvh, work_data, lwork, rwork_data, iwork_data, info_data + i); + } +#endif +} + +void svd_kernel(const Tensor& A, + const bool full_matrices, + const bool compute_uv, + const std::optional& driver, + const Tensor& U, + const Tensor& S, + const Tensor& Vh, + const Tensor& infos) { + TORCH_INTERNAL_ASSERT(!driver.has_value(), "svd_kernel: driver shouldn't have a value here. "); + // Need to copy A as column major, as its contents will be destroyed in the LAPACK call. + // FIXME It'd be more efficient, rather than cloning A, to copy it into `U` or `Vh` (depending on m > n + // or m < n) and call jobz='O' + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(A.scalar_type(), "linalg_svd_cpu", [&]{ + apply_svd(cloneBatchedColumnMajor(A), full_matrices, compute_uv, U, S, Vh, infos); + }); +} + +void unpack_pivots_cpu_kernel(TensorIterator& iter, const int64_t dim_size, const int64_t max_pivot) { + if (iter.numel() == 0 || dim_size == 0) { + return; + } + auto loop = [&](char* const* const data, const int64_t* const strides, const int64_t nelems) { + auto* perm_ptr = data[0]; + const auto* pivots_ptr = data[1]; + + for ([[maybe_unused]] const auto elem : c10::irange(nelems)) { + // WARNING: linalg.lu_factor returns int32 pivots, + // this behavior could change in the future. + const auto perm_data = reinterpret_cast(perm_ptr); + const auto pivots_data = reinterpret_cast(pivots_ptr); + + for (const auto i : c10::irange(dim_size)) { + auto new_idx = pivots_data[i] - 1; + TORCH_CHECK(new_idx >= 0 && new_idx < max_pivot, + "pivots passed to lu_unpack must be between 1 and LU.size(-2) inclusive." + "Did you properly pass the result of lu_factor?"); + std::swap( + perm_data[i], + perm_data[new_idx] + ); + } + + perm_ptr += strides[0]; + pivots_ptr += strides[1]; + } + }; + + iter.for_each(loop); +} +} // anonymous namespace + +REGISTER_ALL_CPU_DISPATCH(cholesky_stub, &cholesky_kernel) +REGISTER_ALL_CPU_DISPATCH(cholesky_inverse_stub, &cholesky_inverse_kernel_impl) +REGISTER_ALL_CPU_DISPATCH(linalg_eig_make_complex_eigenvectors_stub, &linalg_eig_make_complex_eigenvectors_cpu) +REGISTER_ALL_CPU_DISPATCH(linalg_eig_stub, &linalg_eig_kernel) +REGISTER_ALL_CPU_DISPATCH(linalg_eigh_stub, &linalg_eigh_kernel) +REGISTER_ALL_CPU_DISPATCH(geqrf_stub, &geqrf_kernel) +REGISTER_ALL_CPU_DISPATCH(orgqr_stub, &orgqr_kernel_impl) +REGISTER_ALL_CPU_DISPATCH(ormqr_stub, &ormqr_kernel) +REGISTER_ALL_CPU_DISPATCH(lstsq_stub, &lstsq_kernel) +REGISTER_ALL_CPU_DISPATCH(triangular_solve_stub, &triangular_solve_kernel) +REGISTER_ALL_CPU_DISPATCH(lu_factor_stub, &lu_factor_kernel) +REGISTER_ALL_CPU_DISPATCH(ldl_factor_stub, &ldl_factor_kernel) +REGISTER_ALL_CPU_DISPATCH(ldl_solve_stub, &ldl_solve_kernel) +REGISTER_ALL_CPU_DISPATCH(lu_solve_stub, &lu_solve_kernel) +REGISTER_ALL_CPU_DISPATCH(svd_stub, &svd_kernel) +REGISTER_ALL_CPU_DISPATCH(unpack_pivots_stub, &unpack_pivots_cpu_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BinaryOps.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/BinaryOps.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b84c45bb87599bf5ca5e71db4c9aff34bc01c38 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BinaryOps.cpp @@ -0,0 +1,1658 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include + +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::meta { + +TORCH_META_FUNC2(add, Tensor) ( + const Tensor& self, const Tensor& other, const Scalar& alpha +) { + build_borrowing_binary_op(maybe_get_output(), self, other); + native::alpha_check(dtype(), alpha); +} + +TORCH_META_FUNC2(sub, Tensor) ( + const Tensor& self, const Tensor& other, const Scalar& alpha +) { + native::sub_check(self, other); + build_borrowing_binary_op(maybe_get_output(), self, other); + native::alpha_check(dtype(), alpha); +} + +TORCH_META_FUNC2(mul, Tensor) ( + const Tensor& self, const Tensor& other +) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(div, Tensor) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(div, Tensor_mode) (const Tensor& self, const Tensor& other, std::optional rounding_mode) { + if (!rounding_mode.has_value()) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); + // NOLINTNEXTLINE(bugprone-branch-clone) + } else if (*rounding_mode == "trunc") { + build_borrowing_binary_op(maybe_get_output(), self, other); + } else if (*rounding_mode == "floor") { + build_borrowing_binary_op(maybe_get_output(), self, other); + } else { + TORCH_CHECK(false, + "div expected rounding_mode to be one of None, 'trunc', or 'floor' " + "but found '", *rounding_mode, "'"); + } +} + +TORCH_META_FUNC(special_xlog1py) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(special_zeta) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(special_chebyshev_polynomial_t) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_chebyshev_polynomial_u) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_chebyshev_polynomial_v) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_chebyshev_polynomial_w) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_hermite_polynomial_h) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_hermite_polynomial_he) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_laguerre_polynomial_l) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_legendre_polynomial_p) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_shifted_chebyshev_polynomial_t) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_shifted_chebyshev_polynomial_u) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_shifted_chebyshev_polynomial_v) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC(special_shifted_chebyshev_polynomial_w) (const Tensor& self, const Tensor& n) { + build_borrowing_binary_float_op(maybe_get_output(), self, n); +} + +TORCH_META_FUNC2(copysign, Tensor) ( + const Tensor& self, const Tensor& other +) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(heaviside) ( + const Tensor& self, const Tensor& other +) { + TORCH_CHECK(!self.is_complex() && !other.is_complex() && + (maybe_get_output().defined() ? !maybe_get_output().is_complex() : true), + "heaviside is not yet implemented for complex tensors."); + TORCH_CHECK(self.dtype() == other.dtype() && + (maybe_get_output().defined() ? maybe_get_output().dtype() == self.dtype() : true), + "heaviside is not yet implemented for tensors with different dtypes."); + + build_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(atan2) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(remainder, Tensor)(const Tensor& self, const Tensor& other) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(bitwise_left_shift, Tensor) ( + const Tensor& self, const Tensor& other +) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(bitwise_right_shift, Tensor) ( + const Tensor& self, const Tensor& other +) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(bitwise_and, Tensor) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(bitwise_or, Tensor) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(bitwise_xor, Tensor) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(fmod, Tensor) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC2(xlogy, Tensor) (const Tensor& self, const Tensor& other) { + build_borrowing_binary_float_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(logit_backward) (const Tensor& grad_output, const Tensor& input, std::optional eps) { + build_borrowing_binary_op(maybe_get_output(), grad_output, input); +} + +TORCH_META_FUNC(sigmoid_backward) (const Tensor& grad_output, const Tensor& output) { + build_borrowing_binary_op(maybe_get_output(), grad_output, output); +} + +TORCH_META_FUNC(tanh_backward) (const Tensor& grad_output, const Tensor& output) { + build_borrowing_binary_op(maybe_get_output(), grad_output, output); +} + +// These are normal binary ops that preserve dtype +#define CREATE_BINARY_META_FUNC(func) \ + TORCH_META_FUNC(func) (const Tensor& self, const Tensor& other) { \ + build_borrowing_binary_op(maybe_get_output(), self, other); \ + } + +CREATE_BINARY_META_FUNC(logaddexp) +CREATE_BINARY_META_FUNC(logaddexp2) +CREATE_BINARY_META_FUNC(gcd) +CREATE_BINARY_META_FUNC(lcm) +CREATE_BINARY_META_FUNC(hypot) +CREATE_BINARY_META_FUNC(igamma) +CREATE_BINARY_META_FUNC(igammac) +CREATE_BINARY_META_FUNC(nextafter) + +TORCH_META_FUNC(maximum) (const Tensor& self, const Tensor& other) { + TORCH_CHECK(!self.is_complex() && !other.is_complex(), "maximum not implemented for complex tensors."); + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(minimum) (const Tensor& self, const Tensor& other) { + TORCH_CHECK(!self.is_complex() && !other.is_complex(), "minimum not implemented for complex tensors."); + build_borrowing_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(fmax) (const Tensor& self, const Tensor& other) { + TORCH_CHECK(!self.is_complex() && !other.is_complex(), "fmax not implemented for complex tensors."); + build_binary_op(maybe_get_output(), self, other); +} + +TORCH_META_FUNC(fmin) (const Tensor& self, const Tensor& other) { + TORCH_CHECK(!self.is_complex() && !other.is_complex(), "fmin not implemented for complex tensors."); + build_binary_op(maybe_get_output(), self, other); +} + +#define CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(func) \ + TORCH_META_FUNC2(func, Tensor)(const Tensor& self, const Tensor& other) { \ + const Tensor& result = maybe_get_output(); \ + build_borrowing_comparison_op(result, self, other); \ + } \ + \ + TORCH_META_FUNC2(func, Scalar)(const Tensor& self, const Scalar& other) { \ + auto other_tensor = \ + native::wrapped_scalar_tensor(other); \ + build_borrowing_except_last_argument_comparison_op(maybe_get_output(), self, other_tensor); \ + } + +CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(eq) +CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(ne) +CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(lt) +CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(le) +CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(gt) +CREATE_COMPARISON_SCALAR_TENSOR_META_FUNC(ge) + +} // namespace at::meta + + +namespace at::native { + +DEFINE_DISPATCH(add_clamp_stub); +DEFINE_DISPATCH(mul_stub); +DEFINE_DISPATCH(sub_stub); +DEFINE_DISPATCH(div_true_stub); +DEFINE_DISPATCH(div_floor_stub); +DEFINE_DISPATCH(div_trunc_stub); +DEFINE_DISPATCH(remainder_stub); +DEFINE_DISPATCH(atan2_stub); +DEFINE_DISPATCH(bitwise_and_stub); +DEFINE_DISPATCH(bitwise_or_stub); +DEFINE_DISPATCH(bitwise_xor_stub); +DEFINE_DISPATCH(lshift_stub); +DEFINE_DISPATCH(rshift_stub); +DEFINE_DISPATCH(logical_and_stub); +DEFINE_DISPATCH(logical_or_stub); +DEFINE_DISPATCH(logical_xor_stub); +DEFINE_DISPATCH(lt_stub); +DEFINE_DISPATCH(le_stub); +DEFINE_DISPATCH(gt_stub); +DEFINE_DISPATCH(ge_stub); +DEFINE_DISPATCH(eq_stub); +DEFINE_DISPATCH(ne_stub); +DEFINE_DISPATCH(sigmoid_backward_stub); +DEFINE_DISPATCH(logit_backward_stub); +DEFINE_DISPATCH(tanh_backward_stub); +DEFINE_DISPATCH(maximum_stub); +DEFINE_DISPATCH(minimum_stub); +DEFINE_DISPATCH(fmax_stub); +DEFINE_DISPATCH(fmin_stub); +DEFINE_DISPATCH(fmod_stub); +DEFINE_DISPATCH(logaddexp_stub); +DEFINE_DISPATCH(logaddexp2_stub); +DEFINE_DISPATCH(gcd_stub); +DEFINE_DISPATCH(lcm_stub); +DEFINE_DISPATCH(hypot_stub); +DEFINE_DISPATCH(igamma_stub); +DEFINE_DISPATCH(igammac_stub); +DEFINE_DISPATCH(nextafter_stub); +DEFINE_DISPATCH(heaviside_stub); +DEFINE_DISPATCH(copysign_stub); +DEFINE_DISPATCH(xlogy_stub); +DEFINE_DISPATCH(xlog1py_stub); +DEFINE_DISPATCH(zeta_stub); +DEFINE_DISPATCH(chebyshev_polynomial_t_stub); +DEFINE_DISPATCH(chebyshev_polynomial_u_stub); +DEFINE_DISPATCH(chebyshev_polynomial_v_stub); +DEFINE_DISPATCH(chebyshev_polynomial_w_stub); +DEFINE_DISPATCH(hermite_polynomial_h_stub); +DEFINE_DISPATCH(hermite_polynomial_he_stub); +DEFINE_DISPATCH(laguerre_polynomial_l_stub); +DEFINE_DISPATCH(legendre_polynomial_p_stub); +DEFINE_DISPATCH(shifted_chebyshev_polynomial_t_stub); +DEFINE_DISPATCH(shifted_chebyshev_polynomial_u_stub); +DEFINE_DISPATCH(shifted_chebyshev_polynomial_v_stub); +DEFINE_DISPATCH(shifted_chebyshev_polynomial_w_stub); +DEFINE_DISPATCH(ldexp_stub); + +TORCH_IMPL_FUNC(sub_out) ( + const Tensor& self, const Tensor& other, const Scalar& alpha, const Tensor& result +) { + add_stub(device_type(), *this, -alpha); + TORCH_INTERNAL_ASSERT(result.scalar_type() == output().dtype()); +} + +TORCH_IMPL_FUNC(mul_out) ( + const Tensor& self, const Tensor& other, const Tensor& result +) { + mul_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(div_out) (const Tensor& self, const Tensor& other, const Tensor& result) { + div_true_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(div_out_mode) ( + const Tensor& self, const Tensor& other, std::optional rounding_mode, const Tensor& result +) { + if (!rounding_mode.has_value()) { + div_true_stub(device_type(), *this); + } else if (*rounding_mode == "trunc") { + div_trunc_stub(device_type(), *this); + } else if (*rounding_mode == "floor") { + div_floor_stub(device_type(), *this); + } +} + +TORCH_IMPL_FUNC(logit_backward_out) (const Tensor& grad_output, const Tensor& input, std::optional eps, const Tensor& result) { + logit_backward_stub(device_type(), *this, Scalar(eps ? eps.value() : -1.0)); +} + +TORCH_IMPL_FUNC(sigmoid_backward_out) (const Tensor& grad_output, const Tensor& output, const Tensor& result) { + sigmoid_backward_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_xlog1py_out) (const Tensor& self, const Tensor& other, const Tensor& result) { + xlog1py_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_zeta_out) (const Tensor& self, const Tensor& other, const Tensor& result) { + zeta_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_chebyshev_polynomial_t_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + chebyshev_polynomial_t_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_chebyshev_polynomial_u_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + chebyshev_polynomial_u_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_chebyshev_polynomial_v_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + chebyshev_polynomial_v_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_chebyshev_polynomial_w_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + chebyshev_polynomial_w_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_hermite_polynomial_h_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + hermite_polynomial_h_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_hermite_polynomial_he_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + hermite_polynomial_he_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_laguerre_polynomial_l_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + laguerre_polynomial_l_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_legendre_polynomial_p_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + legendre_polynomial_p_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_shifted_chebyshev_polynomial_t_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + shifted_chebyshev_polynomial_t_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_shifted_chebyshev_polynomial_u_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + shifted_chebyshev_polynomial_u_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_shifted_chebyshev_polynomial_v_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + shifted_chebyshev_polynomial_v_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(special_shifted_chebyshev_polynomial_w_out) (const Tensor& self, const Tensor& n, const Tensor& result) { + shifted_chebyshev_polynomial_w_stub(device_type(), *this); +} + +TORCH_IMPL_FUNC(tanh_backward_out) (const Tensor& grad_output, const Tensor& output, const Tensor& result) { + tanh_backward_stub(device_type(), *this); +} + +#define CREATE_BINARY_TORCH_IMPL_FUNC(func_out, func_stub) \ +TORCH_IMPL_FUNC(func_out) (const Tensor& self, const Tensor& other, const Tensor& result) { \ + func_stub(device_type(), *this); \ +} + +CREATE_BINARY_TORCH_IMPL_FUNC(bitwise_and_out, bitwise_and_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(bitwise_or_out, bitwise_or_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(bitwise_xor_out, bitwise_xor_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(maximum_out, maximum_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(minimum_out, minimum_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(fmax_out, fmax_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(fmin_out, fmin_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(fmod_out, fmod_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(logaddexp_out, logaddexp_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(logaddexp2_out, logaddexp2_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(gcd_out, gcd_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(lcm_out, lcm_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(hypot_out, hypot_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(igamma_out, igamma_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(igammac_out, igammac_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(nextafter_out, nextafter_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(remainder_out, remainder_stub) +CREATE_BINARY_TORCH_IMPL_FUNC(xlogy_out, xlogy_stub) + +Tensor special_xlog1py(const Scalar& x, const Tensor& y) { + return at::special_xlog1py(wrapped_scalar_tensor(x), y); +} + +Tensor special_xlog1py(const Tensor& x, const Scalar& y) { + return at::special_xlog1py(x, wrapped_scalar_tensor(y)); +} + +Tensor& special_xlog1py_out(const Scalar& self, const Tensor& other, Tensor& result) { + return at::special_xlog1py_out(result, wrapped_scalar_tensor(self), other); +} + +Tensor& special_xlog1py_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::special_xlog1py_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor special_zeta(const Scalar& x, const Tensor& y) { + return at::special_zeta(wrapped_scalar_tensor(x), y); +} + +Tensor special_zeta(const Tensor& x, const Scalar& y) { + return at::special_zeta(x, wrapped_scalar_tensor(y)); +} + +Tensor& special_zeta_out(const Scalar& self, const Tensor& other, Tensor& result) { + return at::special_zeta_out(result, wrapped_scalar_tensor(self), other); +} + +Tensor& special_zeta_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::special_zeta_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor special_chebyshev_polynomial_t(const Scalar& x, const Tensor& n) { + return at::special_chebyshev_polynomial_t(wrapped_scalar_tensor(x), n); +} + +Tensor special_chebyshev_polynomial_t(const Tensor& x, const Scalar& n) { + return at::special_chebyshev_polynomial_t(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_chebyshev_polynomial_t_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_chebyshev_polynomial_t_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_chebyshev_polynomial_t_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_chebyshev_polynomial_t_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_chebyshev_polynomial_u(const Scalar& x, const Tensor& n) { + return at::special_chebyshev_polynomial_u(wrapped_scalar_tensor(x), n); +} + +Tensor special_chebyshev_polynomial_u(const Tensor& x, const Scalar& n) { + return at::special_chebyshev_polynomial_u(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_chebyshev_polynomial_u_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_chebyshev_polynomial_u_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_chebyshev_polynomial_u_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_chebyshev_polynomial_u_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_chebyshev_polynomial_v(const Scalar& x, const Tensor& n) { + return at::special_chebyshev_polynomial_v(wrapped_scalar_tensor(x), n); +} + +Tensor special_chebyshev_polynomial_v(const Tensor& x, const Scalar& n) { + return at::special_chebyshev_polynomial_v(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_chebyshev_polynomial_v_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_chebyshev_polynomial_v_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_chebyshev_polynomial_v_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_chebyshev_polynomial_v_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_chebyshev_polynomial_w(const Scalar& x, const Tensor& n) { + return at::special_chebyshev_polynomial_w(wrapped_scalar_tensor(x), n); +} + +Tensor special_chebyshev_polynomial_w(const Tensor& x, const Scalar& n) { + return at::special_chebyshev_polynomial_w(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_chebyshev_polynomial_w_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_chebyshev_polynomial_w_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_chebyshev_polynomial_w_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_chebyshev_polynomial_w_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_hermite_polynomial_h(const Scalar& x, const Tensor& n) { + return at::special_hermite_polynomial_h(wrapped_scalar_tensor(x), n); +} + +Tensor special_hermite_polynomial_h(const Tensor& x, const Scalar& n) { + return at::special_hermite_polynomial_h(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_hermite_polynomial_h_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_hermite_polynomial_h_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_hermite_polynomial_h_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_hermite_polynomial_h_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_hermite_polynomial_he(const Scalar& x, const Tensor& n) { + return at::special_hermite_polynomial_he(wrapped_scalar_tensor(x), n); +} + +Tensor special_hermite_polynomial_he(const Tensor& x, const Scalar& n) { + return at::special_hermite_polynomial_he(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_hermite_polynomial_he_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_hermite_polynomial_he_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_hermite_polynomial_he_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_hermite_polynomial_he_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_laguerre_polynomial_l(const Scalar& x, const Tensor& n) { + return at::special_laguerre_polynomial_l(wrapped_scalar_tensor(x), n); +} + +Tensor special_laguerre_polynomial_l(const Tensor& x, const Scalar& n) { + return at::special_laguerre_polynomial_l(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_laguerre_polynomial_l_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_laguerre_polynomial_l_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_laguerre_polynomial_l_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_laguerre_polynomial_l_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_legendre_polynomial_p(const Scalar& x, const Tensor& n) { + return at::special_legendre_polynomial_p(wrapped_scalar_tensor(x), n); +} + +Tensor special_legendre_polynomial_p(const Tensor& x, const Scalar& n) { + return at::special_legendre_polynomial_p(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_legendre_polynomial_p_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_legendre_polynomial_p_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_legendre_polynomial_p_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_legendre_polynomial_p_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_shifted_chebyshev_polynomial_t(const Scalar& x, const Tensor& n) { + return at::special_shifted_chebyshev_polynomial_t(wrapped_scalar_tensor(x), n); +} + +Tensor special_shifted_chebyshev_polynomial_t(const Tensor& x, const Scalar& n) { + return at::special_shifted_chebyshev_polynomial_t(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_shifted_chebyshev_polynomial_t_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_t_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_shifted_chebyshev_polynomial_t_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_t_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_shifted_chebyshev_polynomial_u(const Scalar& x, const Tensor& n) { + return at::special_shifted_chebyshev_polynomial_u(wrapped_scalar_tensor(x), n); +} + +Tensor special_shifted_chebyshev_polynomial_u(const Tensor& x, const Scalar& n) { + return at::special_shifted_chebyshev_polynomial_u(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_shifted_chebyshev_polynomial_u_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_u_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_shifted_chebyshev_polynomial_u_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_u_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_shifted_chebyshev_polynomial_v(const Scalar& x, const Tensor& n) { + return at::special_shifted_chebyshev_polynomial_v(wrapped_scalar_tensor(x), n); +} + +Tensor special_shifted_chebyshev_polynomial_v(const Tensor& x, const Scalar& n) { + return at::special_shifted_chebyshev_polynomial_v(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_shifted_chebyshev_polynomial_v_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_v_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_shifted_chebyshev_polynomial_v_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_v_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor special_shifted_chebyshev_polynomial_w(const Scalar& x, const Tensor& n) { + return at::special_shifted_chebyshev_polynomial_w(wrapped_scalar_tensor(x), n); +} + +Tensor special_shifted_chebyshev_polynomial_w(const Tensor& x, const Scalar& n) { + return at::special_shifted_chebyshev_polynomial_w(x, wrapped_scalar_tensor(n)); +} + +Tensor& special_shifted_chebyshev_polynomial_w_out(const Scalar& self, const Tensor& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_w_out(result, wrapped_scalar_tensor(self), n); +} + +Tensor& special_shifted_chebyshev_polynomial_w_out(const Tensor& self, const Scalar& n, Tensor& result) { + return at::special_shifted_chebyshev_polynomial_w_out(result, self, wrapped_scalar_tensor(n)); +} + +Tensor& special_gammainc_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::igamma_out(result, self, other); +} + +Tensor special_gammainc(const Tensor& self, const Tensor& other) { + return at::igamma(self, other); +} + +Tensor& special_gammaincc_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::igammac_out(result, self, other); +} + +Tensor special_gammaincc(const Tensor& self, const Tensor& other) { + return at::igammac(self, other); +} + +TORCH_IMPL_FUNC(atan2_out) (const Tensor& self, const Tensor& other, const Tensor& result) { + atan2_stub(device_type(), *this); +} + +Tensor arctan2(const Tensor& self, const Tensor& other) { + return at::atan2(self, other); +} + +Tensor& arctan2_(Tensor& self, const Tensor& other) { + return self.atan2_(other); +} + +Tensor& arctan2_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::atan2_out(result, self, other); +} + +static Tensor& add_relu_impl( + Tensor& result, const Tensor& self, const Tensor& other, const Scalar& alpha) { + auto iter = TensorIterator::binary_op(result, self, other); + Scalar min_val; + Scalar max_val; + if (self.dtype() == at::kInt) { + min_val = 0; + max_val = std::numeric_limits::max(); + } else if (self.dtype() == at::kLong) { + min_val = 0; + max_val = std::numeric_limits::max(); + } else if (self.dtype() == at::kShort) { + min_val = 0; + max_val = std::numeric_limits::max(); + } else if (self.dtype() == at::kChar) { + min_val = 0; + max_val = std::numeric_limits::max(); + } else if (self.dtype() == at::kFloat) { + min_val = 0.0; + max_val = std::numeric_limits::max(); + } else if (self.dtype() == at::kDouble) { + min_val = 0.0; + max_val = std::numeric_limits::max(); + } else { + TORCH_INTERNAL_ASSERT( + false, "Unsupported datatype for add_relu:", self.dtype().name()); + } + + result = iter.output(); + add_clamp_stub(iter.device_type(), iter, alpha, min_val, max_val); + return result; +} + +Tensor& add_relu_out(const Tensor& self, const Tensor& other, const Scalar& alpha, Tensor& result) { + return add_relu_impl(result, self, other, alpha); +} + +Tensor add_relu(const Tensor& self, const Tensor& other, const Scalar& alpha) { + Tensor result; + return add_relu_impl(result, self, other, alpha); +} + +Tensor add_relu(const Tensor& self, const Scalar& other, const Scalar& alpha) { + return add_relu(self, wrapped_scalar_tensor(other), alpha); +} + +Tensor& add_relu_(Tensor& self, const Tensor& other, const Scalar& alpha) { + return add_relu_impl(self, self, other, alpha); +} + +Tensor& add_relu_(Tensor& self, const Scalar& other, const Scalar& alpha) { + return add_relu_(self, wrapped_scalar_tensor(other), alpha); +} + +TORCH_IMPL_FUNC(copysign_out) ( + const Tensor& self, const Tensor& other, const Tensor& result +) { + copysign_stub(device_type(), *this); +} + +Tensor copysign(const Tensor& self, const Scalar& other) { + // redispatch! + return at::copysign(self, wrapped_scalar_tensor(other)); +} + +Tensor& copysign_(Tensor& self, const Scalar& other) { + // redispatch! + return self.copysign_(wrapped_scalar_tensor(other)); +} + +Tensor& copysign_out(const Tensor& self, const Scalar& other, Tensor& result) { + // redispatch! + return at::copysign_out(result, self, wrapped_scalar_tensor(other)); +} + +// WARNING: There doesn't appear to be any testing for this function +// with sparse self input. +Tensor div(const Tensor& self, const Scalar& other) { + return self.div(wrapped_scalar_tensor(other)); // redispatch! +} + +// WARNING: This function, with a sparse self, is currently only +// exercised by DistributedDataParallelTest.test_sparse_gradients +// (you need to exercise it from C++, because this overload is never +// used for Python) +Tensor& div_(Tensor& self, const Scalar& other) { + return self.div_(wrapped_scalar_tensor(other)); // redispatch! +} + +Tensor div(const Tensor& self, const Scalar& other, std::optional rounding_mode) { + return self.div(wrapped_scalar_tensor(other), std::move(rounding_mode)); // redispatch! +} + +Tensor& div_(Tensor& self, const Scalar& other, std::optional rounding_mode) { + return self.div_(wrapped_scalar_tensor(other), std::move(rounding_mode)); // redispatch! +} + +// divide, alias for div +Tensor& divide_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::div_out(result, self, other); +} + +Tensor divide(const Tensor& self, const Tensor& other) { + return self.div(other); +} + +Tensor& divide_(Tensor& self, const Tensor& other) { + return self.div_(other); +} + +Tensor divide(const Tensor& self, const Scalar& other) { + return self.div(other); +} + +Tensor& divide_(Tensor& self, const Scalar& other) { + return self.div_(other); +} + +Tensor& divide_out(const Tensor& self, const Tensor& other, std::optional rounding_mode, Tensor& result) { + return at::div_out(result, self, other, std::move(rounding_mode)); +} + +Tensor divide(const Tensor& self, const Tensor& other, std::optional rounding_mode) { + return self.div(other, std::move(rounding_mode)); +} + +Tensor& divide_(Tensor& self, const Tensor& other, std::optional rounding_mode) { + return self.div_(other, std::move(rounding_mode)); +} + +Tensor divide(const Tensor& self, const Scalar& other, std::optional rounding_mode) { + return self.div(other, std::move(rounding_mode)); +} + +Tensor& divide_(Tensor& self, const Scalar& other, std::optional rounding_mode) { + return self.div_(other, std::move(rounding_mode)); +} + +// true_divide, an alias for div +Tensor& true_divide_out(const Tensor& self, const Tensor& divisor, Tensor& result) { + return at::div_out(result, self, divisor); +} + +Tensor true_divide(const Tensor& self, const Tensor& divisor) { + return self.div(divisor); +} + +Tensor& true_divide_(Tensor& self, const Tensor& divisor) { + return self.div_(divisor); +} + +Tensor true_divide(const Tensor& self, const Scalar& divisor) { + return self.div(divisor); +} + +Tensor& true_divide_(Tensor& self, const Scalar& divisor) { + return self.div_(divisor); +} + +Tensor& floor_divide_out(const Tensor& self, const Tensor& other, Tensor& result) { + auto iter = TensorIterator::binary_op(result, self, other); + div_floor_stub(iter.device_type(), iter); + if (!result.defined()) { + result = iter.output(); + } + return result; +} + +Tensor floor_divide(const Tensor& self, const Tensor& other) { + Tensor result; + auto iter = TensorIterator::binary_op(result, self, other); + div_floor_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor& floor_divide_(Tensor& self, const Tensor& other) { + return native::floor_divide_out(self, other, self); +} + +// TODO: Make this structured to undo the perf regression from native:: removal +// in call here +Tensor mul(const Tensor& self, const Scalar& other) { + return at::mul(self, wrapped_scalar_tensor(other)); // redispatch! +} + +Tensor& mul_(Tensor& self, const Scalar& other) { + return at::mul_out(self, wrapped_scalar_tensor(other), self); // redispatch! +} + +Tensor& mul__scalar_sparse_csr(Tensor& self, const Scalar& other) { + self.values().mul_(other); + return self; +} + +static Device correct_out_device(const Tensor& self, const Tensor& other) { + if (self.device() == at::kCPU){ + return other.device(); + } else { + return self.device(); + } +} + +static Tensor send_to_meta(const Tensor& self, const Device& device) { + Tensor out_meta; + if (self._is_zerotensor() && self.unsafeGetTensorImpl()->is_wrapped_number()) { + out_meta = at::_efficientzerotensor(self.sizes(), self.options().device(device)); + out_meta.unsafeGetTensorImpl()->set_wrapped_number(true); + } else { + out_meta = self.to(device); + } + return out_meta; +} + +Tensor mul_zerotensor(const Tensor& self, const Tensor& other) { + auto out_device = correct_out_device(self, other); + // hack to use the TensorIterator to get the correct broadcasting and type promotion logic + auto device_ = Device(DeviceType::Meta); + constexpr c10::DispatchKeySet meta_dks(at::DispatchKey::Meta); + auto self_meta = send_to_meta(self, device_); + auto other_meta = send_to_meta(other, device_); + auto meta_out = at::_ops::mul_Tensor::redispatch(meta_dks, self_meta, other_meta); + return at::_efficientzerotensor(meta_out.sizes(), meta_out.options().device(out_device)); +} + +Tensor div_zerotensor(const Tensor& self, const Tensor& other) { + auto out_device = correct_out_device(self, other); + // hack to use the TensorIterator to get the correct broadcasting and type promotion logic + auto device_ = Device(DeviceType::Meta); + constexpr c10::DispatchKeySet meta_dks(at::DispatchKey::Meta); + auto self_meta = send_to_meta(self, device_); + auto other_meta = send_to_meta(other, device_); + auto meta_out = at::_ops::div_Tensor::redispatch(meta_dks, self_meta, other_meta); + + if (self._is_zerotensor()) { + if (other._is_zerotensor()) { + // 0/0, return full NAN + return at::full(meta_out.sizes(), std::numeric_limits::quiet_NaN(), meta_out.options().device(out_device)); + } + else { + // 0/x, return zero tensor + return at::_efficientzerotensor(meta_out.sizes(), meta_out.options().device(out_device)); + } + } + else { + if (other._is_zerotensor()) { + // x/0, return full INF + return at::full(meta_out.sizes(), std::numeric_limits::infinity(), meta_out.options().device(out_device)); + } + else { + // x/y -- unreachable, see TORCH_INTERNAL_ASSERT above + return at::_efficientzerotensor(meta_out.sizes(), meta_out.options().device(out_device)); + } + } +} + +static Tensor maybe_add_maybe_sub(const Tensor& self, const Tensor& other, const Scalar& alpha) { + auto out_device = correct_out_device(self, other); + // hack to use the TensorIterator to get the correct broadcasting and type promotion logic + auto device_ = Device(DeviceType::Meta); + constexpr c10::DispatchKeySet meta_dks(at::DispatchKey::Meta); + auto self_meta = send_to_meta(self, device_); + auto other_meta = send_to_meta(other, device_); + auto meta_out = at::_ops::add_Tensor::redispatch(meta_dks, self_meta, other_meta, alpha); + + auto get_out_like = [&] (const Tensor& tensor) + { + auto sizes = meta_out.sizes(); + return at::_to_copy(tensor.expand(sizes), meta_out.options().device(out_device)); + }; + + if (self._is_zerotensor()) { + if (other._is_zerotensor()) { + return at::_efficientzerotensor(meta_out.sizes(), meta_out.options().device(out_device)); + } + auto res = get_out_like(other); + return alpha.equal(1) ? std::move(res) : res.mul(alpha); + } else { + return get_out_like(self); + } +} +Tensor add_zerotensor(const Tensor& self, const Tensor& other, const Scalar& alpha) { + return maybe_add_maybe_sub(self, other, alpha); +} + +Tensor sub_zerotensor(const Tensor& self, const Tensor& other, const Scalar& alpha) { + return maybe_add_maybe_sub(self, other, -alpha); +} + +Tensor linalg_cross_zerotensor( + const Tensor& input, + const Tensor& other, + const int64_t dim) +{ + auto out_device = correct_out_device(input, other); + // hack to use the TensorIterator to get the correct broadcasting and type + // promotion logic (see add_zerotensor) + auto device = Device(DeviceType::Meta); + auto meta_out = at::_ops::linalg_cross::redispatch( + c10::DispatchKeySet(at::DispatchKey::Meta), + input.to(device), + other.to(device), + dim); + + return at::_efficientzerotensor( + meta_out.sizes(), + meta_out.options().device(out_device)); +} + +// multiply, alias for mul +Tensor& multiply_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::mul_out(result, self, other); +} + +Tensor multiply(const Tensor& self, const Tensor& other) { + return self.mul(other); +} + +Tensor& multiply_(Tensor& self, const Tensor& other) { + return self.mul_(other); +} + +Tensor multiply(const Tensor& self, const Scalar& other) { + return self.mul(other); +} + +Tensor& multiply_(Tensor& self, const Scalar& other) { + return self.mul_(other); +} + +Tensor sub(const Tensor& self, const Scalar& other, const Scalar& alpha) { + return at::sub(self, wrapped_scalar_tensor(other), alpha); // redispatch! +} + +Tensor& sub_(Tensor& self, const Scalar& other, const Scalar& alpha) { + return self.sub_(wrapped_scalar_tensor(other), alpha); // redispatch! +} + +// subtract, alias for sub +Tensor& subtract_out(const Tensor& self, const Tensor& other, const Scalar& alpha, Tensor& result) { + return at::sub_out(result, self, other, alpha); +} + +Tensor subtract(const Tensor& self, const Tensor& other, const Scalar& alpha) { + return self.sub(other, alpha); +} + +Tensor& subtract_(Tensor& self, const Tensor& other, const Scalar& alpha) { + return self.sub_(other, alpha); +} + +Tensor subtract(const Tensor& self, const Scalar& other, const Scalar& alpha) { + return self.sub(other, alpha); +} + +Tensor& subtract_(Tensor& self, const Scalar& other, const Scalar& alpha) { + return self.sub_(other, alpha); +} + +Tensor rsub(const Tensor& self, const Tensor& other, const Scalar& alpha) { + return at::sub(other, self, alpha); // redispatch! +} + +// TODO: Make this structured to undo the perf regression from native:: removal +// in call here + +Tensor add(const Tensor& self, const Scalar& other, const Scalar& alpha) { + return at::add(self, wrapped_scalar_tensor(other), alpha); +} + +Tensor& add_(Tensor& self, const Scalar& other, const Scalar& alpha) { + return self.add_(wrapped_scalar_tensor(other), alpha); +} + +Tensor remainder(const Tensor& self, const Scalar& other) { + // redispatch + return at::remainder(self, wrapped_scalar_tensor(other)); +} + +Tensor& remainder_(Tensor& self, const Scalar& other) { + // redispatch + return self.remainder_(wrapped_scalar_tensor(other)); +} + +Tensor& remainder_out(const Tensor& self, const Scalar& other, Tensor& result) { + // redispatch + return at::remainder_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor remainder(const Scalar& self, const Tensor& other) { + return at::remainder(wrapped_scalar_tensor(self), other); +} + +Tensor rsub(const Tensor& self, const Scalar& other, const Scalar& alpha) { + return native::rsub(self, wrapped_scalar_tensor(other), alpha); +} + +Tensor& bitwise_and_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::bitwise_and_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_and(const Tensor& self, const Scalar& other) { + return at::bitwise_and(self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_and(const Scalar& self, const Tensor& other) { + return at::bitwise_and(wrapped_scalar_tensor(self), other); +} + +Tensor& bitwise_and_(Tensor& self, const Scalar& other) { + return self.bitwise_and_(wrapped_scalar_tensor(other)); +} + +// Legacy and interfaces. They are aliased to bitwise_and* functions +Tensor __and__(const Tensor& self, const Tensor& other) { + return at::bitwise_and(self, other); +} + +Tensor __and__(const Tensor& self, const Scalar& other) { + return at::bitwise_and(self, other); +} + +Tensor& __iand__(Tensor& self, const Tensor& other) { + return self.bitwise_and_(other); +} + +Tensor& __iand__(Tensor& self, const Scalar& other) { + return self.bitwise_and_(other); +} + +Tensor& bitwise_or_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::bitwise_or_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_or(const Tensor& self, const Scalar& other) { + return at::bitwise_or(self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_or(const Scalar& self, const Tensor& other) { + return at::bitwise_or(wrapped_scalar_tensor(self), other); +} + +Tensor& bitwise_or_(Tensor& self, const Scalar& other) { + return self.bitwise_or_(wrapped_scalar_tensor(other)); +} + +// Legacy or interfaces. They are aliased to bitwise_or* functions +Tensor __or__(const Tensor& self, const Tensor& other) { + return at::bitwise_or(self, other); +} + +Tensor __or__(const Tensor& self, const Scalar& other) { + return at::bitwise_or(self, other); +} + +Tensor& __ior__(Tensor& self, const Tensor& other) { + return self.bitwise_or_(other); +} + +Tensor& __ior__(Tensor& self, const Scalar& other) { + return self.bitwise_or_(other); +} + +Tensor& bitwise_xor_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::bitwise_xor_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_xor(const Tensor& self, const Scalar& other) { + return at::bitwise_xor(self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_xor(const Scalar& self, const Tensor& other) { + return at::bitwise_xor(wrapped_scalar_tensor(self), other); +} + +Tensor& bitwise_xor_(Tensor& self, const Scalar& other) { + return self.bitwise_xor_(wrapped_scalar_tensor(other)); +} + +// Legacy xor interfaces. They are aliased to bitwise_xor* functions +Tensor __xor__(const Tensor& self, const Tensor& other) { + return at::bitwise_xor(self, other); +} + +Tensor __xor__(const Tensor& self, const Scalar& other) { + return at::bitwise_xor(self, other); +} + +Tensor& __ixor__(Tensor& self, const Tensor& other) { + return self.bitwise_xor_(other); +} + +Tensor& __ixor__(Tensor& self, const Scalar& other) { + return self.bitwise_xor_(other); +} + +Tensor __lshift__(const Tensor& self, const Tensor& other) { + Tensor result; + auto iter = TensorIterator::binary_op(result, self, other); + lshift_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor __lshift__(const Tensor& self, const Scalar& other) { + Tensor result; + auto wrapper = wrapped_scalar_tensor(other); + auto iter = TensorIterator::binary_op(result, self, wrapper); + lshift_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor& __ilshift__(Tensor& self, const Tensor& other) { + auto iter = TensorIterator::binary_op(self, self, other); + lshift_stub(iter.device_type(), iter); + return self; +} + +Tensor& __ilshift__(Tensor& self, const Scalar& other) { + auto wrapper = wrapped_scalar_tensor(other); + auto iter = TensorIterator::binary_op(self, self, wrapper); + lshift_stub(iter.device_type(), iter); + return self; +} + +TORCH_IMPL_FUNC(bitwise_left_shift_out) (const Tensor& self, const Tensor& other, const Tensor& result) { + lshift_stub(device_type(), *this); +} + +Tensor& bitwise_left_shift_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::bitwise_left_shift_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_left_shift(const Tensor& self, const Scalar& other) { + return at::bitwise_left_shift(self, wrapped_scalar_tensor(other)); +} + +Tensor& bitwise_left_shift_(Tensor& self, const Scalar& other) { + return at::bitwise_left_shift_out(self, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_left_shift(const Scalar& self, const Tensor& other) { + return at::bitwise_left_shift(wrapped_scalar_tensor(self), other); +} + +Tensor __rshift__(const Tensor& self, const Tensor& other) { + Tensor result; + auto iter = TensorIterator::binary_op(result, self, other); + rshift_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor __rshift__(const Tensor& self, const Scalar& other) { + Tensor result; + auto wrapper = wrapped_scalar_tensor(other); + auto iter = TensorIterator::binary_op(result, self, wrapper); + rshift_stub(iter.device_type(), iter); + return iter.output(); +} + +Tensor& __irshift__(Tensor& self, const Tensor& other) { + auto iter = TensorIterator::binary_op(self, self, other); + rshift_stub(iter.device_type(), iter); + return self; +} + +Tensor& __irshift__(Tensor& self, const Scalar& other) { + auto wrapper = wrapped_scalar_tensor(other); + auto iter = TensorIterator::binary_op(self, self, wrapper); + rshift_stub(iter.device_type(), iter); + return self; +} + +TORCH_IMPL_FUNC(bitwise_right_shift_out) (const Tensor& self, const Tensor& other, const Tensor& result) { + rshift_stub(device_type(), *this); +} + +Tensor& bitwise_right_shift_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::bitwise_right_shift_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_right_shift(const Tensor& self, const Scalar& other) { + return at::bitwise_right_shift(self, wrapped_scalar_tensor(other)); +} + +Tensor& bitwise_right_shift_(Tensor& self, const Scalar& other) { + return at::bitwise_right_shift_out(self, self, wrapped_scalar_tensor(other)); +} + +Tensor bitwise_right_shift(const Scalar& self, const Tensor& other) { + return at::bitwise_right_shift(wrapped_scalar_tensor(self), other); +} + +template +static Tensor& comparison_op_out(Tensor& result, const Tensor& self, const Tensor& other, Stub& stub) { + auto iter = TensorIterator::comparison_op(result, self, other); + stub(iter.device_type(), iter); + return result; +} + +template +static Tensor comparison_op(const Tensor& self, const Tensor& other, OutImpl& out_impl) { + Tensor result = at::empty({0}, self.options().dtype(kBool)); + return out_impl(result, self, other); +} + +template +static Tensor& comparison_op_(Tensor& self, const Tensor& other, OutImpl& out_impl) { + return out_impl(self, self, other); +} + +template +static Tensor& comparison_op_out(Tensor& result, const Tensor& self, const Scalar& other, OutImpl& out_impl) { + return out_impl(result, self, wrapped_scalar_tensor(other)); +} + +template +static Tensor comparison_op(const Tensor& self, const Scalar& other, OutImpl& out_impl) { + return comparison_op(self, wrapped_scalar_tensor(other), out_impl); +} + +template +static Tensor& comparison_op_(Tensor& self, const Scalar& other, OutImpl& out_impl) { + return out_impl(self, self, wrapped_scalar_tensor(other)); +} + +// We need explicit cast to OutFunc because each *_out func is overloaded twice. Without An explicit cast, merely +// referring to *_out function is ambiguous. +using OutFunc = std::add_const_t; + +// less, alias for torch.lt +Tensor& less_out(const Tensor& self, const Tensor& other, Tensor& result) { return at::lt_out(result, self, other); } +Tensor less(const Tensor& self, const Tensor& other) { return self.lt(other); } +Tensor& less_(Tensor& self, const Tensor& other) { return self.lt_(other); } +Tensor& less_out(const Tensor& self, const Scalar& other, Tensor& result) { return at::lt_out(result, self, other); } +Tensor less(const Tensor& self, const Scalar& other) { return self.lt(other); } +Tensor& less_(Tensor& self, const Scalar& other) { return self.lt_(other); } + +// less_equal, alias for torch.le +Tensor& less_equal_out(const Tensor& self, const Tensor& other, Tensor& result) { return at::le_out(result, self, other); } +Tensor less_equal(const Tensor& self, const Tensor& other) { return self.le(other); } +Tensor& less_equal_(Tensor& self, const Tensor& other) { return self.le_(other); } +Tensor& less_equal_out(const Tensor& self, const Scalar& other, Tensor& result) { return at::le_out(result, self, other); } +Tensor less_equal(const Tensor& self, const Scalar& other) { return self.le(other); } +Tensor& less_equal_(Tensor& self, const Scalar& other) { return self.le_(other); } + +// greater, alias for torch.gt +Tensor& greater_out(const Tensor& self, const Tensor& other, Tensor& result) { return at::gt_out(result, self, other); } +Tensor greater(const Tensor& self, const Tensor& other) { return self.gt(other); } +Tensor& greater_(Tensor& self, const Tensor& other) { return self.gt_(other); } +Tensor& greater_out(const Tensor& self, const Scalar& other, Tensor& result) { return at::gt_out(result, self, other); } +Tensor greater(const Tensor& self, const Scalar& other) { return self.gt(other); } +Tensor& greater_(Tensor& self, const Scalar& other) { return self.gt_(other); } + +// greater_equal, alias for torch.ge +Tensor& greater_equal_out(const Tensor& self, const Tensor& other, Tensor& result) { return at::ge_out(result, self, other); } +Tensor greater_equal(const Tensor& self, const Tensor& other) { return self.ge(other); } +Tensor& greater_equal_(Tensor& self, const Tensor& other) { return self.ge_(other); } +Tensor& greater_equal_out(const Tensor& self, const Scalar& other, Tensor& result) { return at::ge_out(result, self, other); } +Tensor greater_equal(const Tensor& self, const Scalar& other) { return self.ge(other); } +Tensor& greater_equal_(Tensor& self, const Scalar& other) { return self.ge_(other); } + +#define CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(func) \ + TORCH_IMPL_FUNC(func##_Tensor_out) \ + (const Tensor& self, const Tensor& other, const Tensor& result) { \ + func##_stub(device_type(), *this); \ + } \ + \ + TORCH_IMPL_FUNC(func##_Scalar_out) \ + (const Tensor& self, const Scalar& other, const Tensor& result) { \ + func##_stub(device_type(), *this); \ + } + +CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(eq) +CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(ne) +CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(gt) +CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(ge) +CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(lt) +CREATE_COMPARISON_SCALAR_TENSOR_IMPL_FUNC(le) + +// not_equal, alias for torch.ne +Tensor& not_equal_out(const Tensor& self, const Tensor& other, Tensor& result) { return at::ne_out(result, self, other); } +Tensor not_equal(const Tensor& self, const Tensor& other) { return self.ne(other); } +Tensor& not_equal_(Tensor& self, const Tensor& other) { return self.ne_(other); } +Tensor& not_equal_out(const Tensor& self, const Scalar& other, Tensor& result) { return at::ne_out(result, self, other); } +Tensor not_equal(const Tensor& self, const Scalar& other) { return self.ne(other); } +Tensor& not_equal_(Tensor& self, const Scalar& other) { return self.ne_(other); } + +Tensor& logical_and_out(const Tensor& self, const Tensor& other, Tensor& result) { return comparison_op_out(result, self, other, logical_and_stub); } +Tensor logical_and(const Tensor& self, const Tensor& other) { return comparison_op(self, other, static_cast(at::logical_and_out)); } +Tensor& logical_and_(Tensor& self, const Tensor& other) { return comparison_op_(self, other, static_cast(at::logical_and_out)); } + +Tensor& logical_or_out(const Tensor& self, const Tensor& other, Tensor& result) { return comparison_op_out(result, self, other, logical_or_stub); } +Tensor logical_or(const Tensor& self, const Tensor& other) { return comparison_op(self, other, static_cast(at::logical_or_out)); } +Tensor& logical_or_(Tensor& self, const Tensor& other) { return comparison_op_(self, other, static_cast(at::logical_or_out)); } + +Tensor& logical_xor_out(const Tensor& self, const Tensor& other, Tensor& result) { return comparison_op_out(result, self, other, logical_xor_stub); } +Tensor logical_xor(const Tensor& self, const Tensor& other) { return comparison_op(self, other, static_cast(at::logical_xor_out)); } +Tensor& logical_xor_(Tensor& self, const Tensor& other) { return comparison_op_(self, other, static_cast(at::logical_xor_out)); } + +// binary max, alias for maximum +Tensor& max_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::maximum_out(result, self, other); +} + +Tensor max(const Tensor& self, const Tensor& other) { + return at::maximum(self, other); +} + +// binary min, alias for minimum +Tensor& min_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::minimum_out(result, self, other); +} + +Tensor min(const Tensor& self, const Tensor& other) { + return at::minimum(self, other); +} + +Tensor floor_divide(const Tensor& self, const Scalar& other) { + return at::floor_divide(self, wrapped_scalar_tensor(other)); +} + +Tensor& floor_divide_(Tensor& self, const Scalar& other) { + return at::floor_divide_out(self, self, wrapped_scalar_tensor(other)); +} + +Tensor& fmod_out(const Tensor& self, const Scalar& other, Tensor & result) { + // redispatch + return at::fmod_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor fmod(const Tensor& self, const Scalar& other) { + // redispatch + return at::fmod(self, wrapped_scalar_tensor(other)); +} + +Tensor& fmod_(Tensor& self, const Scalar& other) { + // redispatch + return self.fmod_(wrapped_scalar_tensor(other)); +} + +// Note: this function is only for testing. +// It is undocumented and should not be used outside of tests. +Tensor _test_serialization_subcmul(const Tensor& self, const Tensor& other, const Scalar& alpha) { + return self - (other * alpha); +} + +TORCH_IMPL_FUNC(heaviside_out) ( + const Tensor& self, const Tensor& other, const Tensor& result +) { + heaviside_stub(device_type(), *this); +} + +static inline Tensor _pow2(const Tensor& self, const Tensor& other) { + const auto self_dtype = self.scalar_type(); + // All integral types are promoted to float32 + if (isIntegralType(self_dtype, true) || self_dtype == kFloat) { + return at::pow(2.0, other); + } + // For double and reduced floating types do regular type promotion + return at::full({}, 2.0, self.options()).pow(other); +} + +// This function is used to dispatch to kernels that use std::ldexp on CPU and the global namespaces ::ldexp on CUDA +// Both of these require floating types for 'self' and integer types for 'other'. +static inline Tensor& _ldexp_int_exponent(const Tensor& self, const Tensor& other, Tensor& result) { + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .add_output(result) + .add_input(self) + .add_input(other) + .build(); + + ldexp_stub(iter.device_type(), iter); + return result; +} + +Tensor& ldexp_out(const Tensor& self, const Tensor& other, Tensor& result) { + TORCH_CHECK(!isIntegralType(result.scalar_type(), /*includeBool=*/true), + "ldexp can't be cast to the desired output type ", result.scalar_type()); + + if (isIntegralType(other.scalar_type(), /*includeBool=*/true) && + isFloatingType(self.scalar_type()) && + ldexp_stub.is_device_supported(self.device().type())) { + return _ldexp_int_exponent(self, other, result); + } + + return at::mul_out(result, self, _pow2(self, other)); +} + +Tensor ldexp(const Tensor& self, const Tensor& other) { + if (isIntegralType(other.scalar_type(), /*includeBool=*/true) && + isFloatingType(self.scalar_type()) && + ldexp_stub.is_device_supported(self.device().type())) { + Tensor result = at::empty_like(self); + return _ldexp_int_exponent(self, other, result); + } + + return at::mul(self, _pow2(self, other)); +} + +Tensor& ldexp_(Tensor& self, const Tensor& other) { + return at::ldexp_out(self, self, other); +} + +Tensor& xlogy_out(const Scalar& self, const Tensor& other, Tensor& result) { + return at::xlogy_out(result, wrapped_scalar_tensor(self), other); +} + +Tensor& xlogy_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::xlogy_out(result, self, wrapped_scalar_tensor(other)); +} + +Tensor xlogy(const Scalar& x, const Tensor& y) { + return at::xlogy(wrapped_scalar_tensor(x), y); +} + +Tensor xlogy(const Tensor& x, const Scalar& y) { + return at::xlogy(x, wrapped_scalar_tensor(y)); +} + +Tensor& xlogy_(Tensor& x, const Scalar& y) { + return at::xlogy_(x, wrapped_scalar_tensor(y)); +} + +Tensor& special_xlogy_out(const Tensor& self, const Tensor& other, Tensor& result) { + return at::xlogy_out(result, self, other); +} + +Tensor& special_xlogy_out(const Scalar& self, const Tensor& other, Tensor& result) { + return at::xlogy_out(result, self, other); +} + +Tensor& special_xlogy_out(const Tensor& self, const Scalar& other, Tensor& result) { + return at::xlogy_out(result, self, other); +} + +Tensor special_xlogy(const Tensor& x, const Tensor& y) { + return at::xlogy(x, y); +} + +Tensor special_xlogy(const Scalar& x, const Tensor& y) { + return at::xlogy(x, y); +} + +Tensor special_xlogy(const Tensor& x, const Scalar& y) { + return at::xlogy(x, y); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BinaryOps.h b/western_ai/usa/pytorch/aten/src/ATen/native/BinaryOps.h new file mode 100644 index 0000000000000000000000000000000000000000..4ae3092bc233d7fd2669b90ed45e02afea91e115 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BinaryOps.h @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include + + +namespace at { +struct TensorIterator; +struct TensorIteratorBase; +} + +namespace at::native { + +inline void alpha_check(const ScalarType dtype, const Scalar& alpha) { + TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool, + "Boolean alpha only supported for Boolean results."); + TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype) + || alpha.isIntegral(true), + "For integral input tensors, argument alpha must not be a floating point number."); + TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(), + "For non-complex input tensors, argument alpha must not be a complex number.") +} + +// Basic checking for all sub functions. +inline void sub_check(const TensorBase& self, const TensorBase& other) { + TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool, + "Subtraction, the `-` operator, with two bool tensors is not supported. " + "Use the `^` or `logical_xor()` operator instead.") + TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool, + "Subtraction, the `-` operator, with a bool tensor is not supported. " + "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead."); +} + +inline void sub_check(const TensorBase& self, const Scalar& scalar) { + TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(), + "Subtraction, the `-` operator, with two bool tensors is not supported. " + "Use the `^` or `logical_xor()` operator instead.") + TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(), + "Subtraction, the `-` operator, with a bool tensor is not supported. " + "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead."); +} + +using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha); +using structured_binary_fn_double = void(*)(TensorIteratorBase&, double); +using structured_binary_fn = void(*)(TensorIteratorBase&); + +using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha); +using binary_fn_double = void(*)(TensorIterator&, double); +using binary_fn = void(*)(TensorIterator&); +using binary_clamp_fn_alpha = + void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val); +using ldexp_fn = void(*)(TensorIteratorBase&); + +// NB: codegenned +DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub) + +DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub) +DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub) +DECLARE_DISPATCH(structured_binary_fn, mul_stub) +DECLARE_DISPATCH(structured_binary_fn, div_true_stub) +DECLARE_DISPATCH(structured_binary_fn, div_floor_stub) +DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub) +DECLARE_DISPATCH(structured_binary_fn, atan2_stub) +DECLARE_DISPATCH(structured_binary_fn, remainder_stub) +DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub) +DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub) +DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub) +DECLARE_DISPATCH(structured_binary_fn, lshift_stub) +DECLARE_DISPATCH(structured_binary_fn, rshift_stub) +DECLARE_DISPATCH(binary_fn, logical_xor_stub) +DECLARE_DISPATCH(binary_fn, logical_and_stub) +DECLARE_DISPATCH(binary_fn, logical_or_stub) +DECLARE_DISPATCH(structured_binary_fn, lt_stub) +DECLARE_DISPATCH(structured_binary_fn, le_stub) +DECLARE_DISPATCH(structured_binary_fn, gt_stub) +DECLARE_DISPATCH(structured_binary_fn, ge_stub) +DECLARE_DISPATCH(structured_binary_fn, eq_stub) +DECLARE_DISPATCH(structured_binary_fn, ne_stub) +DECLARE_DISPATCH(binary_fn, max_elementwise_stub) +DECLARE_DISPATCH(binary_fn, min_elementwise_stub) +DECLARE_DISPATCH(structured_binary_fn, maximum_stub) +DECLARE_DISPATCH(structured_binary_fn, minimum_stub) +DECLARE_DISPATCH(structured_binary_fn, fmax_stub) +DECLARE_DISPATCH(structured_binary_fn, fmin_stub) +DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub) +DECLARE_DISPATCH(binary_fn_double, huber_stub) +DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub) +DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub) +DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub) +DECLARE_DISPATCH(structured_binary_fn, mse_stub) +DECLARE_DISPATCH(structured_binary_fn, fmod_stub) +DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub) +DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub) +DECLARE_DISPATCH(structured_binary_fn, gcd_stub) +DECLARE_DISPATCH(structured_binary_fn, lcm_stub) +DECLARE_DISPATCH(structured_binary_fn, hypot_stub) +DECLARE_DISPATCH(structured_binary_fn, igamma_stub) +DECLARE_DISPATCH(structured_binary_fn, igammac_stub) +DECLARE_DISPATCH(structured_binary_fn, nextafter_stub) +DECLARE_DISPATCH(structured_binary_fn, heaviside_stub) +DECLARE_DISPATCH(structured_binary_fn, copysign_stub) +DECLARE_DISPATCH(structured_binary_fn, xlogy_stub) +DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub) +DECLARE_DISPATCH(structured_binary_fn, zeta_stub) +DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub) +DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub) +DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub) +DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub) +DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub) +DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub) +DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub) +DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub) +DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub) +DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub) +DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub) +DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub) +DECLARE_DISPATCH(ldexp_fn, ldexp_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Blas.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Blas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f78ea1c8a988d8bc14f504aa66a29ae97b1069b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Blas.cpp @@ -0,0 +1,232 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#if !defined(__s390x__) && !defined(__powerpc__) +#include +#endif + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::meta { +TORCH_META_FUNC(addmv)(const Tensor &self, const Tensor &mat, const Tensor &vec, const Scalar& beta, const Scalar& alpha) { + TORCH_CHECK((mat.dim() == 2 && vec.dim() == 1 && self.dim() <= 1), + "vector + matrix @ vector expected, got ", self.dim(), ", ", mat.dim(), ", ", vec.dim()); + + TORCH_CHECK(mat.size(1) == vec.size(0) && (mat.size(0) == self.numel() || self.numel() == 1), + "size mismatch, got input (", self.size(0), "), mat (", mat.size(0), "x", mat.size(1), "), vec (", vec.size(0), ")"); + + TORCH_CHECK(self.scalar_type() == mat.scalar_type() && mat.scalar_type() == vec.scalar_type(), + "addmv input tensors must have the same dtype, but got ", self.scalar_type(), ", ", mat.scalar_type(), ", and ", vec.scalar_type()); + set_output_raw_strided(0, IntArrayRef(mat.sizes().data(), 1), {}, vec.options()); +} +} // namespace at::meta + +namespace at::native { + +template +void gemv(char trans, int64_t m, int64_t n, scalar_t alpha, const scalar_t *a, int64_t lda, const scalar_t *x, int64_t incx, scalar_t beta, scalar_t *y, int64_t incy); + +template +scalar_t dot_impl(int64_t n, const scalar_t *x, int64_t incx, const scalar_t *y, int64_t incy); + +template +scalar_t vdot_impl(int64_t n, const scalar_t *x, int64_t incx, const scalar_t *y, int64_t incy); + +static constexpr bool lda_cond(int64_t m, int64_t n, int64_t lda) { + return n == 1 || lda >= std::max(1L, m); +} + + + + +TORCH_IMPL_FUNC(addmv_out_cpu)(const Tensor &self, const Tensor &mat, const Tensor &vec, const Scalar& beta_, const Scalar& alpha_, const Tensor& result) { + c10::MaybeOwned self_ = expand_size(self, {mat.size(0)}); + auto betaval = beta_.toComplexDouble(); + if (mat.numel() == 0) { + // shortcut for an empty matrix + // By definition, when beta==0, values in self should be ignored. nans and infs + // should not propagate + if (betaval == 0.0) { + result.zero_(); + } else { + at::cpu::mul_out( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + const_cast(result), + self, + at::native::scalar_tensor( + beta_, self.scalar_type(), std::nullopt /* layout */, at::kCPU, std::nullopt /* pin_memory */)); + } + } else { + if (!result.is_same(*self_) && betaval != 0.0) { //if beta is 0, result contents is ignored + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + at::native::copy_(const_cast(result), *self_); + } + if (result.numel() != 0) { + + if (use_mkldnn_matmul(mat, vec, /*result=*/Tensor())){ + mkldnn_matmul(mat, vec, result, beta_.to(), alpha_.to()); + return; + } + + auto r_stride = result.stride(0); + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, mat.scalar_type(), "addmv_impl_cpu", [&] { + auto beta = beta_.to(); + auto alpha = alpha_.to(); + if (mat.stride(0) == 1 && lda_cond(mat.size(0), mat.size(1), mat.stride(1))) { + gemv('n', mat.size(0), mat.size(1), alpha, mat.const_data_ptr(), mat.stride(1), + vec.const_data_ptr(), vec.stride(0), beta, result.mutable_data_ptr(), r_stride); + } + else if (mat.stride(1) == 1 && lda_cond(mat.size(1), mat.size(0), mat.stride(0))) { + gemv('t', mat.size(1), mat.size(0), alpha, mat.const_data_ptr(), mat.stride(0), + vec.const_data_ptr(), vec.stride(0), beta, result.mutable_data_ptr(), r_stride); + } + else { + Tensor cmat = mat.contiguous(); + gemv('t', mat.size(1), mat.size(0), alpha, cmat.const_data_ptr(), cmat.stride(0), + vec.const_data_ptr(), vec.stride(0), beta, result.mutable_data_ptr(), r_stride); + } + }); + } + } +} + +Tensor &mv_out(const Tensor &self, const Tensor &vec, Tensor& result) { + //self arg sent to addmv_out cannot be resized + //here we use result as self argument for addmv, and result is user supplied and can be wrong size + //it's not a hard error, because we allow resizing result, but it becomes a hard error + //in addmv, because addmv expects self to satisfy proper conditions + //to avoid this, supply correctly sized self, its contents doesn't matter because beta is 0 + if (result.dim() > 1 || (result.numel() != self.size(0) && result.numel() != 1)) { + Tensor self_addmv = at::empty({self.size(0)}, vec.options()); + return at::addmv_out(result, self_addmv, self, vec, 0, 1); + } + return at::addmv_out(result, result, self, vec, 0, 1); +} + +Tensor mv(const Tensor &self, const Tensor &vec) { + Tensor result = at::empty({self.size(0)}, vec.options()); + //inplace version is more efficient if we can use it + return at::addmv_(result, self, vec, 0, 1); +} + +static inline void dot_check(const Tensor& self, const Tensor& other) { + TORCH_CHECK( + self.dim() == 1 && other.dim() == 1, + "1D tensors expected, but got ", + self.dim(), + "D and ", + other.dim(), + "D tensors"); + + TORCH_CHECK( + self.scalar_type() == other.scalar_type(), + "dot : expected both vectors to have same dtype, but found ", + self.scalar_type(), + " and ", + other.scalar_type()); + + TORCH_CHECK( + self.numel() == other.numel(), + "inconsistent tensor size, expected tensor [", + self.numel(), + "] and src [", + other.numel(), + "] to have the same number of elements, but got ", + self.numel(), + " and ", + other.numel(), + " elements respectively"); +} + +Tensor dot(const Tensor &self, const Tensor &other){ + if (self.is_complex()) { + if (self.is_conj()) { + if (other.is_conj()) { + return (at::native::dot(self.conj(), other.conj())).conj(); + } else { + return at::native::vdot(self.conj(), other); + } + } else if (other.is_conj()) { + return at::native::vdot(other.conj(), self); + } + } + + dot_check(self, other); + + if (self._is_zerotensor() || other._is_zerotensor()) { + return at::_efficientzerotensor({}, self.options()); + } + + if (use_mkldnn_matmul(self, other, /*result=*/Tensor())){ + // mkldnn matmul expect result have sizes info to create ideep tensor + auto r = at::empty({1, 1}, self.options()); + mkldnn_matmul(self, other, r, /*beta=*/0); + return r; + } + + return AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, self.scalar_type(), "dot", [&] { + Tensor result = at::empty({}, self.options()); + result.fill_(dot_impl(self.numel(), self.const_data_ptr(), self.stride(0), other.const_data_ptr(), other.stride(0))); + return result; + }); +} + +Tensor vdot(const Tensor &self, const Tensor &other){ + // Dispatch to `dot` for real dtypes. + if (!self.is_complex()){ + return at::dot(self, other); + } + + if (self.is_conj()) { + if (other.is_conj()) { + return at::native::vdot(other.conj(), self.conj()); + } else { + return at::native::dot(self.conj(), other); + } + } else if (other.is_conj()) { + return (at::native::dot(self, other.conj())).conj(); + } + + // For complex dtypes. + dot_check(self, other); + + if (self._is_zerotensor() || other._is_zerotensor()) { + return at::_efficientzerotensor({}, self.options()); + } + + return AT_DISPATCH_COMPLEX_TYPES(self.scalar_type(), "vdot", [&] { + Tensor result = at::empty({}, self.options()); + result.fill_(vdot_impl(self.numel(), self.const_data_ptr(), self.stride(0), other.const_data_ptr(), other.stride(0))); + return result; + }); + +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BlasKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/BlasKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19160017c6b7ae4c1596c650ed1ba4528f70f97a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BlasKernel.cpp @@ -0,0 +1,790 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__aarch64__) && !defined(C10_MOBILE) +#include +#include +#endif + +namespace { + +/// Wrapper for const_cast with type-inference. +/// +/// Use this to call into APIs that are not const-correct. +template +T* remove_const(const T* x) { + return const_cast(x); +} + +} // namespace + +#if AT_BUILD_WITH_BLAS() +#ifndef _ARMPL_H +extern "C" double ddot_(int *n, double *x, int *incx, double *y, int *incy); +extern "C" void dscal_(int *n, double *a, double *x, int *incx); +extern "C" void sscal_(int *n, float *a, float *x, int *incx); +extern "C" void dgemv_(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy); +extern "C" void sgemv_(char *trans, int *m, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy); +#endif + +#if AT_BLAS_F2C() +# define ffloat double +#else +# define ffloat float +#endif + +#if AT_BLAS_USE_CBLAS_DOT() + extern "C" float cblas_sdot(const int n, const float *x, const int incx, const float *y, const int incy); + extern "C" void cblas_cdotu_sub(const int n, const void *x, const int incx, const void *y, const int incy, void *dotu); + extern "C" void cblas_zdotu_sub(const int n, const void *x, const int incx, const void *y, const int incy, void *dotu); + extern "C" void cblas_cdotc_sub(const int n, const void *x, const int incx, const void *y, const int incy, void *dotc); + extern "C" void cblas_zdotc_sub(const int n, const void *x, const int incx, const void *y, const int incy, void *dotc); + +#ifndef _ARMPL_H + static inline ffloat sdot_(const int *n, const float *x, const int *incx, const float *y, const int *incy) + { + return cblas_sdot(*n, x, *incx, y, *incy); + } +#endif + static inline void cdotu_(std::complex *res, const int *n, const std::complex *x, const int *incx, + const std::complex *y, const int *incy) { + cblas_cdotu_sub(*n, x, *incx, y, *incy, res); + } + static inline void zdotu_(std::complex *res, const int *n, const std::complex *x, const int *incx, + const std::complex *y, const int *incy) { + cblas_zdotu_sub(*n, x, *incx, y, *incy, res); + } + static inline void cdotc_(std::complex *res, const int *n, const std::complex *x, const int *incx, + const std::complex *y, const int *incy) { + cblas_cdotc_sub(*n, x, *incx, y, *incy, res); + } + static inline void zdotc_(std::complex *res, const int *n, const std::complex *x, const int *incx, + const std::complex *y, const int *incy) { + cblas_zdotc_sub(*n, x, *incx, y, *incy, res); + } + +#else + extern "C" ffloat sdot_(int *n, const float *x, int *incx, const float *y, int *incy); + extern "C" void cdotu_(std::complex *res, int *n, const std::complex *x, int *incx, const std::complex *y, int *incy); + extern "C" void zdotu_(std::complex *res, int *n, const std::complex *x, int *incx, const std::complex *y, int *incy); + extern "C" void cdotc_(std::complex *res, int *n, const std::complex *x, int *incx, const std::complex *y, int *incy); + extern "C" void zdotc_(std::complex *res, int *n, const std::complex *x, int *incx, const std::complex *y, int *incy); +#endif // AT_BLAS_USE_CBLAS_DOT +#endif // AT_BUILD_WITH_BLAS + +namespace at::native { +#if !defined(C10_MOBILE) +DEFINE_DISPATCH(fp16_gemv_trans_stub); +DEFINE_DISPATCH(bf16_gemv_trans_stub); +DEFINE_DISPATCH(fp16_dot_stub); +DEFINE_DISPATCH(bf16_dot_stub); +#endif // !defined(C10_MOBILE) + +namespace blas_impl { +#if !defined(C10_MOBILE) +void fp16_gemv_trans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy); + +void fp16_gemv_trans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy) { + fp16_gemv_trans_stub(kCPU, m, n, alpha, a, lda, x, incx, beta, y, incy); +} + +static float fp16_dot( + const int64_t n, + const Half* x, + const int64_t incx, + const Half* y, + const int64_t incy) { + return fp16_dot_stub(kCPU, n, x, incx, y, incy); +} + +static float bf16_dot( + const int64_t n, + const BFloat16* x, + const int64_t incx, + const BFloat16* y, + const int64_t incy) { + return bf16_dot_stub(kCPU, n, x, incx, y, incy); +} + +#endif // !defined(C10_MOBILE) + +#if defined(__aarch64__) && !defined(C10_MOBILE) +#ifdef __ARM_FEATURE_FP16_SCALAR_ARITHMETIC +static void fp16_gemv_notrans_fp16_arith(int m, int n, const float16_t* a, const int lda, const float16_t *x, float16_t *y) { + for (auto j = 0; j < n; j++) { + auto vecCol = vdup_n_f16(x[j]); + const auto* column = a + lda * j; + for (auto i = 0; i < m; i += 4) { + auto yf16 = y + i; + auto matRow = vld1_f16(column + i); + auto resVec = j != 0 ? vld1_f16(yf16) : vdup_n_f16(0); + resVec = vfma_lane_f16(resVec, matRow, vecCol, 0); + vst1_f16(yf16, resVec); + } + } +} +#endif + +static void fp16_gemv_notrans_fp32_arith(int m, int n, const float16_t* a, const int lda, const float16_t *x, float16_t *y) { + std::vector sum(m); + for (auto j = 0; j < n; j++) { + auto vecCol = vdup_n_f32(x[j]); + const auto* column = a + lda * j; + for (auto i = 0; i < m; i += 4) { + auto sf32 = sum.data() + i; + auto matRow = vcvt_f32_f16(vld1_f16(column + i)); + auto resVec = j != 0 ? vld1q_f32(sf32) : vdupq_n_f32(0); + resVec = vfmaq_lane_f32(resVec, matRow, vecCol, 0); + vst1q_f32(sf32, resVec); + } + } + + for (auto i = 0; i < m; i+= 4) { + vst1_f16(y + i, vcvt_f16_f32(vld1q_f32(sum.data() + i))); + } +} + +void fp16_gemv_notrans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy); + +void fp16_gemv_notrans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy) { + if (incx == 1 && alpha == 1.0 && beta == 0.0 && m % 4 == 0 && incy == 1) { +#ifdef __ARM_FEATURE_FP16_SCALAR_ARITHMETIC + if (at::globalContext().allowFP16ReductionCPU()) { + return fp16_gemv_notrans_fp16_arith(m, n, reinterpret_cast(a), lda, reinterpret_cast(x), reinterpret_cast(y)); + } +#endif + return fp16_gemv_notrans_fp32_arith(m, n, reinterpret_cast(a), lda, reinterpret_cast(x), reinterpret_cast(y)); + } + std::vector sum(m); + for (const auto j : c10::irange(n)) { + const auto* column_ = a + lda * j; + auto z = alpha * x[j * incx]; + for (const auto i : c10::irange(m)) { + sum[i] += z * column_[i]; + } + } + if (beta == 0.0) { + for (const auto i : c10::irange(m)) { + y[i * incy] = sum[i]; + } + } else { + for (const auto i : c10::irange(m)) { + y[i * incy] += sum[i]; + } + } +} + +#endif // defined(__aarch64__) && !defined(C10_MOBILE) + +template +static bool scal_use_fast_path( + [[maybe_unused]] int64_t n, + [[maybe_unused]] int64_t incx) { + return false; +} + +template +static bool gemv_use_fast_path( + [[maybe_unused]] char trans, + [[maybe_unused]] int64_t m, + [[maybe_unused]] int64_t n, + [[maybe_unused]] scalar_t alpha, + [[maybe_unused]] int64_t lda, + [[maybe_unused]] int64_t incx, + [[maybe_unused]] scalar_t beta, + [[maybe_unused]] int64_t incy) { + return false; +} + +template +static void scal_fast_path( + [[maybe_unused]] int* n, + [[maybe_unused]] scalar_t* a, + [[maybe_unused]] scalar_t* x, + [[maybe_unused]] int* incx) { + TORCH_INTERNAL_ASSERT( + false, "scal_fast_path shouldn't be called for this configuration"); +} + +template +static void gemv_fast_path( + [[maybe_unused]] const char* trans, + [[maybe_unused]] const int* m, + [[maybe_unused]] const int* n, + [[maybe_unused]] const scalar_t* alpha, + [[maybe_unused]] const scalar_t* a, + [[maybe_unused]] const int* lda, + [[maybe_unused]] const scalar_t* x, + [[maybe_unused]] const int* incx, + [[maybe_unused]] const scalar_t* beta, + [[maybe_unused]] scalar_t* y, + [[maybe_unused]] const int* incy) { + TORCH_INTERNAL_ASSERT( + false, "gemv_fast_path shouldn't be called for this configuration"); +} + +#define INSTANTIATE(scalar_t) \ +template bool scal_use_fast_path(int64_t n, int64_t incx); \ +template bool gemv_use_fast_path(char trans, int64_t m, int64_t n, scalar_t alpha, int64_t lda, int64_t incx, scalar_t beta, int64_t incy); \ +template void gemv_fast_path(const char *trans, const int *m, const int *n, const scalar_t *alpha, const scalar_t *a, const int *lda, const scalar_t *x, const int *incx, const scalar_t *beta, scalar_t *y, const int *incy); \ +template void scal_fast_path(int *n, scalar_t *a, scalar_t *x, int *incx); + +#if AT_BUILD_WITH_BLAS() +template <> +bool scal_use_fast_path(int64_t n, int64_t incx) { + auto constexpr intmax = std::numeric_limits::max(); + return n <= intmax && incx <= intmax; +} + +template <> +bool scal_use_fast_path(int64_t n, int64_t incx) { + return scal_use_fast_path(n, incx); +} + +template <> +void scal_fast_path(int *n, double *a, double *x, int *incx) { + dscal_(n, a, x, incx); +} + +template <> +void scal_fast_path(int *n, float *a, float *x, int *incx) { + sscal_(n, a, x, incx); +} + +template <> +bool gemv_use_fast_path( + [[maybe_unused]] char trans, + int64_t m, + int64_t n, + [[maybe_unused]] float alpha, + int64_t lda, + int64_t incx, + [[maybe_unused]] float beta, + int64_t incy) { + auto constexpr intmax = std::numeric_limits::max(); + return (m <= intmax) && (n <= intmax) && (lda <= intmax) && + (incx > 0) && (incx <= intmax) && (incy > 0) && (incy <= intmax); +} + +template <> +bool gemv_use_fast_path( + [[maybe_unused]] char trans, + int64_t m, + int64_t n, + [[maybe_unused]] double alpha, + int64_t lda, + int64_t incx, + [[maybe_unused]] double beta, + int64_t incy) { + return gemv_use_fast_path( + trans, m, n, static_cast(alpha), lda, incx, static_cast(beta), incy); +} + +template <> +void gemv_fast_path(const char *trans, const int *m, const int *n, const double *alpha, const double *a, const int *lda, const double *x, const int *incx, const double *beta, double *y, const int *incy) { + dgemv_(remove_const(trans), remove_const(m), remove_const(n), remove_const(alpha), remove_const(a), remove_const(lda), remove_const(x), remove_const(incx), remove_const(beta), y, remove_const(incy)); +} + +template <> +void gemv_fast_path(const char *trans, const int *m, const int *n, const float *alpha, const float *a, const int *lda, const float *x, const int *incx, const float *beta, float *y, const int *incy) { + sgemv_(remove_const(trans), remove_const(m), remove_const(n), remove_const(alpha), remove_const(a), remove_const(lda), remove_const(x), remove_const(incx), remove_const(beta), y, remove_const(incy)); +} + +INSTANTIATE(uint8_t) +INSTANTIATE(int8_t) +INSTANTIATE(int16_t) +INSTANTIATE(int) +INSTANTIATE(int64_t) +#if !defined(C10_MOBILE) +template <> +bool gemv_use_fast_path( + [[maybe_unused]] char trans, + [[maybe_unused]] int64_t m, + [[maybe_unused]] int64_t n, + at::BFloat16 alpha, + [[maybe_unused]] int64_t lda, + [[maybe_unused]] int64_t incx, + at::BFloat16 beta, + [[maybe_unused]] int64_t incy) { + return (trans == 'T' || trans == 't') && incx == 1 && alpha == 1.0 && + beta == 0.0; +} + +static void bf16_gemv_trans( + const int m, + const int n, + const at::BFloat16 alpha, + const at::BFloat16* a, + const int lda, + const at::BFloat16* x, + const int incx, + const at::BFloat16 beta, + at::BFloat16* y, + const int incy) { + bf16_gemv_trans_stub(kCPU, m, n, alpha, a, lda, x, incx, beta, y, incy); +} + +template <> +void gemv_fast_path( + const char* trans, + const int* m, + const int* n, + const at::BFloat16* alpha, + const at::BFloat16* a, + const int* lda, + const at::BFloat16* x, + const int* incx, + const at::BFloat16* beta, + at::BFloat16* y, + const int* incy) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(trans[0] == 'T' || trans[0] == 't'); + bf16_gemv_trans( + *m, + *n, + *alpha, + a, + *lda, + x, + *incx, + *beta, + y, + *incy); +} +#if !defined(__aarch64__) +// Currently, only fp16_gemv_trans is built for non-aarch64. +template <> +bool gemv_use_fast_path( + char trans, + [[maybe_unused]] int64_t m, + [[maybe_unused]] int64_t n, + at::Half alpha, + [[maybe_unused]] int64_t lda, + [[maybe_unused]] int64_t incx, + [[maybe_unused]] at::Half beta, + [[maybe_unused]] int64_t incy) { + // clang is capable of constant-folding fp16_ieee_from_fp32_value, + // so use it to get simple integer comparisons. + // https://godbolt.org/z/v936hroYb + using c10::detail::fp16_ieee_from_fp32_value;; + return (trans == 'T' || trans == 't') && incx == 1 && + alpha.x == fp16_ieee_from_fp32_value(1.0f); +} +template <> +void gemv_fast_path( + const char* trans, + const int* m, + const int* n, + const at::Half* alpha, + const at::Half* a, + const int* lda, + const at::Half* x, + const int* incx, + const at::Half* beta, + at::Half* y, + const int* incy) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(trans[0] == 'T' || trans[0] == 't'); + fp16_gemv_trans( + *m, + *n, + *alpha, + a, + *lda, + x, + *incx, + *beta, + y, + *incy); +} +#else // !defined(__aarch64__)) +template <> +bool gemv_use_fast_path( + char trans, + [[maybe_unused]] int64_t m, + [[maybe_unused]] int64_t n, + at::Half alpha, + [[maybe_unused]] int64_t lda, + [[maybe_unused]] int64_t incx, + at::Half beta, + [[maybe_unused]] int64_t incy) { + return incx == 1 && c10::detail::fp16_from_bits(alpha.x) == 1.0f && + // TODO: enable nonzero beta for fp16_gemv_notrans + (c10::detail::fp16_from_bits(beta.x) == 0.0f || trans == 't' || trans == 'T'); +} + +template <> +void gemv_fast_path( + const char* trans, + const int* m, + const int* n, + const at::Half* alpha, + const at::Half* a, + const int* lda, + const at::Half* x, + const int* incx, + const at::Half* beta, + at::Half* y, + const int* incy) { + using namespace c10::detail; + if ((trans[0] == 'T') || (trans[0] == 't')) { + fp16_gemv_trans( + *m, + *n, + *alpha, + a, + *lda, + x, + *incx, + *beta, + y, + *incy); + } else { + fp16_gemv_notrans( + *m, + *n, + *alpha, + a, + *lda, + x, + *incx, + *beta, + y, + *incy); + } +} + +// Note that the above block was an else, so it's active if __aarch64__ *is* defined. +#endif // !defined(__aarch64__) +#else // !defined(C10_MOBILE)) +INSTANTIATE(c10::Half) +INSTANTIATE(c10::BFloat16) +#endif // !defined(C10_MOBILE) +#endif // AT_BUILD_WITH_BLAS +#undef INSTANTIATE + +} // namespace blas_impl + +template +static inline void scal(int64_t n, scalar_t a, scalar_t *x, int64_t incx) +{ + if (n == 1) incx = 1; +#if AT_BUILD_WITH_BLAS() + if (blas_impl::scal_use_fast_path(n, incx)) { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + blas_impl::scal_fast_path(&i_n, &a, x, &i_incx); + return; + } +#endif + for (const auto i : c10::irange(n)) { + if (a == scalar_t(0)) { + x[i * incx] = 0; + } else { + x[i * incx] *= a; + } + } +} + +template +void gemv(char trans, int64_t m, int64_t n, scalar_t alpha, const scalar_t *a, int64_t lda, const scalar_t *x, int64_t incx, scalar_t beta, scalar_t *y, int64_t incy) { + if(n == 1) lda = m; + +#if AT_BUILD_WITH_BLAS() + if (blas_impl::gemv_use_fast_path(trans, m, n, alpha, lda, incx, beta, incy)) { + TORCH_CHECK(lda >= std::max(1L, m), "lda should be at least max(1,", m, "), but have ", lda); + int i_m = static_cast(m); + int i_n = static_cast(n); + int i_lda = static_cast(lda); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + blas_impl::gemv_fast_path(&trans, &i_m, &i_n, &alpha, a, &i_lda, x, &i_incx, &beta, y, &i_incy); + return; + } +#endif + + using opmath_t = at::opmath_type; + if ((trans == 'T') || (trans == 't')) { + for (const auto i : c10::irange(n)) { + opmath_t sum = 0; + const scalar_t *row_ = a + lda * i; + for (const auto j : c10::irange(m)) { + sum += static_cast(x[j * incx]) * static_cast(row_[j]); + } + if (beta == scalar_t(0)) { + y[i * incy] = alpha * sum; + } else { + y[i * incy] = beta * y[i * incy] + alpha * sum; + } + } + } else { + if (beta != scalar_t(1) && beta != scalar_t(0)) scal(m, beta, y, incy); + + constexpr bool is_low_precision = !std::is_same_v; + std::vector sum; + if constexpr (is_low_precision) { + sum.resize(m); + } + for (const auto j : c10::irange(n)) { + const scalar_t *column_ = a + lda * j; + opmath_t z = alpha * static_cast(x[j * incx]); + for (const auto i : c10::irange(m)) { + //output values are ignored if beta is 0, and set to 0, nans and infs are not propagated + if (j==0 && beta==scalar_t(0)) { + if constexpr (!is_low_precision) { + y[i * incy] = 0; + } + } + if constexpr (is_low_precision) { + sum[i] += z * column_[i]; + } else { + y[i * incy] += z * column_[i]; + } + } + } + if constexpr (is_low_precision) { + if (beta == scalar_t(0)) { + for (const auto i : c10::irange(m)) { + y[i * incy] = sum[i]; + } + } else { + for (const auto i : c10::irange(m)) { + y[i * incy] += sum[i]; + } + } + } + } + return; +} + +#define INSTANTIATE(scalar_t, _) \ +template void gemv(char trans, int64_t m, int64_t n, scalar_t alpha, const scalar_t *a, int64_t lda, const scalar_t *x, int64_t incx, scalar_t beta, scalar_t *y, int64_t incy); +AT_FORALL_SCALAR_TYPES_AND2(BFloat16, Half, INSTANTIATE) +AT_FORALL_COMPLEX_TYPES(INSTANTIATE) +#undef INSTANTIATE + +namespace blas_impl { +#if AT_BUILD_WITH_BLAS() +static float dot_fast_path(int n, const float* x, int incx, const float* y, int incy) { + return sdot_(&n, x, &incx, y, &incy); +} + +static double dot_fast_path(int n, const double* x, int incx, const double* y, int incy) { + return ddot_(&n, const_cast(x), &incx, const_cast(y), &incy); +} + +static c10::complex vdot_fast_path(int n, const c10::complex* x, int incx, const c10::complex* y, int incy) { + c10::complex result; + cdotc_(reinterpret_cast* >(&result), &n, reinterpret_cast*>(x), &incx, reinterpret_cast*>(y), &incy); + return result; +} + +static c10::complex vdot_fast_path(int n, const c10::complex* x, int incx, const c10::complex* y, int incy) { + c10::complex result; + zdotc_(reinterpret_cast* >(&result), &n, reinterpret_cast*>(x), &incx, reinterpret_cast*>(y), &incy); + return result; +} + +static c10::complex dot_fast_path(int n, const c10::complex* x, int incx, const c10::complex* y, int incy) { + c10::complex result; + zdotu_(reinterpret_cast* >(&result), &n, reinterpret_cast*>(x), &incx, reinterpret_cast*>(y), &incy); + return result; +} + +static c10::complex dot_fast_path(int n, const c10::complex* x, int incx, const c10::complex* y, int incy) { + c10::complex result; + cdotu_(reinterpret_cast* >(&result), &n, reinterpret_cast*>(x), &incx, reinterpret_cast*>(y), &incy); + return result; +} +#endif + +template +static scalar_t dot_naive( + int64_t n, + const scalar_t* x, + int64_t incx, + const scalar_t* y, + int64_t incy, + Functor op) { + using opmath_t = at::opmath_type; + opmath_t sum = 0; + for (int64_t i = 0; i < n; i++) { + sum += op(static_cast(x[i * incx]), static_cast(y[i * incy])); + } + return static_cast(sum); +} + +} // namespace blas_impl + +template +static scalar_t dot_impl_floating(int64_t n, const scalar_t* x, int64_t incx, const scalar_t* y, int64_t incy) +{ + if (n == 1) { + incx = 1; + incy = 1; + } +#if AT_BUILD_WITH_BLAS() + if ((n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX)) { + return blas_impl::dot_fast_path(n, x, incx, y, incy); + } else { + return blas_impl::dot_naive(n, x, incx, y, incy, std::multiplies{}); + } +#else + { return blas_impl::dot_naive(n, x, incx, y, incy, std::multiplies{}); } +#endif +} + +template +scalar_t dot_impl(int64_t n, const scalar_t* x, int64_t incx, const scalar_t* y, int64_t incy) { + if (n == 1) { + incx = 1; + incy = 1; + } + return blas_impl::dot_naive(n, x, incx, y, incy, std::multiplies>{}); +} + +template <> +float dot_impl(int64_t n, const float* x, int64_t incx, const float* y, int64_t incy) { + return dot_impl_floating(n, x, incx, y, incy); +} + +template <> +double dot_impl(int64_t n, const double* x, int64_t incx, const double* y, int64_t incy) { + return dot_impl_floating(n, x, incx, y, incy); +} + +template <> +c10::complex dot_impl(int64_t n, const c10::complex* x, int64_t incx, const c10::complex* y, int64_t incy) { + return dot_impl_floating(n, x, incx, y, incy); +} + +template <> +c10::complex dot_impl(int64_t n, const c10::complex* x, int64_t incx, const c10::complex* y, int64_t incy) { + return dot_impl_floating(n, x, incx, y, incy); +} + +template <> +Half dot_impl(int64_t n, const Half* x, int64_t incx, const Half* y, int64_t incy) { + if (n == 1) { + incx = 1; + incy = 1; + } +#if !defined(C10_MOBILE) + if (incx == 1 && incy == 1) { + return blas_impl::fp16_dot(n, x, incx, y, incy); + } +#endif // !defined(C10_MOBILE) + return blas_impl::dot_naive(n, x, incx, y, incy, std::multiplies{}); +} + +template <> +BFloat16 dot_impl(int64_t n, const BFloat16* x, int64_t incx, const BFloat16* y, int64_t incy) { + if (n == 1) { + incx = 1; + incy = 1; + } +#if !defined(C10_MOBILE) + if (incx == 1 && incy == 1) { + return blas_impl::bf16_dot(n, x, incx, y, incy); + } +#endif // !defined(C10_MOBILE) + return blas_impl::dot_naive(n, x, incx, y, incy, std::multiplies{}); +} + +namespace { +template +struct vdot_op { + scalar_t operator()(scalar_t x, scalar_t y) { + return std::conj(x) * y; + } +}; +} // anonymous namespace + +template +scalar_t vdot_impl(int64_t n, const scalar_t* x, int64_t incx, const scalar_t* y, int64_t incy) { + if (n == 1) { + incx = 1; + incy = 1; + } +#if AT_BUILD_WITH_BLAS() + if ((n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX)) { + return blas_impl::vdot_fast_path(n, x, incx, y, incy); + } else { + return blas_impl::dot_naive(n, x, incx, y, incy, vdot_op{}); + } +#else + { return blas_impl::dot_naive(n, x, incx, y, incy, vdot_op{}); } +#endif +} + +// Skip reinstantiating the explicitly specialized types `float`, `double`, `half` & `bfloat16`. +#define INSTANTIATE_DOT_IMPL(scalar_t) \ + template scalar_t dot_impl( \ + int64_t n, const scalar_t * x, int64_t incx, const scalar_t * y, int64_t incy); +INSTANTIATE_DOT_IMPL(uint8_t) +INSTANTIATE_DOT_IMPL(int8_t) +INSTANTIATE_DOT_IMPL(int16_t) +INSTANTIATE_DOT_IMPL(int) +INSTANTIATE_DOT_IMPL(int64_t) + +#define INSTANTIATE_VDOT_IMPL(scalar_t) \ + template scalar_t vdot_impl( \ + int64_t n, const scalar_t * x, int64_t incx, const scalar_t * y, int64_t incy); +INSTANTIATE_VDOT_IMPL(c10::complex) +INSTANTIATE_VDOT_IMPL(c10::complex) + +#undef INSTANTIATE_DOT_IMPL + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Bucketization.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Bucketization.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e09d0078741a45070a9af3ae11627e30c5127afa --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Bucketization.cpp @@ -0,0 +1,246 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#endif + +/* Implement a numpy like searchsorted and a TF like bucketize function running on cpu + * + * - torch.searchsorted(sorted_sequence, values, right=False, side=None, out_int32=False, sorter=None) + * sorted_sequence - N*D or 1D (apply to all values) tensor containing sorted sequences in last dimension + * values - N*D tensor or a Scalar (when sorted_sequence is 1D) containing the search values + * right - corresponding to lower bound if False and upper bound if True + * side - (preferred to right) corresponding to lower bound if 'left' and upper bound if 'right' + * out_int32 - the output tensor is int64_t type if False and int(32bit normally) type if True. + * sorter - if provided, sorted_sequence may not be sorted and the sorted order is given by this tensor + * + * - torch.bucketize(values, boundaries, right=False, out_int32=False) + * values - N*D tensor or a Scalar containing the search value + * boundaries - 1D tensor containing a sorted sequences + * right - corresponding to lower bound if False and upper bound if True + * out_int32 - the output tensor is int64_t type if False and int(32bit normally) type if True. + * + * - Restrictions are defined in searchsorted_pre_check() + */ + +namespace at::native { + +namespace { + +// minimal size for searchsorted_cpu_contiguous to run parallel (multithread) +constexpr int64_t SEARCHSORTED_GRAIN_SIZE = 200; + +// customized lower_bound func to ensure the low bound of 'nan', 'inf' etc. be the end of boundary +// and we can properly handle a sorter argument +// std::lower_bound can not be used here since its customized comparator need strict weak ordering +// and the customized comparators require both arguments to have the same type, which wouldn't +// happen when comparing val of input_t to an indexer value from sorter of int64 +template +int64_t cus_lower_bound(int64_t start, int64_t end, const input_t val, const input_t* bd, const int64_t* sort) { + // sorter gives relative ordering for ND tensors, so we need to save and add the non-updated start as an offset + // i.e. the second row of a 3x3 tensors starts at element 3 but sorter's second row only contains 0, 1, or 2 + const int64_t orig_start = start; + while (start < end) { + const int64_t mid = start + ((end - start) >> 1); + const input_t mid_val = sort ? bd[sort[mid] + orig_start] : bd[mid]; + if (!(mid_val >= val)) { + start = mid + 1; + } + else { + end = mid; + } + } + return start; +} + +// customized upper_bound func to ensure we can properly handle a sorter argument +// std::upper_bound can not be used here since its customized comparator requires both arguments to have the +// same type, which wouldn't happen when comparing val of input_t to an indexer value from sorter of int64 +template +int64_t cus_upper_bound(int64_t start, int64_t end, const input_t val, const input_t* bd, const int64_t* sort) { + // sorter gives relative ordering for ND tensors, so we need to save and add the non-updated start as an offset + // i.e. the second row of a 3x3 tensors starts at element 3 but sorter's second row only contains 0, 1, or 2 + const int64_t orig_start = start; + while (start < end) { + const int64_t mid = start + ((end - start) >> 1); + const input_t mid_val = sort ? bd[sort[mid] + orig_start] : bd[mid]; + if (!(mid_val > val)) { + start = mid + 1; + } + else { + end = mid; + } + } + return start; +} + +template +void searchsorted_cpu_contiguous(Tensor& result, const Tensor& input, const Tensor& boundaries, const bool& right, const Tensor& sorter) { + int64_t numel_in = input.numel(); + bool is_scalar_input = input.dim() == 0 && numel_in == 1; + // inner most dim size of input and boundaries + int64_t idim_in = is_scalar_input ? 1 : input.sizes().back(); + int64_t idim_bd = boundaries.sizes().back(); + + const input_t *data_in = input.const_data_ptr(); + const input_t *data_bd = boundaries.const_data_ptr(); + const int64_t *data_st = sorter.defined() ? sorter.const_data_ptr() : nullptr; + output_t *data_out = result.data_ptr(); + + bool is_1d_boundaries = boundaries.dim() == 1; + at::parallel_for(0, numel_in, SEARCHSORTED_GRAIN_SIZE, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + // If boundaries tensor is 1d, we always search the entire boundary tensor + int64_t start_bd = is_1d_boundaries ? 0 : i / idim_in * idim_bd; + int64_t end_bd = start_bd + idim_bd; + + int64_t pos = !right ? + cus_lower_bound(start_bd, end_bd, data_in[i], data_bd, data_st) - start_bd : + cus_upper_bound(start_bd, end_bd, data_in[i], data_bd, data_st) - start_bd; + + // type conversion might happen here + data_out[i] = pos; + } + }); +} + +void dispatch(Tensor& result, const Tensor& input, const Tensor& boundaries, bool out_int32, bool right, const Tensor& sorter) { + if (!out_int32) { + AT_DISPATCH_ALL_TYPES_AND2( + ScalarType::Half, + ScalarType::BFloat16, + input.scalar_type(), + "searchsorted_out_cpu", + [&] { + searchsorted_cpu_contiguous( + result, input, boundaries, right, sorter); + }); + } + else { + AT_DISPATCH_ALL_TYPES_AND2( + ScalarType::Half, + ScalarType::BFloat16, + input.scalar_type(), + "searchsorted_out_cpu", + [&] { + searchsorted_cpu_contiguous( + result, input, boundaries, right, sorter); + }); + } +} + +} + +Tensor& searchsorted_out_cpu( + const Tensor& sorted_sequence, + const Tensor& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter_opt, + Tensor& result) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned sorter_maybe_owned = at::borrow_from_optional_tensor(sorter_opt); + const Tensor& sorter = *sorter_maybe_owned; + searchsorted_pre_check(sorted_sequence, self, result, out_int32, right, side_opt, sorter); + resize_output(result, self.sizes()); + + // we have two inputs to set right, pre_check checks that they aren't set to opposites + bool is_right = side_opt ? *side_opt == "right" : right; + + if (self.numel() == 0) { + return result; + } + + // for non-contiguous result tensors, we write the output to a contiguous copy so we can later copy back, maintaining the original result tensor + Tensor out = result; + if (!result.is_contiguous()) { + out = result.contiguous(); + } + if (sorted_sequence.is_contiguous() && self.is_contiguous() && sorted_sequence.dtype() == self.dtype() && sorter.is_contiguous()) { + dispatch(out, self, sorted_sequence, out_int32, is_right, sorter); + } + else { + Tensor trimmed_input; + Tensor trimmed_boundaries; + Tensor trimmed_sorter; + searchsorted_maybe_trim_input_tensors(trimmed_input, trimmed_boundaries, trimmed_sorter, self, sorted_sequence, sorter); + const Tensor& final_input = trimmed_input.defined() ? trimmed_input : self; + const Tensor& final_boundaries = trimmed_boundaries.defined() ? trimmed_boundaries : sorted_sequence; + const Tensor& final_sorter = trimmed_sorter.defined() ? trimmed_sorter : sorter; + dispatch(out, final_input, final_boundaries, out_int32, is_right, final_sorter); + } + + // if result is non-contiguous, we wrote the answer to a copied version, so we copy back to the original result tensor + if (!result.is_contiguous()) { + result.copy_(out); + } + return result; +} + +Tensor& searchsorted_out_cpu( + const Tensor& sorted_sequence, + const Scalar& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter_opt, + Tensor& result) { + const Tensor& scalar_tensor = searchsorted_scalar_tensor(self, sorted_sequence.device()); + return searchsorted_out_cpu(sorted_sequence, scalar_tensor, out_int32, right, side_opt, sorter_opt, result); +} + +Tensor searchsorted_cpu( + const Tensor& sorted_sequence, + const Tensor& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter_opt) { + ScalarType scalar_type = out_int32 ? ScalarType::Int : ScalarType::Long; + c10::TensorOptions options = TensorOptions().device(self.options().device()).dtype(scalar_type); + Tensor result = at::empty({0}, options, MemoryFormat::Contiguous); + at::native::searchsorted_out_cpu(sorted_sequence, self, out_int32, right, side_opt, sorter_opt, result); + return result; +} + +Tensor searchsorted_cpu( + const Tensor& sorted_sequence, + const Scalar& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter_opt) { + const Tensor& scalar_tensor = searchsorted_scalar_tensor(self, sorted_sequence.device()); + return searchsorted_cpu(sorted_sequence, scalar_tensor, out_int32, right, side_opt, sorter_opt); +} + +Tensor& bucketize_out_cpu(const Tensor& self, const Tensor& boundaries, bool out_int32, bool right, Tensor& result) { + TORCH_CHECK(boundaries.dim() == 1, "boundaries tensor must be 1 dimension, but got dim(", boundaries.dim(), ")"); + at::native::searchsorted_out_cpu(boundaries, self, out_int32, right, std::nullopt, std::nullopt, result); + return result; +} + +Tensor bucketize_cpu(const Tensor& self, const Tensor& boundaries, bool out_int32, bool right) { + ScalarType scalar_type = out_int32 ? ScalarType::Int : ScalarType::Long; + c10::TensorOptions options = TensorOptions().device(self.options().device()).dtype(scalar_type); + Tensor result = at::empty({0}, options, MemoryFormat::Contiguous); + at::native::bucketize_out_cpu(self, boundaries, out_int32, right, result); + return result; +} + +Tensor bucketize_cpu(const Scalar& self, const Tensor& boundaries, bool out_int32, bool right) { + return bucketize_cpu(searchsorted_scalar_tensor(self, boundaries.device()), boundaries, out_int32, right); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/BucketizationUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/BucketizationUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..7656323a2fee56172db3b00b108671db885784ea --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/BucketizationUtils.h @@ -0,0 +1,173 @@ +#pragma once + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace at::native { + +// original values given by raw_*. If an original value is not contiguous, will make a contiguous copy to +// the corresponding trimmed_* value. Additionally, if the dtypes of the boundary and input tensor do not +// match, will change them to be a common super type so comparisons are done between the same types. +// For any trimmed_* tensor, if its outgoing value matches what it was incoming (typically null), then the +// corresponding raw_* version should be used since it was already contiguous of the right type. +inline void searchsorted_maybe_trim_input_tensors( + Tensor& trimmed_input, + Tensor& trimmed_boundaries, + Tensor& trimmed_sorter, + const Tensor& raw_input, + const Tensor& raw_boundaries, + const Tensor& raw_sorter) { + bool in_is_contiguous = raw_input.is_contiguous(); + bool bd_is_contiguous = raw_boundaries.is_contiguous(); + bool sort_is_contiguous = raw_sorter.is_contiguous(); + + if (!in_is_contiguous) { + TORCH_WARN_ONCE("torch.searchsorted(): input value tensor is non-contiguous, this will lower the performance due " + "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous input value " + "tensor if possible. This message will only appear once per program."); + trimmed_input = raw_input.contiguous(); + } + if (!bd_is_contiguous) { + TORCH_WARN_ONCE("torch.searchsorted(): boundary tensor is non-contiguous, this will lower the performance due " + "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous boundary " + "tensor if possible. This message will only appear once per program."); + trimmed_boundaries = raw_boundaries.contiguous(); + } + if (!sort_is_contiguous) { + TORCH_WARN_ONCE("torch.searchsorted(): sorter tensor is non-contiguous, this will lower the performance due " + "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous sorter " + "tensor if possible. This message will only appear once per program."); + trimmed_sorter = raw_sorter.contiguous(); + } + if (raw_input.dtype() != raw_boundaries.dtype()) { + at::native::ResultTypeState state = {}; + state = at::native::update_result_type_state(raw_boundaries, state); + state = at::native::update_result_type_state(raw_input, state); + ScalarType common_stype = at::native::result_type(state); + + TORCH_INTERNAL_ASSERT(common_stype != ScalarType::Undefined); + if (common_stype != raw_input.scalar_type()) { + trimmed_input = in_is_contiguous ? raw_input.to(common_stype) : trimmed_input.to(common_stype); + } + if (common_stype != raw_boundaries.scalar_type()) { + trimmed_boundaries = bd_is_contiguous ? raw_boundaries.to(common_stype) : trimmed_boundaries.to(common_stype); + } + } +} + +/* unused but needed for internal jagged tensor class */ +inline void searchsorted_maybe_trim_input_tensors( + Tensor& trimmed_input, + Tensor& trimmed_boundaries, + const Tensor& raw_input, + const Tensor& raw_boundaries) { + Tensor trimmed_sorter; + Tensor raw_sorter; + searchsorted_maybe_trim_input_tensors( + trimmed_input, + trimmed_boundaries, + trimmed_sorter, + raw_input, + raw_boundaries, + raw_sorter); +} + +inline bool searchsorted_dims_matched_before_last_dim(const Tensor& boundaries, const Tensor& input) { + if (boundaries.dim() != input.dim()) { + return false; + } + const auto& dims_bd = boundaries.sizes(); + const auto& dims_in = input.sizes(); + for (int64_t dim = 0; dim + 1 < boundaries.dim(); ++dim) { + if (dims_bd[dim] != dims_in[dim]) { + return false; + } + } + return true; +} + +inline Tensor searchsorted_scalar_tensor(const Scalar& scalar, const c10::Device& device) { + auto tensor = c10::scalar_to_tensor(scalar, device); + // This is to adopt the scalar promotion rules defined in native/TypeProperties.h + // So we have the same type promotion rules as binary operations. + tensor.unsafeGetTensorImpl()->set_wrapped_number(true); + return tensor; +} + +inline void searchsorted_pre_check( + const Tensor& boundaries, + const Tensor& input, + const Tensor& output, + const bool out_int32, + const bool right, + const std::optional side_opt, + const Tensor& sorter) { + if (side_opt) { + const std::string_view side = *side_opt; + TORCH_CHECK(side == "left" || side == "right", "torch.searchsorted(): side can only be 'left' or 'right' but ", + "got ", side); + + // assume the user has not explicitly set (right=False, side="right") + TORCH_CHECK(!right || side == "right", "torch.searchsorted(): side and right can't be set to opposites, got side " + "of ", side, " while right was True"); + } + + TORCH_CHECK(boundaries.device() == input.device(), "torch.searchsorted(): boundaries and input value tensors ", + "should have same device type, but got boundaries tensor device type ", boundaries.device(), " and input value ", + "tensor device type ", input.device()); + + if (sorter.defined()) { + TORCH_CHECK(sorter.device() == boundaries.device(), "torch.searchsorted(): sorter and boundary tensors should ", + "have same device type, but got sorter tensor device type ", sorter.device(), " and input value tensor ", + "device type ", boundaries.device()); + + TORCH_CHECK(sorter.sizes() == boundaries.sizes(), "torch.searchsorted(): boundary and sorter must have the same " + "size, but got boundary tensor ", boundaries.sizes(), "and got sorter tensor ", sorter.sizes()); + + TORCH_CHECK(sorter.scalar_type() == ScalarType::Long, "torch.searchsorted(): sorter must be a tensor of long ", + "dtype but got dtype ", sorter.scalar_type()); + + if (sorter.numel() > 0) { + auto minmax = sorter.aminmax(); + int64_t vmin = std::get<0>(minmax).item().toLong(); + int64_t vmax = std::get<1>(minmax).item().toLong(); + TORCH_CHECK(vmin >= 0 && vmax < sorter.sizes().back(), "torch.searchsorted(): sorter index out of range"); + } + } + + TORCH_CHECK(input.dim() > 0 || (input.dim() == 0 && input.numel() == 1 && boundaries.dim() == 1), + "torch.searchsorted(): input value can be a scalar only when boundaries tensor dimension is 1, but we got ", + "boundaries tensor dim(", boundaries.dim(), ") and input value's dim(", input.dim(), ") numel(", + input.numel(), ")"); + + TORCH_CHECK(boundaries.dim() != 0, "torch.searchsorted(): boundaries tensor should have positive dimension, but ", + "got 0 dimension"); + + TORCH_CHECK(boundaries.dim() == 1 || searchsorted_dims_matched_before_last_dim(boundaries, input), + "torch.searchsorted(): boundaries tensor should be 1 dimension or the first N-1 dimensions of boundaries tensor ", + "and input value tensor must match, but we got boundaries tensor ", boundaries.sizes(), " and input value tensor ", + input.sizes()); + + ScalarType output_dtype = output.scalar_type(); + TORCH_CHECK( + (output_dtype == ScalarType::Long && !out_int32) || + (output_dtype == ScalarType::Int && out_int32), + "torch.searchsorted(): output tensor's dtype is wrong, it can only be Int(int32) or Long(int64) depending on ", + "whether out_int32 flag is True, but we got output tensor's dtype ", output_dtype, + " and out_int32 flag is ", (out_int32 ? "True" : "False")); + + if (out_int32) { + TORCH_CHECK(boundaries.sizes().back() < INT_MAX, + "torch.searchsorted(): the size of boundaries' last dimension should be less than ", INT_MAX, ", but we got ", + boundaries.sizes().back()); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CPUBlas.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/CPUBlas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cdaa387b97ab88347f944093ca9cd125691ed4ca --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CPUBlas.cpp @@ -0,0 +1,1515 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#include +#include + +#include +#if !defined(__s390x__ ) && !defined(__powerpc__) +#include +#endif + +#if AT_BUILD_WITH_BLAS() +#if C10_IOS +#include +#elif !defined(_ARMPL_H) +extern "C" void dgemm_(char *transa, char *transb, int *m, int *n, int *k, double *alpha, const double *a, int *lda, const double *b, int *ldb, double *beta, double *c, int *ldc); +extern "C" void sgemm_(char *transa, char *transb, int *m, int *n, int *k, float *alpha, const float *a, int *lda, const float *b, int *ldb, float *beta, float *c, int *ldc); +extern "C" void cgemm_(char *transa, char *transb, int *m, int *n, int *k, void *alpha, const void *a, int *lda, const void *b, int *ldb, void *beta, void *c, int *ldc); +extern "C" void zgemm_(char *transa, char *transb, int *m, int *n, int *k, void *alpha, const void *a, int *lda, const void *b, int *ldb, void *beta, void *c, int *ldc); +#ifdef BLAS_HAS_SBGEMM +extern "C" void sbgemm_(char *transa, char *transb, int *m, int *n, int *k, + float *alpha, + const at::BFloat16 *a, int *lda, + const at::BFloat16 *b, int *ldb, + float *beta, + float *c, int *ldc); +#endif // BLAS_HAS_SBGEMM +#ifdef BLAS_HAS_SHGEMM +extern "C" void shgemm_(char *transa, char *transb, int *m, int *n, int *k, + float *alpha, + const at::Half *a, int *lda, + const at::Half *b, int *ldb, + float *beta, + float *c, int *ldc); +#endif // BLAS_HAS_SHGEMM +extern "C" void cswap_(int *n, const void *x, int *incx, void *y, int *incy); +extern "C" void dcopy_(int *n, const double *x, int *incx, double *y, int *incy); +extern "C" void scopy_(int *n, const float *x, int *incx, float *y, int *incy); +extern "C" void zcopy_(int *n, const void *x, int *incx, void *y, int *incy); +extern "C" void ccopy_(int *n, const void *x, int *incx, void *y, int *incy); +extern "C" void daxpy_(int *n, double *a, const double *x, int *incx, double *y, int *incy); +extern "C" void saxpy_(int *n, float *a, const float *x, int *incx, float *y, int *incy); +extern "C" void caxpy_(int *n, void *a, const void *x, int *incx, void *y, int *incy); +extern "C" void zaxpy_(int *n, void *a, const void *x, int *incx, void *y, int *incy); +#endif // C10_IOS +#endif // AT_BUILD_WITH_BLAS + +#ifdef USE_FBGEMM +#include +#endif // USE_FBGEMM + +#if AT_MKLDNN_ENABLED() +#include +// Add uKernel API versioning to be compatible with different oneDNN versions +// oneDNN 3.6.x updates the ukernel APIs of brgemm and brgemm_pack_B +// brgemm_pack_B is changed to transform and the setting of brgemm beta is changed to set_add_C +#if (IDEEP_VERSION_MAJOR == 3 && IDEEP_VERSION_MINOR == 5) +#define ONEDNN_UKERNEL_1 +#elif ((IDEEP_VERSION_MAJOR == 3 && IDEEP_VERSION_MINOR >= 6) || (IDEEP_VERSION_MAJOR > 3)) +#define ONEDNN_UKERNEL_2 +#endif +#if ((defined(ONEDNN_UKERNEL_1) || defined(ONEDNN_UKERNEL_2)) && (defined(__x86_64__) || (defined(_M_X64) && !defined(_M_ARM64EC)))) +#define ONEDNN_UKERNEL_ENABLED +#endif + +#if IDEEP_PREREQ(3, 9, 0, 0) +#define ONEDNN_FP8_UKERNEL_AVAILABLE +#endif + +#endif // AT_MKLDNN_ENABLED() + +#if defined(ONEDNN_UKERNEL_ENABLED) +#include +#include +#endif // oneDNN BRGEMM + +namespace at::native::cpublas { +namespace internal { + +void normalize_last_dims( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + int64_t *lda, int64_t *ldb, int64_t *ldc) { + if (n == 1) { + *ldc = m; + } + + if(transa != TransposeType::NoTranspose) { + if (m == 1) { + *lda = k; + } + } else if(k == 1) { + *lda = m; + } + + if(transb != TransposeType::NoTranspose) { + if (k == 1) { + *ldb = n; + } + } else if (n == 1) { + *ldb = k; + } +} +} // namespace internal + +namespace { +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunneeded-internal-declaration") +bool use_blas_gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + int64_t lda, int64_t ldb, int64_t ldc) { + const bool transa_ = transa != TransposeType::NoTranspose; + const bool transb_ = transb != TransposeType::NoTranspose; + return ( + (m <= INT_MAX) && (n <= INT_MAX) && (k <= INT_MAX) && + (lda <= INT_MAX) && (ldb <= INT_MAX) && (ldc <= INT_MAX) && + (lda >= std::max(int64_t{1}, (transa_ ? k : m))) && + (ldb >= std::max(int64_t{1}, (transb_ ? n : k))) && + (ldc >= std::max(int64_t{1}, m))); +} +C10_DIAGNOSTIC_POP() + +#ifdef USE_FBGEMM +fbgemm::matrix_op_t to_fbgemm(TransposeType trans) { + switch (trans) { + case TransposeType::Transpose: return fbgemm::matrix_op_t::Transpose; + case TransposeType::NoTranspose: return fbgemm::matrix_op_t::NoTranspose; + case TransposeType::ConjTranspose: TORCH_INTERNAL_ASSERT(false, "ConjTranspose type is not supported in fbgemm"); + } + TORCH_INTERNAL_ASSERT(false, "Invalid transpose type"); +} +#endif // USE_FBGEMM + +#if (AT_BUILD_WITH_BLAS() && C10_IOS) +CBLAS_TRANSPOSE to_apple_accelerate_transpose(TransposeType trans) { + switch (trans) { + case TransposeType::Transpose: return CblasTrans; + case TransposeType::NoTranspose: return CblasNoTrans; + case TransposeType::ConjTranspose: return CblasConjTrans; + } + TORCH_INTERNAL_ASSERT(false, "Invalid transpose type"); +} +#endif + +} // namespace (anonymous) + +DEFINE_DISPATCH(gemm_stub); +DEFINE_DISPATCH(gemm_no_downcast_stub); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const double alpha, + const double *a, int64_t lda, + const double *b, int64_t ldb, + const double beta, + double *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_BUILD_WITH_BLAS() + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + double alpha_ = alpha, beta_ = beta; + #if C10_IOS + CBLAS_TRANSPOSE transa_ = to_apple_accelerate_transpose(transa); + CBLAS_TRANSPOSE transb_ = to_apple_accelerate_transpose(transb); + cblas_dgemm(CblasColMajor, + transa_, transb_, + m_, n_, k_, + alpha_, + a, lda_, + b, ldb_, + beta_, + c, ldc_); + #else + char transa_ = to_blas(transa), transb_ = to_blas(transb); + dgemm_( + &transa_, &transb_, + &m_, &n_, &k_, + &alpha_, + a, &lda_, + b, &ldb_, + &beta_, + c, &ldc_); + #endif + return; + } +#endif + gemm_stub( + at::kCPU, at::kDouble, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +#ifndef armpl_doublecomplex_t +#define COMPLEX_DBL(a) a +#define COMPLEX_DBL_CONST(a) a +#define COMPLEX_FLOAT(a) a +#define COMPLEX_FLOAT_CONST(a) a +#else +#define COMPLEX_DBL(a) ((armpl_doublecomplex_t*)a) +#define COMPLEX_DBL_CONST(a) ((const armpl_doublecomplex_t*)a) +#define COMPLEX_FLOAT(a) ((armpl_singlecomplex_t*)a) +#define COMPLEX_FLOAT_CONST(a) ((const armpl_singlecomplex_t*)a) +#endif + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const float *a, int64_t lda, + const float *b, int64_t ldb, + const float beta, + float *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_MKLDNN_ENABLED() + if (mkldnn_reduced_f32_gemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)) { + return; + } +#endif +#if AT_BUILD_WITH_BLAS() + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + float alpha_ = alpha, beta_ = beta; + #if C10_IOS + CBLAS_TRANSPOSE transa_ = to_apple_accelerate_transpose(transa); + CBLAS_TRANSPOSE transb_ = to_apple_accelerate_transpose(transb); + cblas_sgemm(CblasColMajor, + transa_, transb_, + m_, n_, k_, + alpha_, + a, lda_, + b, ldb_, + beta_, + c, ldc_); + #else + char transa_ = to_blas(transa), transb_ = to_blas(transb); + sgemm_( + &transa_, &transb_, + &m_, &n_, &k_, + &alpha_, + a, &lda_, + b, &ldb_, + &beta_, + c, &ldc_); + #endif + return; + } +#endif + gemm_stub( + at::kCPU, at::kFloat, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const c10::complex alpha, + const c10::complex *a, int64_t lda, + const c10::complex *b, int64_t ldb, + const c10::complex beta, + c10::complex *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_BUILD_WITH_BLAS() + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + c10::complex alpha_ = alpha, beta_ = beta; + #if C10_IOS + CBLAS_TRANSPOSE transa_ = to_apple_accelerate_transpose(transa); + CBLAS_TRANSPOSE transb_ = to_apple_accelerate_transpose(transb); + cblas_zgemm(CblasColMajor, + transa_, transb_, + m_, n_, k_, + &alpha_, + a, lda_, + b, ldb_, + &beta_, + c, ldc_); + #else + char transa_ = to_blas(transa), transb_ = to_blas(transb); + zgemm_( + &transa_, &transb_, + &m_, &n_, &k_, + COMPLEX_DBL_CONST(&alpha_), + COMPLEX_DBL_CONST(a), &lda_, + COMPLEX_DBL_CONST(b), &ldb_, + COMPLEX_DBL_CONST(&beta_), + COMPLEX_DBL(c), &ldc_); + #endif + return; + } +#endif + gemm_stub( + at::kCPU, at::kComplexDouble, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const c10::complex alpha, + const c10::complex *a, int64_t lda, + const c10::complex *b, int64_t ldb, + const c10::complex beta, + c10::complex *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_BUILD_WITH_BLAS() + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + c10::complex alpha_ = alpha, beta_ = beta; + #if C10_IOS + CBLAS_TRANSPOSE transa_ = to_apple_accelerate_transpose(transa); + CBLAS_TRANSPOSE transb_ = to_apple_accelerate_transpose(transb); + cblas_cgemm(CblasColMajor, + transa_, transb_, + m_, n_, k_, + &alpha_, + a, lda_, + b, ldb_, + &beta_, + c, ldc_); + #else + char transa_ = to_blas(transa), transb_ = to_blas(transb); + cgemm_( + &transa_, &transb_, + &m_, &n_, &k_, + COMPLEX_FLOAT_CONST(&alpha_), + COMPLEX_FLOAT_CONST(a), &lda_, + COMPLEX_FLOAT_CONST(b), &ldb_, + COMPLEX_FLOAT_CONST(&beta_), + COMPLEX_FLOAT(c), &ldc_); + #endif + return; + } +#endif + gemm_stub( + at::kCPU, at::kComplexFloat, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const at::BFloat16 *a, int64_t lda, + const at::BFloat16 *b, int64_t ldb, + const float beta, + at::BFloat16 *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_MKLDNN_ENABLED() +#ifdef __aarch64__ + // MKLDNN also supports ARM for bf16, and the bypass is only + // currently intended for x86/x86_64. + const bool use_bf16_gemv_trans = false; +#elif defined(__powerpc__) + const bool use_bf16_gemv_trans = false; +#else + const bool bf16_gemv_trans_would_be_faster = cpuinfo_initialize() && + !cpuinfo_has_x86_avx512bf16(); + const bool use_bf16_gemv_trans = bf16_gemv_trans_would_be_faster && + transa == TransposeType::Transpose && + transb == TransposeType::NoTranspose && n == 1 && alpha == 1.0; +#endif + if (!use_bf16_gemv_trans && mkldnn_bf16_gemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)) { + return; + } +#endif +#if AT_BUILD_WITH_BLAS() && defined(BLAS_HAS_SBGEMM) + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + char transa_ = to_blas(transa), transb_ = to_blas(transb); + float alpha_ = alpha, beta_ = beta; + int c_size = n_ * m_; + // C matrix in OpenBLAS sbgemm are of type "float" so we have to convert, copy and copy back. + std::vector float_v(c_size, 0.0f); + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + float_v[j * m_ + i] = c10::convert(c[j * ldc_ + i]); + } + } + sbgemm_(&transa_, &transb_, + &m_, &n_, &k_, + &alpha_, + a, &lda_, + b, &ldb_, + &beta_, + float_v.data(), &m_); + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + c[j * ldc_ + i] = c10::convert(float_v[j * m_ + i]); + } + } + return; + } +#endif + gemm_stub( + at::kCPU, at::kBFloat16, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const at::Half *a, int64_t lda, + const at::Half *b, int64_t ldb, + const float beta, + at::Half *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_MKLDNN_ENABLED() + // Per https://github.com/pytorch/pytorch/pull/137918#discussion_r1825460179 , + // we should not bother checking for !cpuinfo_has_x86_avx512fp16() here, + // because "onednn (mkldnn) won't use avx512fp16 to compute gemms by default + // because the avx512fp16 fma would incur accuracy loss". +#if defined(__powerpc__) + const bool fp16_gemv_trans_would_be_faster = false; +#else + const bool fp16_gemv_trans_would_be_faster = cpuinfo_initialize() && + cpuinfo_has_x86_f16c(); +#endif + const bool use_fp16_gemv_trans = fp16_gemv_trans_would_be_faster && + transa == TransposeType::Transpose && + transb == TransposeType::NoTranspose && n == 1 && alpha == 1.0; + if (!use_fp16_gemv_trans && + mkldnn_fp16_gemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)) { + return; + } +#endif +#if AT_BUILD_WITH_BLAS() && defined(BLAS_HAS_SHGEMM) + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + char transa_ = to_blas(transa), transb_ = to_blas(transb); + float alpha_ = alpha, beta_ = beta; + int c_size = n_ * m_; + // C matrix in OpenBLAS shgemm are of type "float" so we have to convert, copy and copy back. + std::vector float_v(c_size, 0.0f); + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + float_v[j * m_ + i] = c10::convert(c[j * ldc_ + i]); + } + } + shgemm_(&transa_, &transb_, + &m_, &n_, &k_, + &alpha_, + a, &lda_, + b, &ldb_, + &beta_, + float_v.data(), &m_); + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + c[j * ldc_ + i] = c10::convert(float_v[j * m_ + i]); + } + } + return; + } +#endif + gemm_stub( + at::kCPU, at::kHalf, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const at::BFloat16 *a, int64_t lda, + const at::BFloat16 *b, int64_t ldb, + const float beta, + float *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_BUILD_WITH_BLAS() && defined(BLAS_HAS_SBGEMM) + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + char transa_ = to_blas(transa), transb_ = to_blas(transb); + float alpha_ = alpha, beta_ = beta; + sbgemm_(&transa_, &transb_, + &m_, &n_, &k_, + &alpha_, + a, &lda_, + b, &ldb_, + &beta_, + c, &ldc_); + return; + } +#endif +#if AT_MKLDNN_ACL_ENABLED() +// add heuristic based on shape to dispatch to sbgemm_ vs MKLDNN + if (mkldnn_bf16f32_gemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)) { + return; + } +#endif //AT_MKLDNN_ACL_ENABLED + +#ifdef MKL_HAS_SBGEMM + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + mkl_gemm_bf16bf16f32(transa, transb, m_, n_, k_, alpha, a, lda_, b, ldb_, beta, c, ldc_); + return; + } +#endif + gemm_no_downcast_stub( + at::kCPU, at::kBFloat16, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const at::Half *a, int64_t lda, + const at::Half *b, int64_t ldb, + const float beta, + float *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#if AT_BUILD_WITH_BLAS() && defined(BLAS_HAS_SHGEMM) + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + char transa_ = to_blas(transa), transb_ = to_blas(transb); + float alpha_ = alpha, beta_ = beta; + shgemm_(&transa_, &transb_, + &m_, &n_, &k_, + &alpha_, + a, &lda_, + b, &ldb_, + &beta_, + c, &ldc_); + return; + } +#endif +#ifdef MKL_HAS_SHGEMM + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + int m_ = m, n_ = n, k_ = k, lda_ = lda, ldb_ = ldb, ldc_ = ldc; + mkl_gemm_f16f16f32(transa, transb, m_, n_, k_, alpha, a, lda_, b, ldb_, beta, c, ldc_); + return; + } +#endif + gemm_no_downcast_stub( + at::kCPU, at::kHalf, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const int64_t alpha, + const int64_t *a, int64_t lda, + const int64_t *b, int64_t ldb, + const int64_t beta, + int64_t *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); +#ifdef USE_FBGEMM + if (alpha == 1 && (beta == 0 || beta == 1)) { + // In FBGEMM, we assume row-major ordering; However, here we assume the + // column-major ordering following the FORTRAN tradition in BLAS interface + // in this function: we can configure the layout (row/column-major ordering) + // of A and B by changing transa_ and transb_, but we cannot change the + // layout of C with this FORTRAN-style BLAS interface. + // + // The workaround is that we compute + // C^T (n x m) = B^T (n x k) * A^T (k x m) instead. + // + // In this way we view C^T as the row-major ordering when passing to FBGEMM. + fbgemm::cblas_gemm_i64_i64acc( + to_fbgemm(transb), + to_fbgemm(transa), + n, + m, + k, + b, + ldb, + a, + lda, + beta == 1, + c, + ldc); + return; + } +#endif + + gemm_stub( + kCPU, kLong, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +template +static void gemm_batched_mkl_impl( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t **a, int64_t lda, + const scalar_t **b, int64_t ldb, + scalar_t beta, + scalar_t **c, int64_t ldc) { + for (int64_t i = 0; i < batch_size;) { + int sub_batch = std::min(batch_size - i, int64_t{INT_MAX}); + mkl_gemm_batched(transa, transb, sub_batch, m, n, k, alpha, + &a[i], lda, &b[i], ldb, beta, &c[i], ldc); + i += sub_batch; + } +} + +template +using is_blas_library_type = std::integral_constant || + std::is_same_v || + std::is_same_v> || + std::is_same_v>>; + +template +static void gemm_batched_generic( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t **a, int64_t lda, + const scalar_t **b, int64_t ldb, + scalar_t beta, + scalar_t **c, int64_t ldc) { + for (const auto batch : c10::irange(batch_size)) { + gemm(transa, transb, m, n, k, alpha, a[batch], lda, b[batch], ldb, beta, c[batch], ldc); + } +} + +template +static void gemm_batched( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t **a, int64_t lda, + const scalar_t **b, int64_t ldb, + scalar_t beta, + scalar_t **c, int64_t ldc) { + if (batch_size == 1) { + return gemm(transa, transb, m, n, k, alpha, a[0], lda, b[0], ldb, beta, c[0], ldc); + } + + if constexpr (AT_MKL_ENABLED() && is_blas_library_type::value) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + gemm_batched_mkl_impl( + transa, transb, batch_size, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + gemm_batched_generic( + transa, transb, batch_size, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } + } else { + gemm_batched_generic( + transa, transb, batch_size, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } +} + +template +static void gemm_batched_with_stride_generic( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t *a, int64_t lda, int64_t batch_stride_a, + const scalar_t *b, int64_t ldb, int64_t batch_stride_b, + scalar_t beta, + scalar_t *c, int64_t ldc, int64_t batch_stride_c) { + for (const auto batch : c10::irange(batch_size)) { + const auto a_batch = a + batch_stride_a * batch; + const auto b_batch = b + batch_stride_b * batch; + const auto c_batch = c + batch_stride_c * batch; + gemm(transa, transb, m, n, k, alpha, a_batch, lda, b_batch, ldb, beta, c_batch, ldc); + } +} + +template +void gemm_batched_with_stride( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t *a, int64_t lda, int64_t batch_stride_a, + const scalar_t *b, int64_t ldb, int64_t batch_stride_b, + scalar_t beta, + scalar_t *c, int64_t ldc, int64_t batch_stride_c) { + if (batch_size == 1) { + return gemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } + + if constexpr (AT_MKL_ENABLED() && is_blas_library_type::value) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); + if (use_blas_gemm(transa, transb, m, n, k, lda, ldb, ldc)) { + c10::SmallBuffer a_ptrs(batch_size); + c10::SmallBuffer b_ptrs(batch_size); + c10::SmallBuffer c_ptrs(batch_size); + + for (const auto batch : c10::irange(batch_size)) { + a_ptrs[batch] = a + batch_stride_a * batch; + b_ptrs[batch] = b + batch_stride_b * batch; + c_ptrs[batch] = c + batch_stride_c * batch; + } + gemm_batched_mkl_impl( + transa, transb, batch_size, m, n, k, alpha, a_ptrs.data(), lda, + b_ptrs.data(), ldb, beta, c_ptrs.data(), ldc); + } else { + gemm_batched_with_stride_generic( + transa, transb, batch_size, m, n, k, alpha, a, lda, batch_stride_a, + b, ldb, batch_stride_b, beta, c, ldc, batch_stride_c); + } + } else { + gemm_batched_with_stride_generic(transa, transb, batch_size, m, n, k, alpha, + a, lda, batch_stride_a, b, ldb, batch_stride_b, + beta, c, ldc, batch_stride_c); + } +} + +#define INSTANTIATE_BATCHED_GEMM(scalar_t, DType) \ + template void gemm_batched( \ + TransposeType transa, TransposeType transb, \ + int64_t batch_size, int64_t m, int64_t n, int64_t k, \ + scalar_t alpha, \ + const scalar_t **a, int64_t lda, \ + const scalar_t **b, int64_t ldb, \ + scalar_t beta, \ + scalar_t **c, int64_t ldc); \ + template void gemm_batched_with_stride( \ + TransposeType transa, TransposeType transb, \ + int64_t batch_size, int64_t m, int64_t n, int64_t k, \ + scalar_t alpha, \ + const scalar_t *a, int64_t lda, int64_t batch_stride_a, \ + const scalar_t *b, int64_t ldb, int64_t batch_stride_b, \ + scalar_t beta, \ + scalar_t *c, int64_t ldc, int64_t batch_stride_c); + +AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_EXCEPT_COMPLEX_HALF_F8NZ(INSTANTIATE_BATCHED_GEMM) + +DEFINE_DISPATCH(axpy_stub); + +void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) + { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_daxpy(i_n, a, x, i_incx, y, i_incy); + #else + daxpy_(&i_n, &a, x, &i_incx, y, &i_incy); + #endif + return; + } + #endif + axpy_stub( + kCPU, at::kDouble, + n, a, x, incx, y, incy); +} + +void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) + { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_saxpy(i_n, a, x, i_incx, y, i_incy); + #else + saxpy_(&i_n, &a, x, &i_incx, y, &i_incy); + #endif + return; + } + #endif + axpy_stub( + kCPU, at::kFloat, + n, a, x, incx, y, incy); +} + +void axpy(int64_t n, c10::complex a, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) + { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_zaxpy(i_n, &a, x, i_incx, y, i_incy); + #else + zaxpy_(&i_n, COMPLEX_DBL(&a), COMPLEX_DBL_CONST(x), &i_incx, COMPLEX_DBL(y), &i_incy); + #endif + return; + } + #endif + axpy_stub( + kCPU, at::kComplexDouble, + n, a, x, incx, y, incy); +} + +void axpy(int64_t n, c10::complex a, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) + { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_caxpy(i_n, &a, x, i_incx, y, i_incy); + #else + caxpy_(&i_n, COMPLEX_FLOAT(&a), COMPLEX_FLOAT_CONST(x), &i_incx, COMPLEX_FLOAT(y), &i_incy); + #endif + return; + } + #endif + axpy_stub( + kCPU, at::kComplexFloat, + n, a, x, incx, y, incy); +} + +DEFINE_DISPATCH(copy_stub); + +void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_dcopy(i_n, x, i_incx, y, i_incy); + #else + dcopy_(&i_n, x, &i_incx, y, &i_incy); + #endif + return; + } + #endif + copy_stub( + kCPU, at::kDouble, + n, x, incx, y, incy); +} + +void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_scopy(i_n, x, i_incx, y, i_incy); + #else + scopy_(&i_n, x, &i_incx, y, &i_incy); + #endif + return; + } + #endif + copy_stub( + kCPU, at::kFloat, + n, x, incx, y, incy); +} + +void copy(int64_t n, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_zcopy(i_n, x, i_incx, y, i_incy); + #else + zcopy_(&i_n, COMPLEX_DBL_CONST(x), &i_incx, COMPLEX_DBL(y), &i_incy); + #endif + return; + } + #endif + copy_stub( + kCPU, at::kComplexDouble, + n, x, incx, y, incy); +} + +void copy(int64_t n, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy){ + if(n == 1) + { + incx = 1; + incy = 1; + } + #if AT_BUILD_WITH_BLAS() + if( (n <= INT_MAX) && (incx <= INT_MAX) && (incy <= INT_MAX) ) { + int i_n = static_cast(n); + int i_incx = static_cast(incx); + int i_incy = static_cast(incy); + #if C10_IOS + cblas_ccopy(i_n, &x, i_incx, y, i_incy); + #else + ccopy_(&i_n, COMPLEX_FLOAT(x), &i_incx, COMPLEX_FLOAT(y), &i_incy); + #endif + return; + } + #endif + copy_stub( + kCPU, at::kComplexFloat, + n, x, incx, y, incy); +} + +// oneDNN BRGEMM +#if defined(ONEDNN_UKERNEL_ENABLED) +struct BrgemmKey { + int64_t M; + int64_t N; + int64_t K; + int64_t batch_size; + int64_t lda; + int64_t ldb; + int64_t ldc; + ScalarType dt_a; + ScalarType dt_b; + ScalarType dt_c; + bool add_C; + + BrgemmKey( + int64_t M, + int64_t N, + int64_t K, + int64_t batch_size, + int64_t lda, + int64_t ldb, + int64_t ldc, + ScalarType dt_a, + ScalarType dt_b, + ScalarType dt_c, + bool add_C) + : M(M), + N(N), + K(K), + batch_size(batch_size), + lda(lda), + ldb(ldb), + ldc(ldc), + dt_a(dt_a), + dt_b(dt_b), + dt_c(dt_c), + add_C(add_C) {} + bool operator==(const BrgemmKey& other) const { + return M == other.M && N == other.N && K == other.K && + batch_size == other.batch_size && lda == other.lda && + ldb == other.ldb && ldc == other.ldc && dt_a == other.dt_a && + dt_b == other.dt_b && dt_c == other.dt_c && add_C == other.add_C; + } +}; + +struct PackKey { + int64_t K; + int64_t N; + int64_t ld_in; + int64_t ld_out; + ScalarType dt_in; + ScalarType dt_out; + PackKey( + int64_t K, + int64_t N, + int64_t ld_in, + int64_t ld_out, + ScalarType dt_in, + ScalarType dt_out) + : K(K), + N(N), + ld_in(ld_in), + ld_out(ld_out), + dt_in(dt_in), + dt_out(dt_out) {} + bool operator==(const PackKey& other) const { + return N == other.N && K == other.K && ld_in == other.ld_in && + ld_out == other.ld_out && dt_in == other.dt_in && + dt_out == other.dt_out; + } +}; + +static inline dnnl::memory::data_type get_dnnl_dtype(ScalarType dtype) { + using at::ScalarType; + using data_type = dnnl::memory::data_type; + switch (dtype) { + case ScalarType::Float: return data_type::f32; + case ScalarType::BFloat16: return data_type::bf16; + case ScalarType::Half: return data_type::f16; + case ScalarType::Int: return data_type::s32; + case ScalarType::Byte: return data_type::u8; + case ScalarType::Char: return data_type::s8; + case ScalarType::Float8_e4m3fn: return data_type::f8_e4m3; + case ScalarType::Float8_e5m2: return data_type::f8_e5m2; + default: + TORCH_CHECK(false, "Unsupported dtype for oneDNN"); + } +} + +template +struct UnsafeUkernelKeyHasher { + std::size_t operator()(const key_t& key) const; +}; + +template<> +std::size_t UnsafeUkernelKeyHasher::operator()(const BrgemmKey& key) const { + // Use M, N, K add_C, and ldc to compute hash to reduce the overhead as + // batch size and data types are unlikely to change within the same kernel and + // lda/ldb are likely to be related to M, K, N or use fixed values. + std::size_t h = std::hash()(key.M); + h = std::hash()(key.N) ^ (h << 1); + h = std::hash()(key.K) ^ (h << 1); + h = std::hash()(key.add_C) ^ (h << 1); + h = std::hash()(key.ldc) ^ (h << 1); + return h; +} + +template<> +std::size_t UnsafeUkernelKeyHasher::operator()(const PackKey& key) const { + // Use K and N to compute hash to reduce the overhead as + // data types are unlikely to change and + // ld_in/ld_out is likely to be related to K, N or use fixed values + std::size_t h = std::hash()(key.K); + h = std::hash()(key.N) ^ (h << 1); + return h; +} + +template +struct KernelCache { + using kstore_t = std::unordered_map, UnsafeUkernelKeyHasher>; + static std::shared_ptr&& fetch_or_create( + const key_t& key, + const std::function()>& callback) { + auto&& search = get_store().find(key); + if (search != get_store().end()) { + return std::move(search->second); + } else { + get_store().insert({key, callback()}); + return std::move(get_store()[key]); + } + } + + static kstore_t& get_store() { + static thread_local kstore_t cache_kernels; + return cache_kernels; + } +}; + +// Helper struct for convenient brgemm configuration +struct GemmHelper { + GemmHelper( + int64_t M, + int64_t N, + int64_t K, + int64_t bs, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + ScalarType dt_a, + ScalarType dt_b, + ScalarType dt_c, + const bool add_C) { + // Create brgemm +#if defined(ONEDNN_UKERNEL_1) + brg = dnnl::ukernel::brgemm( + M, + N, + K, + bs, + ld_a, + ld_b, + ld_c, + get_dnnl_dtype(dt_a), + get_dnnl_dtype(dt_b), + get_dnnl_dtype(dt_c), + 1, + add_C ? 1 : 0); +#elif defined(ONEDNN_UKERNEL_2) + brg = dnnl::ukernel::brgemm( + M, + N, + K, + bs, + ld_a, + ld_b, + ld_c, + get_dnnl_dtype(dt_a), + get_dnnl_dtype(dt_b), + get_dnnl_dtype(dt_c)); + brg.set_add_C(add_C); + brg.finalize(); +#endif + // Create a scratchpad buffer for the brgemm execution + scratchpad = std::vector(brg.get_scratchpad_size()); + // Prepare default vector of pairs of tensors A and B offsets for each batch. + A_B_offsets.resize(1); + A_B_offsets[0] = std::make_pair(0, 0); + } + dnnl::ukernel::brgemm brg; + std::vector scratchpad; + std::vector> A_B_offsets; +}; + +struct Brgemm : public KernelCache { + // Fetch/create GemmHelper object and execute brgemm with batch size = 1 + template + static void call( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const scalar_t_a* A, + const scalar_t_b* B, + scalar_t_c* C) { + auto&& key = BrgemmKey( + M, + N, + K, + 1, + ld_a, + ld_b, + ld_c, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + add_C); + // Fetch/create GemmHelper object + auto&& value = fetch_or_create(key, [&]() { + auto&& v = std::make_shared( + M, + N, + K, + 1, + ld_a, + ld_b, + ld_c, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + add_C); + (*v).brg.generate(); + return std::move(v); + }); + if (get_current() != value) { +#if defined(ONEDNN_UKERNEL_1) + dnnl::ukernel::brgemm::release_hw_context(); +#endif + ((*value).brg).set_hw_context(); + get_current() = value; + } + ((*value).brg) + .execute(A, B, (*value).A_B_offsets, C, (*value).scratchpad.data()); + } + + static std::shared_ptr& get_current() { + static thread_local std::shared_ptr current; + return current; + } + + static bool device_check(ScalarType dtype) { + if (!at::globalContext().userEnabledMkldnn()) { + return false; + } + static bool fp16_support = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_fp16; + static bool fp32_support = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx2; + static bool bf16_support = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core; + static bool u8_support = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_amx; + static bool s8_support = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_vnni; +#ifdef ONEDNN_FP8_UKERNEL_AVAILABLE + static bool f8_support = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_amx; +#else + static bool f8_support = false; +#endif + switch (dtype) { + case ScalarType::Half: return fp16_support; + case ScalarType::Float: return fp32_support; + case ScalarType::BFloat16: return bf16_support; + case ScalarType::Byte: return u8_support; + case ScalarType::Char: return s8_support; + case ScalarType::Float8_e4m3fn: return f8_support; + case ScalarType::Float8_e5m2: return f8_support; + default: return false; + } + } +}; + +#if defined(ONEDNN_UKERNEL_1) +using pack_t = dnnl::ukernel::brgemm_pack_B; +#elif defined(ONEDNN_UKERNEL_2) +using pack_t = dnnl::ukernel::transform; +#endif +struct Pack : public KernelCache { + static void call( + int64_t K, + int64_t N, + int64_t ld_in, + int64_t ld_out, + ScalarType dt_in, + ScalarType dt_out, + const void* in, + void* out) { + auto&& key = PackKey(K, N, ld_in, ld_out, dt_in, dt_out); + auto&& pack = fetch_or_create(key, [&]() { + auto&& p = std::make_shared( +#if defined(ONEDNN_UKERNEL_1) + K, N, ld_in, ld_out, get_dnnl_dtype(dt_in), get_dnnl_dtype(dt_out)); +#elif defined(ONEDNN_UKERNEL_2) + K, N, dnnl::ukernel::pack_type::no_trans, ld_in, ld_out, get_dnnl_dtype(dt_in), get_dnnl_dtype(dt_out)); +#endif + if (could_pack(dt_in)) { + (*p).generate(); + } + return std::move(p); + }); + if (could_pack(dt_in)) { + (*pack).execute(in, out); + } else { + TORCH_CHECK(false, "No need to pack"); + } + } + + static bool could_pack(ScalarType dtype) { + if (!at::globalContext().userEnabledMkldnn()) { + return false; + } + static bool fp16_pack = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_amx_fp16; + static bool bf16_pack = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_amx; + static bool bit8_pack = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_amx; +#ifdef ONEDNN_FP8_UKERNEL_AVAILABLE + static bool fp8_pack = dnnl::get_effective_cpu_isa() >= dnnl::cpu_isa::avx512_core_amx; +#else + static bool fp8_pack = false; +#endif + switch (dtype) { + case ScalarType::Half: return fp16_pack; + case ScalarType::BFloat16: return bf16_pack; + case ScalarType::Byte: return bit8_pack; + case ScalarType::Char: return bit8_pack; + case ScalarType::Float8_e4m3fn: return fp8_pack; + case ScalarType::Float8_e5m2: return fp8_pack; + default: return false; + } + } +}; +#endif + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const float* A, + const float* B, + float* C, + bool is_vnni) { + + TORCH_CHECK(!is_vnni, + "Float Brgemm does not support vnni layout."); + +#if defined(ONEDNN_UKERNEL_ENABLED) + if (Brgemm::device_check(ScalarType::Float)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // fallback path + auto beta = add_C ? 1 : 0; + gemm( + at::native::TransposeType::NoTranspose, + at::native::TransposeType::NoTranspose, + N, M, K, 1, + B, ld_b, A, ld_a, + beta, C, ld_c); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::BFloat16* A, + const at::BFloat16* B, + float* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) + if (is_vnni && Brgemm::device_check(ScalarType::BFloat16)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // fallback path + TORCH_CHECK(!is_vnni, + "BFloat16 Brgemm VNNI format is only supported on X64 when oneDNN ukernel is enabled and `amx` is supported"); + auto beta = add_C ? 1 : 0; + gemm( + at::native::TransposeType::NoTranspose, + at::native::TransposeType::NoTranspose, + N, M, K, 1, + B, ld_b, A, ld_a, + beta, C, ld_c); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::Half* A, + const at::Half* B, + float* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) + if (is_vnni && Brgemm::device_check(ScalarType::Half)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // fallback path + TORCH_CHECK(!is_vnni, + "Half Brgemm VNNI format is only supported on X64 when oneDNN ukernel is enabled and `amx_fp16` is supported"); + auto beta = add_C ? 1 : 0; + gemm( + at::native::TransposeType::NoTranspose, + at::native::TransposeType::NoTranspose, + N, M, K, 1, + B, ld_b, A, ld_a, + beta, C, ld_c); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const unsigned char* A, + const unsigned char* B, + int32_t* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) + if (is_vnni && Brgemm::device_check(ScalarType::Byte)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // raise an error if the path is not supported + TORCH_CHECK(false, + "U8 Brgemm is only supported on X64 when oneDNN ukernel is enabled and `amx` is supported"); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const unsigned char* A, + const signed char* B, + int32_t* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) + if (is_vnni && Brgemm::device_check(ScalarType::Char)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // raise an error if the path is not supported + TORCH_CHECK(false, + "I8 Brgemm is only supported on X64 when oneDNN ukernel is enabled and `amx` is supported"); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const signed char* A, + const signed char* B, + int32_t* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) + if (is_vnni && Brgemm::device_check(ScalarType::Char)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // raise an error if the path is not supported + TORCH_CHECK(false, + "I8 Brgemm is only supported on X64 when oneDNN ukernel is enabled and `amx` is supported"); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::Float8_e4m3fn* A, + const at::Float8_e4m3fn* B, + float* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) && defined(ONEDNN_FP8_UKERNEL_AVAILABLE) + if (is_vnni && Brgemm::device_check(ScalarType::Float8_e4m3fn)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // raise an error if the path is not supported + TORCH_CHECK(false, + "F8 Brgemm is only supported on X64 when oneDNN ukernel is enabled and `amx` is supported"); +} + +void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::Float8_e5m2* A, + const at::Float8_e5m2* B, + float* C, + bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) && defined(ONEDNN_FP8_UKERNEL_AVAILABLE) + if (is_vnni && Brgemm::device_check(ScalarType::Float8_e5m2)) { + Brgemm::call( + M, N, K, ld_a, ld_b, ld_c, add_C, A, B, C); + return; + } +#endif + // raise an error if the path is not supported + TORCH_CHECK(false, + "F8 Brgemm is only supported on X64 when oneDNN ukernel is enabled and `amx` is supported"); +} + +void brgemm_release(bool is_vnni) { +#if defined(ONEDNN_UKERNEL_ENABLED) + if (is_vnni) { + dnnl::ukernel::brgemm::release_hw_context(); + Brgemm::get_current() = nullptr; + } +#endif +} + +void pack( + int64_t K, + int64_t N, + int64_t ld_in, + int64_t ld_out, + ScalarType dt_in, + ScalarType dt_out, + const void* in, + void* out) { +#if defined(ONEDNN_UKERNEL_ENABLED) + Pack::call(K, N, ld_in, ld_out, dt_in, dt_out, in, out); +#else + TORCH_CHECK(false, "pack is only supported on X64 with oneDNN ukernel enabled"); +#endif +} + +bool could_pack(ScalarType dt_in) { +#if defined(ONEDNN_UKERNEL_ENABLED) + return Pack::could_pack(dt_in); +#else + return false; +#endif +} + +} // namespace at::native::cpublas diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CPUBlas.h b/western_ai/usa/pytorch/aten/src/ATen/native/CPUBlas.h new file mode 100644 index 0000000000000000000000000000000000000000..f0c38a8f477b6255a9dc1ca0a1393daceab9b4c8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CPUBlas.h @@ -0,0 +1,344 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + + +namespace at::native::cpublas { + +namespace internal { +void normalize_last_dims( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + int64_t *lda, int64_t *ldb, int64_t *ldc); +} // namespace internal + +using gemm_fn = void(*)( + at::ScalarType type, + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const Scalar& alpha, + const void *a, int64_t lda, + const void *b, int64_t ldb, + const Scalar& beta, + void *c, int64_t ldc); + +DECLARE_DISPATCH(gemm_fn, gemm_stub) + +using gemm_no_downcast_fn = void(*)( + at::ScalarType type, + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const Scalar& alpha, + const void *a, int64_t lda, + const void *b, int64_t ldb, + const Scalar& beta, + void *c, int64_t ldc); + +DECLARE_DISPATCH(gemm_no_downcast_fn, gemm_no_downcast_stub) + +template +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + at::opmath_type alpha, + const scalar_t *a, int64_t lda, + const scalar_t *b, int64_t ldb, + at::opmath_type beta, + scalar_t *c, int64_t ldc) { + internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc); + gemm_stub( + kCPU, c10::CppTypeToScalarType::value, + transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); +} + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + double alpha, + const double *a, int64_t lda, + const double *b, int64_t ldb, + double beta, + double *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + float alpha, + const float *a, int64_t lda, + const float *b, int64_t ldb, + float beta, + float *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + float alpha, + const at::BFloat16 *a, int64_t lda, + const at::BFloat16 *b, int64_t ldb, + float beta, + at::BFloat16 *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const at::BFloat16 *a, int64_t lda, + const at::BFloat16 *b, int64_t ldb, + const float beta, + float *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + float alpha, + const at::Half *a, int64_t lda, + const at::Half *b, int64_t ldb, + float beta, + at::Half *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const float alpha, + const at::Half *a, int64_t lda, + const at::Half *b, int64_t ldb, + const float beta, + float *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + c10::complex alpha, + const c10::complex *a, int64_t lda, + const c10::complex *b, int64_t ldb, + c10::complex beta, + c10::complex *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + c10::complex alpha, + const c10::complex *a, int64_t lda, + const c10::complex *b, int64_t ldb, + c10::complex beta, + c10::complex *c, int64_t ldc); + +void gemm( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + int64_t alpha, + const int64_t *a, int64_t lda, + const int64_t *b, int64_t ldb, + int64_t beta, + int64_t *c, int64_t ldc); + +template +void gemm_batched( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t * const *a, int64_t lda, + const scalar_t * const *b, int64_t ldb, + const scalar_t beta, + scalar_t * const *c, int64_t ldc); + +template +void gemm_batched_with_stride( + TransposeType transa, TransposeType transb, + int64_t batch_size, int64_t m, int64_t n, int64_t k, + scalar_t alpha, + const scalar_t *a, int64_t lda, int64_t batch_stride_a, + const scalar_t *b, int64_t ldb, int64_t batch_stride_b, + scalar_t beta, + scalar_t *c, int64_t ldc, int64_t batch_stride_c); + +using axpy_fn = void(*)(at::ScalarType type, int64_t n, const Scalar& a, const void *x, int64_t incx, void *y, int64_t incy); + +DECLARE_DISPATCH(axpy_fn, axpy_stub) + +template +void axpy(int64_t n, scalar_t a, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy){ + if(n == 1) + { + incx = 1; + incy = 1; + } + axpy_stub( + kCPU, c10::CppTypeToScalarType::value, + n, a, x, incx, y, incy); +} + +void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy); +void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy); +void axpy(int64_t n, c10::complex a, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy); +void axpy(int64_t n, c10::complex a, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy); + +using copy_fn = void(*)(at::ScalarType type, int64_t n, const void *x, int64_t incx, void *y, int64_t incy); + +DECLARE_DISPATCH(copy_fn, copy_stub) + +template +void copy(int64_t n, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy) { + if(n == 1) + { + incx = 1; + incy = 1; + } + copy_stub( + kCPU, c10::CppTypeToScalarType::value, + n, x, incx, y, incy); +} + +void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy); +void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy); +void copy(int64_t n, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy); +void copy(int64_t n, const c10::complex *x, int64_t incx, c10::complex *y, int64_t incy); + +// Batch-reduce GEMM +// Operates by the following formula: +// C = SUM(A[i] x B[i]) + C if add_C is true, i = 0 to batch size +// A Base pointer to a tensor A. +// B Base pointer to a tensor B. +// C Pointer to a tensor C (accumulation buffer). +// Note only batch size 1 is used currently + +// Define macros for available brgemm APIs +// so that callers can determine which APIs are available +#define CPUBLAS_BRGEMM_F16F16F32 // half * half -> float +#define CPUBLAS_BRGEMM_BF16BF16F32 // bfloat16 * bfloat16 -> float +#define CPUBLAS_BRGEMM_F32F32F32 // float * float -> float +#define CPUBLAS_BRGEMM_U8U8I32 // unsigned char * unsigned char -> int32 +#define CPUBLAS_BRGEMM_U8I8I32 // unsigned char * signed char -> int32 +#define CPUBLAS_BRGEMM_I8I8I32 // signed char * signed char -> int32 +#define CPUBLAS_BRGEMM_F8F8F32 // float8 * float8 -> float (e4m3 & e5m2) + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::Half* A, + const at::Half* B, + float* C, + bool is_vnni = true); + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::BFloat16* A, + const at::BFloat16* B, + float* C, + bool is_vnni = true); + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const float* A, + const float* B, + float* C, + bool is_vnni = false); + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const unsigned char* A, + const unsigned char* B, + int32_t* C, + bool is_vnni = true); + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const unsigned char* A, + const signed char* B, + int32_t* C, + bool is_vnni = true); + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const signed char* A, + const signed char* B, + int32_t* C, + bool is_vnni = true); + +#ifdef CPUBLAS_BRGEMM_F8F8F32 +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::Float8_e4m3fn* A, + const at::Float8_e4m3fn* B, + float* C, + bool is_vnni = true); + +TORCH_API void brgemm( + int64_t M, + int64_t N, + int64_t K, + int64_t ld_a, + int64_t ld_b, + int64_t ld_c, + const bool add_C, + const at::Float8_e5m2* A, + const at::Float8_e5m2* B, + float* C, + bool is_vnni = true); +#endif + +// Release brgemm hardware context +TORCH_API void brgemm_release(bool is_vnni = true); + +// Pack B matrix to get better performance if needed +TORCH_API void pack( + int64_t K, + int64_t N, + int64_t ld_in, + int64_t ld_out, + ScalarType dt_in, + ScalarType dt_out, + const void* in, + void* out); + +// Whether pack is supported in the platform. +TORCH_API bool could_pack(ScalarType dt_in); + +} // namespace at::native::cpublas diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CPUFallback.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/CPUFallback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd14e58e6fffcdec08ee0438f916209f89d394d4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CPUFallback.cpp @@ -0,0 +1,343 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include + +#include +#include + + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + + +namespace at::native { + +// convenience helper for converting tensors to cpu + +template || std::is_same_v>, int> = 1> +static std::vector to_cpu(const std::vector& tensors) { + // We can't just call at::to_cpu() on the entire list of Tensors + // Because it will break on undefined tensors. Separate out undefined tensors first. + const int num = tensors.size(); + std::vector cpu_tensors(num); + std::vector valid_tensors; + std::vector to_translate(num); + for (const auto i : c10::irange(num)) { + // Explicitly handling undefined tensors here instead of letting `at::_to_cpu` handle it. + // Otherwise, we'd need to require all backends with their own implementation of _to_cpu + // to properly handle undefined tensors. + if constexpr(std::is_same_v>) { + if (tensors[i].has_value() && tensors[i].value().defined()) { + to_translate[i] = true; + valid_tensors.push_back(tensors[i].value()); + } else { + cpu_tensors[i] = tensors[i]; + } + } else { + if (tensors[i].defined()) { + to_translate[i] = true; + valid_tensors.push_back(tensors[i]); + } else { + cpu_tensors[i] = tensors[i]; + } + } + } + auto cpu_valid_tensors = at::_to_cpu(valid_tensors); + for (int i = 0, defined_pos = 0; i < num; ++i) { + if (to_translate[i]) { + cpu_tensors[i] = std::move(cpu_valid_tensors[defined_pos++]); + } + } + return cpu_tensors; +} + +static std::optional compute_target_device(std::vector& t_args, const std::vector>& tlist_args) { + // Decide what device to move the output tensor(s) to. + // The current convention is that we use the first tensor arg to pick the device + // Barring that, we take the first tensor from a TensorList arg. + if (!t_args.empty()) { + return t_args[0].device(); + } else { + // We need to loop through all of the (potentially multiple) TensorList arguments + // In case, e.g. the first one is empty but the second is not. + for (auto& tens_list : tlist_args) { + for (const auto i : c10::irange(tens_list.size())) { + return tens_list.get(i).device(); + } + } + } + return std::nullopt; +} + +static bool validate_tensor_list(const c10::List& tensorlist) { + bool flag = false; + + for (const auto& i : c10::irange(tensorlist.size())) { + if (tensorlist[i].defined()) + flag = true; + } + + return flag; +} + +void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool error_on_views, + c10::DispatchKey cpu_dispatch_key) { + TORCH_CHECK(c10::BackendComponent::CPUBit == c10::toBackendComponent(cpu_dispatch_key), + "Expected CPU backend DispatchKey but got ", + c10::toString(cpu_dispatch_key)); + auto& schema_args = op.schema().arguments(); + const auto num_arguments = schema_args.size(); + auto arguments = torch::jit::last(stack, num_arguments); + const auto arguments_begin = stack->size() - num_arguments; + + std::vector tensor_args; + std::vector tensor_args_indices; + + std::vector> tensorlist_args; + std::vector tensorlist_args_indices; + + std::vector>> optional_tensorlist_args; + std::vector optional_tensorlist_args_indices; + + std::optional tgt_device = std::nullopt; + // save converted cpu tensor for TensorList and optional TensorList + std::vector tensorlist_cpu_args; + std::vector optional_tensorlist_cpu_args; + + // Step 1: Convert all non-CPU tensor inputs into CPU tensors + // and put them on the stack at the correct indices. + for (const auto idx : c10::irange(arguments.size())) { + const auto& ivalue = arguments[idx]; + if (ivalue.isTensor()) { + tensor_args.push_back(ivalue.toTensor()); + tensor_args_indices.push_back(idx); + } else if (ivalue.isTensorList()) { + // Note: we copy each TensorList argument to CPU individually out of convenience, + // but XLA would benefit from materializing all tensor and TensorList args onto the CPU at the same time. + // We can improve this if we need better perf for XLA's CPU fallbacks. + tensorlist_args.push_back(ivalue.toTensorList()); + tensorlist_args_indices.push_back(idx); + auto cpu_ivalue = c10::IValue(c10::List(to_cpu(ivalue.toTensorVector()))); + tensorlist_cpu_args.push_back(cpu_ivalue); + (*stack)[arguments_begin + idx] = std::move(cpu_ivalue); + } else if (ivalue.isOptionalTensorList()) { + optional_tensorlist_args.push_back(ivalue.toOptionalTensorList()); + optional_tensorlist_args_indices.push_back(idx); + auto cpu_ivalue = c10::IValue(c10::List>(to_cpu(ivalue.toOptionalTensorVector()))); + optional_tensorlist_cpu_args.push_back(cpu_ivalue); + (*stack)[arguments_begin + idx] = c10::IValue(cpu_ivalue); + } else if (ivalue.isDevice()) { + tgt_device = ivalue.toDevice(); + (*stack)[arguments_begin + idx] = c10::IValue(c10::Device(kCPU)); + } + } + // XLA requires all of the tensor arguments to be gathered up and converted to CPU together. + auto cpu_tensors = to_cpu(tensor_args); + + for (const auto i : c10::irange(tensor_args_indices.size())) { + auto idx = tensor_args_indices[i]; + (*stack)[arguments_begin + idx] = c10::IValue(cpu_tensors[i]); + } + + // Step 2: Call the underlying CPU implementation of the operator + op.redispatchBoxed(c10::DispatchKeySet(cpu_dispatch_key), stack); + + // Step 3: We need to take special care to handle mutable aliases properly: + // If any input tensors are mutable aliases, we need to + // directly copy the updated data on the CPU tensors back to the original inputs. + for (const auto i : c10::irange(tensor_args_indices.size())) { + auto tensor_idx = tensor_args_indices[i]; + const AliasInfo* alias_info = schema_args[tensor_idx].alias_info(); + if (alias_info != nullptr && alias_info->isWrite()) { + if (!tensor_args[i].defined()) continue; + at::_copy_from_and_resize(cpu_tensors[i], tensor_args[i]); + } + } + + // We also need to explicit reapply input mutations to inputs that are lists + // of tensors + for (const auto i : c10::irange(tensorlist_args_indices.size())) { + auto tensorlist_idx = tensorlist_args_indices[i]; + const AliasInfo* alias_info = schema_args[tensorlist_idx].alias_info(); + if (alias_info != nullptr && alias_info->isWrite()) { + const auto& cpu_tensors = tensorlist_cpu_args[i].toTensorVector(); + for (const auto idx : c10::irange(tensorlist_args[i].size())) { + if (!cpu_tensors[idx].defined()) continue; + at::_copy_from_and_resize(cpu_tensors[idx], tensorlist_args[i][idx]); + } + } + } + + // We also need to explicit reapply input mutations to inputs that are lists + // of optional tensors + for (const auto i : c10::irange(optional_tensorlist_args_indices.size())) { + auto tensorlist_idx = optional_tensorlist_args_indices[i]; + const AliasInfo* alias_info = schema_args[tensorlist_idx].alias_info(); + if (alias_info != nullptr && alias_info->isWrite()) { + const auto& cpu_tensors = optional_tensorlist_cpu_args[i].toOptionalTensorList(); + for (const auto idx : c10::irange(optional_tensorlist_args[i].size())) { + if (cpu_tensors[idx].has_value() && cpu_tensors[idx].value().defined()) { + const std::optional& optional_tensor = optional_tensorlist_args[i][idx]; + at::_copy_from_and_resize(cpu_tensors[idx].value(), optional_tensor.value()); + } + } + } + } + + // Step 4: Convert any CPU output tensors back to the original input device. + // For mutable alias'd outputs, we also need to take special care + // to move the ORIGINAL input tensor back onto the stack, in place of + // the temporary CPU output tensor that we created. + // + // Note [CPU Fallback Does Not Handle View Operators] + // Also note that we are incapable of handling immutable aliases properly. + // Why? + // Schemas with an immutable alias'd tensor outputs correspond to view operators. + // For example, the `view_as` schema from native_functions.yaml: + // `view_as(Tensor(a) self, Tensor other) -> Tensor(a)` + // We can't handle these ops properly, because view ops are supposed to return + // a NEW tensor that shares the SAME storage as the original tensor. + // However, the new tensor that we created cannot share the same storage, + // since it lives on CPU and the original tensor lives on a different device. + // Because of that, we warn if someone attempts to call the + // CPU fallback on a view operator (this is to maintain BC for view ops for XLA + // that fall back to CPU). + const auto& schema_returns = op.schema().returns(); + const auto& num_returns = schema_returns.size(); + auto returns = torch::jit::last(stack, num_returns); + const auto returns_begin = stack->size() - num_returns; + + if (!tgt_device.has_value()){ + tgt_device = compute_target_device(tensor_args, tensorlist_args); + } + + for (const auto idx : c10::irange(returns.size())) { + const AliasInfo* alias_info = schema_returns[idx].alias_info(); + if (alias_info != nullptr && alias_info->isWrite()) { + // Case (1): mutable alias case. + // Move the input ivalue directly onto the stack in place of + // the existing cpu output tensor. + bool found_alias = false; + if (returns[idx].isTensor() && returns[idx].toTensor().defined()) { + // We could store some extra metadata on the function schema to avoid + // the loop here if we need to improve perf. + for (const auto i : c10::irange(tensor_args_indices.size())) { + auto input_tensor_idx = tensor_args_indices[i]; + const auto& input_tensor = cpu_tensors[i]; + const AliasInfo* input_alias_info = + schema_args[input_tensor_idx].alias_info(); + // Checked above; adding assert to guard against breakage of the below + // condition due to changing the above if test. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(alias_info != nullptr); + if (input_tensor.defined() && + (alias_info == input_alias_info || + (input_alias_info != nullptr && + *alias_info == *input_alias_info))) { + // We've found the original input tensor that aliases with the + // current output. Wrap it in an IValue and put it directly on the + // stack. + (*stack)[returns_begin + idx] = c10::IValue(tensor_args[i]); + found_alias = true; + break; + } + } + } else if ( + returns[idx].isTensorList() && + validate_tensor_list(returns[idx].toTensorList())) { + for (const auto i : c10::irange(tensorlist_args_indices.size())) { + auto input_tensor_idx = tensorlist_args_indices[i]; + const AliasInfo* input_alias_info = + schema_args[input_tensor_idx].alias_info(); + // Checked above; adding assert to guard against breakage of the below + // condition due to changing the above if test. + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(alias_info != nullptr); + if (validate_tensor_list(tensorlist_args[i]) && + (alias_info == input_alias_info || + (input_alias_info != nullptr && + *alias_info == *input_alias_info))) { + // We've found the original input tensor that aliases with the + // current output. Wrap it in an IValue and put it directly on the + // stack. + (*stack)[returns_begin + idx] = c10::IValue(tensorlist_args[i]); + found_alias = true; + break; + } + } + } + TORCH_CHECK( + found_alias, + "The operator ", + op.schema().operator_name(), + " appears to have invalid alias information. ", + "Found a return tensor argument with a mismatched mutable alias: ", + schema_returns[idx]); + } else { + if (alias_info != nullptr && !alias_info->isWrite()) { + // Case (3): immutable alias (view) case. + // Warn here, since we're copying and not creating a view. + // If this operator is needed, the backend should provide a kernel for + // it. See Note [CPU Fallback Does Not Handle View Operators] + std::stringstream dev_str; + if (tgt_device) { + dev_str << *tgt_device; + } else { + dev_str << ""; + } + if (error_on_views) { + TORCH_CHECK( + false, + "The operator ", + op.schema().operator_name(), + " appears to be a view operator, ", + "but it has no implementation for the backend \"", + std::move(dev_str).str(), + "\". View operators don't support ", + "since the tensor's storage cannot be shared across devices."); + } else { + TORCH_WARN( + false, + "The operator ", + op.schema().operator_name(), + " appears to be a view operator, ", + "but it has no implementation for the backend \"", + std::move(dev_str).str(), + "\". View operators don't support falling back to run on the CPU, ", + "since the tensor's storage cannot be shared across devices."); + } + } + // Case (2): copy case. + // Copy the cpu output tensor to the original device. + + // We technically might not have a target device, e.g. if you call + // torch.cat() with an empty list In that case, we shouldn't have any + // tensors to schlep across devices anyway. + if (tgt_device) { + if (returns[idx].isTensor() && returns[idx].toTensor().defined()) { + (*stack)[returns_begin + idx] = + c10::IValue(returns[idx].toTensor().to(*tgt_device)); + } else if ( + returns[idx].isTensorList() && + validate_tensor_list(returns[idx].toTensorList())) { + const auto& cpu_tensors = returns[idx].toTensorList().vec(); + std::vector tensors; + tensors.reserve(cpu_tensors.size()); + + for (const auto& tensor : cpu_tensors) { + tensors.push_back(tensor.to(*tgt_device)); + } + (*stack)[returns_begin + idx] = + c10::IValue(c10::List(tensors)); + } + } + } + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CPUFallback.h b/western_ai/usa/pytorch/aten/src/ATen/native/CPUFallback.h new file mode 100644 index 0000000000000000000000000000000000000000..5bffefe5a4223ac7756914457a525d9cc67c7ba5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CPUFallback.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +// This function implements a boxed fallback to CPU. +// External backends can add their own custom logging on top if it to customize their own CPU fallbacks. +TORCH_API void cpu_fallback(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool error_on_views = false, + c10::DispatchKey cpu_dispatch_key = c10::DispatchKey::CPU); + +// This is a helper function that backends can use to directly call their boxed CPU fallback +// TODO: update and add a usage example after https://github.com/pytorch/pytorch/pull/58092 lands. +template +struct _call_fallback_fn final {}; + +template +struct _call_fallback_fn final { + static ReturnType call(typename c10::maybe_keep_symint::type... args) { + auto op = c10::Dispatcher::singleton() + // TODO: figure out how to make compiler happy without dynamic casts + .findSchemaOrThrow((const char*) Op::name, (const char*) Op::overload_name) + //.findSchemaOrThrow("a", "b") + .typed::type...)>(); + return c10::impl::BoxedKernelWrapper::type...)>::call( + c10::BoxedKernel::makeFromFunction(), + op, + c10::DispatchKeySet(), // we know that the cpu_fallback doesn't use the dispatch keyset. + // TODO: get std::forward<> to work + args... + ); + } +}; + +template +using call_fallback_fn_symint = _call_fallback_fn; + +template +using call_fallback_fn = _call_fallback_fn; + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CanUse32BitIndexMath.h b/western_ai/usa/pytorch/aten/src/ATen/native/CanUse32BitIndexMath.h new file mode 100644 index 0000000000000000000000000000000000000000..983ff7fe26e332a979ece32d42889081e6c56fcf --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CanUse32BitIndexMath.h @@ -0,0 +1,13 @@ +#pragma once +#include +#include + +namespace at { +class TensorBase; +} + +namespace at::native { + +TORCH_API bool canUse32BitIndexMath(const at::TensorBase &t, int64_t max_elem=std::numeric_limits::max()); + +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ChanelShuffle.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ChanelShuffle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68b5b4dd649bbc1f92e2dc1a199b0412595c22ed --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ChanelShuffle.cpp @@ -0,0 +1,106 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#if defined(C10_MOBILE) && defined(USE_XNNPACK) +#include +#endif +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { + +Tensor channel_shuffle_cpu(const Tensor& self, int64_t groups) { + TORCH_CHECK(self.dim() > 2, + "channel_shuffle expects input with > 2 dims, but got input with sizes ", + self.sizes()); + int64_t c = self.size(1); + TORCH_CHECK(groups > 0, + "Number of groups to divide channels in must be positive.", + " Value of groups:", groups); + TORCH_CHECK((c % groups) == 0, + "Number of channels must be divisible by groups. Got ", + c, " channels and ", groups, " groups."); + + Tensor output; + if (self.numel() == 0) { + output = self.alias(); + } else { + auto memory_format = self.suggest_memory_format(); + output = at::empty({0}, self.options()); + output.resize_(self.sizes(), memory_format); + auto input = self.contiguous(memory_format); + channel_shuffle_kernel(kCPU, output, input, groups); + } + return output; +} + +Tensor channel_shuffle(const Tensor& self, int64_t groups) { + TORCH_CHECK(self.dim() > 2, + "channel_shuffle expects input with > 2 dims, but got input with sizes ", + self.sizes()); + int64_t c = self.size(1); + TORCH_CHECK(groups > 0, + "Number of groups to divide channels in must be positive.", + " Value of groups:", groups); + TORCH_CHECK((c % groups) == 0, + "Number of channels must be divisible by groups. Got ", + c, " channels and ", groups, " groups."); + +#if defined(C10_MOBILE) && defined(USE_XNNPACK) + if (self.is_contiguous(MemoryFormat::ChannelsLast) && + xnnpack::use_channel_shuffle(self, groups)) { + auto output = self.numel() == 0 ? self.alias() : xnnpack::channel_shuffle(self, groups); + return output; + } +#endif + + auto output = self.numel() == 0 ? self.alias() : at::native_channel_shuffle(self, groups); + return output; +} + +Tensor math_channel_shuffle(const Tensor& self, int64_t groups) { + TORCH_CHECK(self.dim() > 2, + "channel_shuffle expects input with > 2 dims, but got input with sizes ", + self.sizes()); + int64_t b = self.size(0); + int64_t c = self.size(1); + TORCH_CHECK(groups > 0, + "Number of groups to divide channels in must be positive.", + " Value of groups:", groups); + TORCH_CHECK((c % groups) == 0, + "Number of channels must be divisible by groups. Got ", + c, " channels and ", groups, " groups."); + int64_t oc = c / groups; + + auto input_reshaped = self.view({b, groups, oc, -1}); + // TODO: contiguous can be made to preserve the memory format + // of the input. However since the above reshape clobbers h and w + // it may not be safe to do that, since channels_last contiguous + // may think oc and the last dim correspond to h,w? + // It is not clear, however from initial looking around it feels that + // this may not be correct. + // In this case channels last will likely require custom implementation + // if we want to preserve the memory order. + // XNNPACK has channel shuffle op for NHWC. For mobile usecase this is good. + // For server we will have to do a custom implementation. + // For ChannelsFirst, a.k.a Contiguous, memory format we will also need + // a fast custom implementation perhaps. + Tensor output_tensor = + input_reshaped.permute({0 /* b */, 2 /* oc */, 1 /* groups */, 3}) + .contiguous() + .reshape(self.sizes()); + return output_tensor; +} + +DEFINE_DISPATCH(channel_shuffle_kernel); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Col2Im.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Col2Im.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1756a13391626df47c6658b457d776c423f01115 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Col2Im.cpp @@ -0,0 +1,217 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +// Note [im2col/col2im output padding] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Our implementations of im2col and col2im take both the input height/width as +// well as a seemingly redundant output height/width. In principle, you could +// compute the output height/width by using the convolution shape formulas. So, +// what's up with that? +// +// The trouble arises when one runs the backward of a transposed convolution +// with output_padding >= stride. (BTW, output_padding is known as adj inside +// THNN.) Let's consider a simple case where we have kernel=2, dilation=2, +// stride=1, output_padding=1 for a 4x4 input: +// +// Input: X +// +// Output: X.X. +// .... +// X.X. +// .... +// +// If we compute backwards of output with a standard convolution on the output +// with the same parameters, we would end up with a 2x2 grad_input (because you +// can slide the stencil over to the right once and down once). But that is all +// out-of-bounds if you're computing backwards for a 1x1 input. +// +// "Now Edward," you might say, "the real problem is that you set output_padding +// >= stride, surely an error should have been raised in this case." To +// understand why it is useful to handle this case, we have to understand how we +// compute the weight gradient of a convolution. Suppose we have a convolution +// with kernel=2, stride=2 on a 5x5 input. Let us see all the contributions of +// weight[0][0] (which we have labeled w) in the output: +// +// Input: a.b.. Weight: w. +// ..... .. +// c.d.. +// ..... +// ..... +// +// Output: [ aw+... bw+... ] +// [ cw+... dw+... ] +// +// From this diagram, it easy to see that we can compute the weight gradient +// by performing a *dilated* convolution between the input and the +// output gradients with kernel=2, dilation=2, stride=1. But there's a rub: if +// we do a dilated convolution directly, we'll end up with a 3x3 weight +// gradient, when we clearly wanted a 2x2. So how do we avoid going out +// of bounds? We could add a notion of 'output_padding' for non-transposed +// convolution, but another simple and effective fix is to just accept +// the desired output size directly, and compute only within those bounds. +// +// +// ALSO do vol2col + +namespace at::native { +namespace { + +void col2im_out_cpu_template( + Tensor& output, + const Tensor& input_, + IntArrayRef output_size, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride) { + TORCH_CHECK( + output_size.size() == 2, + "It is expected output_size equals to 2, but got size ", + output_size.size()); + + TORCH_CHECK( + kernel_size.size() == 2, + "It is expected kernel_size equals to 2, but got size ", + kernel_size.size()); + + TORCH_CHECK( + dilation.size() == 2, + "It is expected dilation equals to 2, but got size ", + dilation.size()); + + TORCH_CHECK( + padding.size() == 2, + "It is expected padding equals to 2, but got size ", + padding.size()); + + TORCH_CHECK( + stride.size() == 2, + "It is expected stride equals to 2, but got size ", + stride.size()); + + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + int64_t kernel_height = kernel_size[0]; + int64_t kernel_width = kernel_size[1]; + int64_t dilation_height = dilation[0]; + int64_t dilation_width = dilation[1]; + int64_t pad_height = padding[0]; + int64_t pad_width = padding[1]; + int64_t stride_height = stride[0]; + int64_t stride_width = stride[1]; + + col2im_shape_check( + input_, + Tensor(), + output_height, + output_width, + kernel_height, + kernel_width, + dilation_height, + dilation_width, + pad_height, + pad_width, + stride_height, + stride_width); + + Tensor input = input_.contiguous(); + + bool batched_input = true; + if (input.dim() == 2) { + // Force batch + batched_input = false; + input = input.view({1, input.size(0), input.size(1)}); + } + + int64_t batch_size = input.size(0); + int64_t n_input_plane = input.size(1); + int64_t n_output_plane = n_input_plane / (kernel_width * kernel_height); + + output.resize_({batch_size, n_output_plane, output_height, output_width}); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3(kBFloat16, kHalf, kBool, + input.scalar_type(), "col2im_out_cpu", [&] { + Tensor input_n = Tensor(); + Tensor output_n = Tensor(); + + int64_t height_col = (output_height + 2 * pad_height - + (dilation_height * (kernel_height - 1) + 1)) / + stride_height + + 1; + int64_t width_col = (output_width + 2 * pad_width - + (dilation_width * (kernel_width - 1) + 1)) / + stride_width + + 1; + + for (const auto elt : c10::irange(batch_size)) { + input_n = input.select(0, elt); + output_n = output.select(0, elt); + + col2im( + input_n.const_data_ptr(), + n_output_plane, + output_height, + output_width, + height_col, + width_col, + kernel_height, + kernel_width, + pad_height, + pad_width, + stride_height, + stride_width, + dilation_height, + dilation_width, + output_n.mutable_data_ptr()); + } + + if (!batched_input) { + output.resize_({n_output_plane, output_height, output_width}); + } + }); +} + +} // namespace + +Tensor& col2im_out_cpu(const Tensor& input, + IntArrayRef output_size, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride, + Tensor& output) { + col2im_out_cpu_template( + output, input, output_size, kernel_size, dilation, padding, stride); + return output; +} + +Tensor col2im_cpu( + const Tensor& input, + IntArrayRef output_size, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride) { + Tensor output = at::empty_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + + col2im_out_cpu_template( + output, input, output_size, kernel_size, dilation, padding, stride); + return output; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ComparisonUtils.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ComparisonUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9d107664acb015e2b61bb6e49dd368a7c6ff574 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ComparisonUtils.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include + +#ifdef AT_PER_OPERATOR_HEADERS +#include +#endif + +namespace at { + +class Tensor; + +namespace native { + +template +static void _assert_match(const O& original, const C& compared, const std::string& name) { + TORCH_CHECK(!compared || original == compared.value(), "Tensor ", + name, + " mismatch! Expected: ", + compared.value(), + ", Got: ", + original); +} + +template<> +void _assert_match>( + const c10::Device& original, + const std::optional& compared, + const std::string& name) { + if (compared) { + const c10::Device& expected = compared.value(); + TORCH_CHECK(original.type() == expected.type(), "Tensor ", + name, + " mismatch! Expected: ", + expected, + ", Got: ", + original); + + // If the expected device doesn't have an index (e.g., just "cuda"), + // or if both devices have the same index, consider them equal + TORCH_CHECK(!expected.has_index() || !original.has_index() || expected.index() == original.index(), "Tensor ", + name, + " mismatch! Expected: ", + expected, + ", Got: ", + original); + } +} + +void _assert_tensor_metadata_meta_symint(at::Tensor const& tensor, at::OptionalSymIntArrayRef sizes, at::OptionalSymIntArrayRef strides, std::optional dtype, std::optional device, std::optional layout) { + _assert_match(tensor.sym_sizes(), sizes, "sizes"); + _assert_match(tensor.sym_strides(), strides, "strides"); + _assert_match(tensor.dtype(), dtype, "dtype"); + if (tensor.device().type() != DeviceType::Meta) { + _assert_match(tensor.device(), device, "device"); + } + _assert_match(tensor.layout(), layout, "layout"); +} + +void _assert_tensor_metadata(at::Tensor const& tensor, at::OptionalIntArrayRef sizes, at::OptionalIntArrayRef strides, std::optional dtype, std::optional device, std::optional layout) { + _assert_match(tensor.sizes(), sizes, "sizes"); + _assert_match(tensor.strides(), strides, "strides"); + _assert_match(tensor.dtype(), dtype, "dtype"); + if (tensor.device().type() != DeviceType::Meta) { + _assert_match(tensor.device(), device, "device"); + } + _assert_match(tensor.layout(), layout, "layout"); +} + +} +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ComplexHelper.h b/western_ai/usa/pytorch/aten/src/ATen/native/ComplexHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..a7a380c0bbb356616eab94495a94f43c95db5bae --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ComplexHelper.h @@ -0,0 +1,104 @@ +#pragma once + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include + +#include +#endif + +// WARNING: this header contains non-inline functions and should be only +// included from ONE cpp file + +namespace at::native { + +// View tensor with new dtype, storage offset, sizes and strides +inline Tensor view_tensor( + const Tensor &tensor, ScalarType dtype, + c10::SymInt offset, SymIntArrayRef sizes, SymIntArrayRef strides) { + Storage storage = tensor.storage(); + auto key_set = tensor.key_set().remove(DispatchKey::Conjugate); + auto new_tensor = detail::make_tensor( + c10::TensorImpl::VIEW, std::move(storage), key_set, scalarTypeToTypeMeta(dtype)); + auto * impl = new_tensor.unsafeGetTensorImpl(); + impl->set_sizes_and_strides(sizes, strides, offset); + return new_tensor; +} + +inline SymDimVector computeStrideForViewAsReal(SymIntArrayRef oldstride) { + SymDimVector res(oldstride.size() + 1); + for (const auto i : c10::irange(oldstride.size())) { + res[i] = oldstride[i] * 2; + } + res.back() = 1; + return res; +} + +inline Tensor _view_as_real_physical(const Tensor& self) { + TORCH_CHECK(self.is_complex(), "view_as_real is only supported for complex tensors"); + auto old_sizes = self.sym_sizes(); + SymDimVector new_sizes(old_sizes.size() + 1); + std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin()); + // last dimension will always have two elements containing the real and imag vals + new_sizes.back() = 2; + auto new_strides = computeStrideForViewAsReal(self.sym_strides()); + auto new_storage_offset = self.sym_storage_offset() * 2; + const auto float_type = c10::toRealValueType(self.scalar_type()); + auto real_tensor = view_tensor(self, float_type, std::move(new_storage_offset), new_sizes, new_strides); + return real_tensor; +} + +// expects as input a complex tensor and returns back a tensor +// with corresponding real dtype containing the complex values +// in the last two dimensions +Tensor view_as_real(const Tensor& self) { + TORCH_CHECK(!self.is_conj(), "view_as_real doesn't work on unresolved conjugated tensors. To resolve the conjugate tensor so you can view it as real, use self.resolve_conj(); however, be warned that the resulting tensor will NOT alias the original."); + return _view_as_real_physical(self); +} + +inline SymDimVector computeStrideForViewAsComplex( + SymIntArrayRef oldstride, + SymIntArrayRef oldsizes) { + const auto dim = oldstride.size(); + TORCH_CHECK(dim > 0, "Tensor must have one or more dimensions"); + TORCH_SYM_CHECK(oldstride[dim - 1].sym_eq(1), "Tensor must have a last dimension with stride 1"); + + SymDimVector res(dim - 1); + for (const auto i : c10::irange(res.size())) { + // Skip divisibility check for singleton dimensions + TORCH_SYM_CHECK( + oldsizes[i].sym_eq(1) | (oldstride[i] % 2).sym_eq(0), + "Tensor must have a stride divisible by 2 for all but last dimension"); + res[i] = oldstride[i] / 2; + } + return res; +} + +// expects as input a float or double tensor with last dimension of size 2 +// and returns back a tensor with corresponding complex dtype +Tensor view_as_complex(const Tensor& self) { + TORCH_CHECK( + self.scalar_type() == kFloat || self.scalar_type() == kDouble || self.scalar_type() == kHalf, + "view_as_complex is only supported for half, float and double tensors, but got a tensor of scalar type: ", self.scalar_type()); + + auto old_sizes = self.sym_sizes(); + TORCH_CHECK(!old_sizes.empty(), "Input tensor must have one or more dimensions"); + TORCH_SYM_CHECK(old_sizes[old_sizes.size()-1].sym_eq(2), "Tensor must have a last dimension of size 2"); + SymDimVector new_sizes(old_sizes.begin(), old_sizes.end() - 1); + + const auto new_strides = computeStrideForViewAsComplex(self.sym_strides(), self.sym_sizes()); + const auto complex_type = c10::toComplexType(self.scalar_type()); + + TORCH_SYM_CHECK((self.sym_storage_offset() % 2).sym_eq(0), "Tensor must have a storage_offset divisible by 2"); + const auto new_storage_offset = self.sym_storage_offset() / 2; + + return view_tensor(self, complex_type, new_storage_offset, new_sizes, new_strides); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CompositeRandomAccessor.h b/western_ai/usa/pytorch/aten/src/ATen/native/CompositeRandomAccessor.h new file mode 100644 index 0000000000000000000000000000000000000000..27aefd57376f4468da7f628cec608c4e4837c4b5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CompositeRandomAccessor.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +namespace at::native { + +struct TupleInfoCPU { + template + using tuple = std::tuple; + + template + static constexpr auto tie(Types&... args) noexcept { + return std::tie(args...); + } +}; + +template +using CompositeRandomAccessorCPU = + CompositeRandomAccessor; + +template +void swap( + references_holder rh1, + references_holder rh2 +) { + return std::swap(rh1.data(), rh2.data()); +} + +template +auto get(references_holder rh) -> decltype(std::get(rh.data())) { + return std::get(rh.data()); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/CompositeRandomAccessorCommon.h b/western_ai/usa/pytorch/aten/src/ATen/native/CompositeRandomAccessorCommon.h new file mode 100644 index 0000000000000000000000000000000000000000..5db76a15575c4542004ef6fbedbdc3fb73d1f3fb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/CompositeRandomAccessorCommon.h @@ -0,0 +1,263 @@ +#include + +#pragma once + +namespace at::native { + +namespace { + +// operator_brackets_proxy is used in +// CompositeRandomAccessor in place of operator[]. +// For some iterators, references returned by operator[] +// could become invalid, operator_brackets_proxy tries to +// resolve that by making accessor[n] to be equivalent to +// *(accessor + n). +template +class operator_brackets_proxy { + using reference = typename std::iterator_traits::reference; + using value_type = typename std::iterator_traits::value_type; + +public: + C10_HOST_DEVICE + operator_brackets_proxy(Accessor const& accessor) + : accessor(accessor) + {} + + C10_HOST_DEVICE + operator reference() { + return *accessor; + } + + C10_HOST_DEVICE + reference operator*() { + return *accessor; + } + + C10_HOST_DEVICE + operator_brackets_proxy& operator=(value_type const& val) { + *accessor = val; + return *this; + } + +private: + Accessor accessor; +}; + +} + +// references_holder is used as a surrogate for the +// references type from std::iterator_traits in CompositeRandomAccessor. +// It is assumed in CompositeRandomAccessor that +// References = tuple, +// Values = tuple by default, +// but they could be anything as long as References could be +// cast to Values. +// If you plan to use it with STL, for example, you will need to +// define 'swap` and `get`(aka std::get) methods. +template +class references_holder { +public: + using values = Values; + using references = References; + + C10_HOST_DEVICE + references_holder(references refs) + : refs{std::move(refs)} + {} + + C10_HOST_DEVICE + operator references() { + return refs; + } + + C10_HOST_DEVICE + operator values() { + return refs; + } + + C10_HOST_DEVICE + references_holder& operator=(values vals) { + refs = vals; + return *this; + } + + C10_HOST_DEVICE + references& data() { + return refs; + } + +protected: + references refs; +}; + +// CompositeRandomAccessor is essentially a simplified version of +// a random access iterator over two random access iterators. +// TupleInfo should contain a variadic type `tuple`, and a method `tie`, +// which constructs a tuple of references from a variadic list of arguments. +template +class CompositeRandomAccessor { + using self_type = CompositeRandomAccessor; + + using key_accessor_value_type = + typename std::iterator_traits::value_type; + using value_accessor_value_type = + typename std::iterator_traits::value_type; + using key_accessor_reference_type = + typename std::iterator_traits::reference; + using value_accessor_reference_type = + typename std::iterator_traits::reference; + + using composite_value_type = typename TupleInfo::template tuple< + key_accessor_value_type, + value_accessor_value_type>; + using composite_reference = typename TupleInfo::template tuple< + key_accessor_reference_type, + value_accessor_reference_type>; + +public: + using value_type = composite_value_type; + using reference = references_holder; + // Note that CompositeRandomAccessor does not hold key and values + // in a specific datastructure, which means that a pointer to a (key, value) + // is not defined. Hence we just use a pointer type of the KeyAccessor. + using pointer = typename std::iterator_traits::pointer; + using difference_type = typename std::iterator_traits::difference_type; + using iterator_category = std::random_access_iterator_tag; + + C10_HOST_DEVICE + CompositeRandomAccessor() = default; + + C10_HOST_DEVICE + CompositeRandomAccessor(KeyAccessor keys, ValueAccessor values) + : keys(keys), values(values) + {} + + // Pointer-like operations { + C10_HOST_DEVICE + reference operator*() const { + return TupleInfo::tie(*keys, *values); + } + + // operator->() is supposed to return a pointer type. + // Since CompositeRandomAccessor does not hold pointers to pairs, + // we just return a pointer to a key. + C10_HOST_DEVICE + auto* operator->() const { + return keys.operator->(); + } + + C10_HOST_DEVICE + reference operator[](difference_type idx) { + return operator_brackets_proxy( + CompositeRandomAccessor(keys + idx, values + idx) + ); + } + // } + + // Prefix/postfix increment/decrement { + C10_HOST_DEVICE + CompositeRandomAccessor& operator++() { + ++keys; + ++values; + return *this; + } + + C10_HOST_DEVICE + CompositeRandomAccessor operator++(int) { + CompositeRandomAccessor copy(*this); + ++*this; + return copy; + } + + C10_HOST_DEVICE + CompositeRandomAccessor& operator--() { + --keys; + --values; + return *this; + } + + C10_HOST_DEVICE + CompositeRandomAccessor operator--(int) { + CompositeRandomAccessor copy(*this); + --*this; + return copy; + } + // } + + // Arithmetic operations { + C10_HOST_DEVICE + CompositeRandomAccessor& operator+=(difference_type offset) { + keys += offset; + values += offset; + return *this; + } + + C10_HOST_DEVICE + CompositeRandomAccessor operator+(difference_type offset) const { + return CompositeRandomAccessor(keys + offset, values + offset); + } + + C10_HOST_DEVICE + friend CompositeRandomAccessor operator+( + difference_type offset, + const CompositeRandomAccessor& accessor + ) { + return accessor + offset; + } + + C10_HOST_DEVICE + CompositeRandomAccessor& operator-=(difference_type offset) { + keys -= offset; + values -= offset; + return *this; + } + + C10_HOST_DEVICE + CompositeRandomAccessor operator-(difference_type offset) const { + return CompositeRandomAccessor(keys - offset, values - offset); + } + + C10_HOST_DEVICE + difference_type operator-(const CompositeRandomAccessor& other) const { + return keys - other.keys; + } + // } + + // Comparison operators { + C10_HOST_DEVICE + bool operator==(const CompositeRandomAccessor& other) const { + return keys == other.keys; + } + + C10_HOST_DEVICE + bool operator!=(const CompositeRandomAccessor& other) const { + return keys != other.keys; + } + + C10_HOST_DEVICE + bool operator<(const CompositeRandomAccessor& other) const { + return keys < other.keys; + } + + C10_HOST_DEVICE + bool operator<=(const CompositeRandomAccessor& other) const { + return keys <= other.keys; + } + + C10_HOST_DEVICE + bool operator>(const CompositeRandomAccessor& other) const { + return keys > other.keys; + } + + C10_HOST_DEVICE + bool operator>=(const CompositeRandomAccessor& other) const { + return keys >= other.keys; + } + // } + +protected: + KeyAccessor keys; + ValueAccessor values; +}; + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Constraints.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Constraints.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d18c03bed247f51fde16ef3c18f24282a778fde --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Constraints.cpp @@ -0,0 +1,90 @@ +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +void sym_constrain_range( + const Scalar& size, + std::optional min, + std::optional max) { + + int64_t min_val = min.has_value() ? min.value() : std::numeric_limits::min(); + int64_t max_val = max.has_value() ? max.value() : std::numeric_limits::max(); + int64_t size_as_int = size.toLong(); + + TORCH_CHECK( + max_val >= min_val, + "Max must be greater than or equal to min. Got min=", + min_val, + " max=", + max_val + ); + + TORCH_CHECK( + min_val <= size_as_int && size_as_int <= max_val, + "Invalid value range for ", + size_as_int, + " between [", + min_val, + ", ", + max_val, + "]." + ); +} + +Tensor _functional_sym_constrain_range( + const Scalar& size, + std::optional min, + std::optional max, + const Tensor& dep_token) { + sym_constrain_range(size, min, max); + return dep_token.clone(); +} + +void sym_constrain_range_for_size(const Scalar& size, std::optional min, std::optional max) { + int64_t min_val = min.has_value() ? min.value() : 0; + if (max.has_value() && max.value() <= 2) { + TORCH_CHECK(false, "Max value to constrain_range_for_size must be greater than 2. got: ", max.value()); + } + sym_constrain_range(size, min_val, max); +} + +Tensor _functional_sym_constrain_range_for_size( + const Scalar& size, + std::optional min, + std::optional max, + const Tensor& dep_token) { + sym_constrain_range_for_size(size, min, max); + return dep_token.clone(); +} + +Tensor _make_dep_token_cpu( + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt) { + return at::empty( + {}, dtype_opt, layout_opt, device_opt, pin_memory_opt, memory_format_opt); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ConvUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/ConvUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..4c476746c64b00b2fae77e5bc01b863e11f69425 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ConvUtils.h @@ -0,0 +1,446 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native { + +// Shared dispatch signatures. Many backward ops have identical shapes; +// one alias per shape avoids N near-duplicate typedefs. The stub name passed +// to DECLARE_DISPATCH is what makes each registration unique. + +// 2-output backward (depthwise2d): 4 IntArrayRef params. +using conv_depthwise2d_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, at::IntArrayRef, std::array); + +// 3-output backward with 4 IntArrayRef params (depthwise3d, slow_conv_dilated2d/3d). +using conv_dilated_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, at::IntArrayRef, std::array); + +// 3-output slow transpose backward with 5 IntArrayRef params (slow_conv_transpose2d/3d). +using slow_conv_transpose_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array); + +// 3-output backward, forward shape (mps, mkldnn): 3 IARs + groups. +using conv_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, int64_t, std::array); + +// 3-output backward, transpose shape (mkldnn_transpose): 4 IARs + groups. +using conv_transpose_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, at::IntArrayRef, int64_t, std::array); + +// cuDNN backward (2-output, carries benchmark/deterministic/allow_tf32). +using cudnn_convolution_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, int64_t, bool, bool, bool, std::array); +using cudnn_convolution_transpose_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, bool, std::array); + +// MIOpen backward (3-output, carries benchmark/deterministic). +using miopen_convolution_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, int64_t, bool, bool, std::array); +using miopen_convolution_transpose_backward_fn = std::tuple(*)( + const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef, + at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, std::array); + +// MKLDNN forward transpose (not a backward). +using mkldnn_convolution_transpose_fn = Tensor(*)(const Tensor&, const Tensor&, const std::optional&, + IntArrayRef, IntArrayRef, IntArrayRef, IntArrayRef, int64_t); + +// Depthwise. +DECLARE_DISPATCH(conv_depthwise2d_backward_fn, conv_depthwise2d_backward_stub) +DECLARE_DISPATCH(conv_dilated_backward_fn, conv_depthwise3d_backward_stub) + +// cuDNN. +DECLARE_DISPATCH(cudnn_convolution_backward_fn, cudnn_convolution_backward_stub) +DECLARE_DISPATCH(cudnn_convolution_transpose_backward_fn, cudnn_convolution_transpose_backward_stub) + +// MPS. +DECLARE_DISPATCH(conv_backward_fn, mps_convolution_backward_stub) + +// MIOpen. +DECLARE_DISPATCH(miopen_convolution_backward_fn, miopen_convolution_backward_stub) +DECLARE_DISPATCH(miopen_convolution_transpose_backward_fn, miopen_convolution_transpose_backward_stub) +DECLARE_DISPATCH(miopen_convolution_backward_fn, miopen_depthwise_convolution_backward_stub) + +// MKLDNN. +DECLARE_DISPATCH(conv_backward_fn, mkldnn_convolution_backward_stub) +DECLARE_DISPATCH(mkldnn_convolution_transpose_fn, mkldnn_convolution_transpose_stub) +DECLARE_DISPATCH(conv_transpose_backward_fn, mkldnn_convolution_transpose_backward_stub) + +// Slow conv (CPU reference). +DECLARE_DISPATCH(conv_dilated_backward_fn, slow_conv_dilated2d_backward_stub) +DECLARE_DISPATCH(conv_dilated_backward_fn, slow_conv_dilated3d_backward_stub) +DECLARE_DISPATCH(slow_conv_transpose_backward_fn, slow_conv_transpose2d_backward_stub) +DECLARE_DISPATCH(slow_conv_transpose_backward_fn, slow_conv_transpose3d_backward_stub) + +namespace { + bool is_cudnnv8_heuristic_mode_b() { + static const bool is_cudnnv8_heuristic_mode_b = c10::utils::check_env("TORCH_CUDNN_USE_HEURISTIC_MODE_B") == true; + return is_cudnnv8_heuristic_mode_b; + } +} + +inline bool cudnnv8_enabled_check_debug() { + static bool cudnnv8_flag = c10::utils::check_env("TORCH_CUDNN_V8_API_DISABLED") != true; + static bool cudnnv8_debug = c10::utils::check_env("TORCH_CUDNN_V8_API_DEBUG") == true; + static uint8_t cudnnv8_debugcount = 0; + if (cudnnv8_debug == 1 && cudnnv8_debugcount < 10) { + TORCH_WARN("TORCH_CUDNN_V8_DEBUG ON, V8 ON: ", cudnnv8_flag, " TORCH_CUDNN_USE_HEURISTIC_MODE B: ", is_cudnnv8_heuristic_mode_b()); + cudnnv8_debugcount++; + } + return cudnnv8_flag == 1; +} + +inline bool cudnnv8_use_heur_mode_b() { + return is_cudnnv8_heuristic_mode_b(); +} + +// Keep in sync with py::enum_ in Module.cpp +enum class ConvBackend { + CudaDepthwise2d, + CudaDepthwise3d, + Cudnn, + CudnnTranspose, + Empty, + Miopen, + MiopenDepthwise, + MiopenTranspose, + Mkldnn, + MkldnnTranspose, + MkldnnEmpty, + NnpackSpatial, + Overrideable, + Slow2d, + Slow3d, + SlowDilated2d, + SlowDilated3d, + SlowTranspose2d, + SlowTranspose3d, + Winograd3x3Depthwise, + Xnnpack2d, + Mps, + MpsTranspose, +}; + +// Overload for selecting the convolution backend from the full set of convolution inputs. +// This overload is exposed to python for testing, etc. +TORCH_API ConvBackend select_conv_backend( + const Tensor& input, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef dilation, + bool transposed, SymIntArrayRef output_padding, c10::SymInt groups, const at::OptionalSymIntArrayRef bias_sizes_opt); + +TORCH_API at::MemoryFormat _determine_backend_memory_format(const Tensor& input, + const Tensor& weight, + const ConvBackend backend); + +// --------------------------------------------------------------------- +// +// Math +// +// --------------------------------------------------------------------- + +constexpr int input_batch_size_dim = 0; // also grad_input +constexpr int input_channels_dim = 1; +constexpr int output_batch_size_dim = 0; // also grad_output +constexpr int output_channels_dim = 1; +constexpr int weight_output_channels_dim = 0; +constexpr int weight_input_channels_dim = 1; + +// Often written as 2 + max_dim (extra dims for batch size and channels) +constexpr int max_dim = 3; + +// --------------------------------------------------------------------- +// +// Checking +// +// --------------------------------------------------------------------- + +// Used on pad, stride and dilation +static void check_args(CheckedFrom c, IntArrayRef args, size_t expected_size, const char* arg_name) +{ + TORCH_CHECK(args.size() <= expected_size, + "Too many ", arg_name, " values (", args.size(), ") supplied, expecting ", + expected_size, " (while checking arguments for ", c, ")"); + TORCH_CHECK(args.size() >= expected_size, + "Not enough ", arg_name, " values (", args.size(), ") supplied, expecting ", + expected_size, " (while checking arguments for ", c, ")"); + + auto num_negative_values = std::count_if(args.begin(), args.end(), [](int x){return x < 0;}); + if (num_negative_values > 0){ + std::stringstream ss; + ss << arg_name << " should be greater than zero but got ("; + std::copy(args.begin(), args.end() - 1, std::ostream_iterator(ss,", ")); + ss << args.back() << ')' << " (while checking arguments for " << c << ')'; + TORCH_CHECK(false, std::move(ss).str()); + } +} + + +// NOTE [ Convolution checks ] +// +// NB: For many call sites, it is not strictly necessary to check all of +// these relationships (for example, for forward convolution, we compute +// the size of output ourselves, so we don't actually need to check +// output. However, writing a single function that does everything +// means we get to reuse it for both forwards and all backwards +// variants, even when the set of "real" inputs varies. The magic of +// relational computing! +// +// (There is one downside, which is that it is slightly harder to write +// error messages which are able to distinguish between real inputs +// (which the user can change) and computed inputs (which the user can +// only indirectly affect). It would be an interesting exercise to +// come up with a general framework to handle such situations.) +inline void convolution_shape_check( + CheckedFrom c, + const TensorGeometryArg& input, const TensorGeometryArg& weight, const TensorGeometryArg& output, + IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups) +{ + check_args(c, padding, input->dim() - 2, "padding"); + check_args(c, stride, padding.size(), "stride"); + check_args(c, dilation, padding.size(), "dilation"); + for (auto s : stride) { + TORCH_CHECK(s > 0, "Stride must be greater than 0 but got ", s); + } + for (auto d : dilation) { + TORCH_CHECK(d > 0, "Dilation must be greater than 0 but got ", d); + } + for (auto p : padding) { + TORCH_CHECK(p >= 0, "Padding must be non-negative but got ", p); + } + + // Input + checkDimRange(c, input, 3, 6 /* exclusive */); + checkSize_symint(c, input, input_channels_dim, weight->size(1) * groups); + + // Weight + checkSameDim(c, input, weight); + + // TODO: check that output->size() matches output_sizes + // TODO: check that weight matches output->sizes() + checkSameDim(c, input, output); +} + +// NB: conv_output_size and conv_input_size are not bijections, +// as conv_output_size loses information; this is why conv_input_size +// takes an extra output_padding argument to resolve the ambiguity. + +template +inline std::vector _conv_output_size( + ArrayRef input_size, ArrayRef weight_size, + ArrayRef padding, ArrayRef stride, ArrayRef dilation = ArrayRef() +) { + // ASSERT(input_size.size() > 2) + // ASSERT(input_size.size() == weight_size.size()) + bool has_dilation = !dilation.empty(); + auto dim = input_size.size(); + std::vector output_size(dim); + output_size[0] = input_size[input_batch_size_dim]; + output_size[1] = weight_size[weight_output_channels_dim]; + for (const auto d : c10::irange(2, dim)) { + auto dilation_ = has_dilation ? dilation[d - 2] : 1; + auto kernel = dilation_ * (weight_size[d] - 1) + 1; + output_size[d] = (input_size[d] + (2 * padding[d - 2]) - kernel) / stride[d - 2] + 1; + } + return output_size; +} + +inline std::vector conv_output_size( + IntArrayRef input_size, IntArrayRef weight_size, + IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef() +) { + return _conv_output_size(input_size, weight_size, padding, stride, dilation); +} + +inline std::vector conv_output_size( + SymIntArrayRef input_size, SymIntArrayRef weight_size, + SymIntArrayRef padding, SymIntArrayRef stride, SymIntArrayRef dilation = SymIntArrayRef() +) { + return _conv_output_size(input_size, weight_size, padding, stride, dilation); +} + +template +std::vector _conv_input_size( + ArrayRef output_size, ArrayRef weight_size, + ArrayRef padding, ArrayRef output_padding, ArrayRef stride, ArrayRef dilation, T groups +) { + // ASSERT(output_size.size() > 2) + // ASSERT(output_size.size() == weight_size.size()) + auto dim = output_size.size(); + std::vector input_size(dim); + input_size[0] = output_size[output_batch_size_dim]; + input_size[1] = weight_size[weight_input_channels_dim] * groups; + for (const auto d : c10::irange(2, dim)) { + auto kernel = (weight_size[d] - 1) * dilation[d - 2] + 1; + input_size[d] = (output_size[d] - 1) * stride[d - 2] - (padding[d - 2] * 2) + + kernel + output_padding[d - 2]; + } + return input_size; +} + +inline std::vector conv_input_size( + SymIntArrayRef output_size, SymIntArrayRef weight_size, + SymIntArrayRef padding, SymIntArrayRef output_padding, SymIntArrayRef stride, SymIntArrayRef dilation, c10::SymInt groups +) { + return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, std::move(groups)); +} + +inline std::vector conv_input_size( + IntArrayRef output_size, IntArrayRef weight_size, + IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups +) { + return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups); +} + +template +std::vector _conv_weight_size( + ArrayRef input_size, ArrayRef output_size, + ArrayRef padding, ArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups +) { + auto dim = input_size.size(); + std::vector weight_size(dim); + weight_size[0] = output_size[1]; + weight_size[1] = input_size[1] / groups; + for (const auto d : c10::irange(2, dim)) { + auto kernel = input_size[d] - (output_size[d] - 1) * stride[d - 2] + + padding[d - 2] * 2 - output_padding[d - 2]; + weight_size[d] = (kernel - 1) / dilation[d - 2] + 1; + } + return weight_size; +} + +inline std::vector conv_weight_size( + SymIntArrayRef input_size, SymIntArrayRef output_size, + SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups +) { + return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups); +} + +inline std::vector conv_weight_size( + IntArrayRef input_size, IntArrayRef output_size, + IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups +) { + return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups); +} + +inline Tensor reshape_bias(int64_t dim, const Tensor& bias) { + std::vector shape(dim, 1); + shape[1] = -1; + return bias.reshape(shape); +} + +// Shared logic for memory-format suggestions +// enabled: backend gate (compiled-with-X && not-float64). If false, return Contiguous. +// Dispatches by weight.ndim: 4 -> CL, 5 -> CL3d, else Contiguous. +inline at::MemoryFormat _conv_suggest_memory_format_impl( + const at::Tensor& input, const at::Tensor& weight, bool enabled) { + if (!enabled) { + return at::MemoryFormat::Contiguous; + } + auto input_mf = input.suggest_memory_format(); + auto weight_mf = weight.suggest_memory_format(); + auto weight_ndim = weight.ndimension(); + + if (weight_ndim == 4 && + (input_mf == at::MemoryFormat::ChannelsLast || + weight_mf == at::MemoryFormat::ChannelsLast)) { + return at::MemoryFormat::ChannelsLast; + } + if (weight_ndim == 5 && + (input_mf == at::MemoryFormat::ChannelsLast3d || + weight_mf == at::MemoryFormat::ChannelsLast3d)) { + return at::MemoryFormat::ChannelsLast3d; + } + return at::MemoryFormat::Contiguous; +} + +inline at::MemoryFormat cudnn_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) { + bool enabled = at::detail::getCUDAHooks().compiledWithCuDNN() && + input.scalar_type() != at::kDouble && weight.scalar_type() != at::kDouble; + return _conv_suggest_memory_format_impl(input, weight, enabled); +} + +// controls whether emptyCache will be called following cudnn conv benchmarking +TORCH_API void _cudnn_set_conv_benchmark_empty_cache(bool enable); +TORCH_API bool _cudnn_get_conv_benchmark_empty_cache(); + + +inline at::MemoryFormat miopen_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) { + bool enabled = at::detail::getCUDAHooks().compiledWithMIOpen() && + input.scalar_type() != at::kDouble && weight.scalar_type() != at::kDouble; + // TODO: Remove PYTORCH_MIOPEN_SUGGEST_NHWC once ROCm officially supports NHWC in MIOpen. + // See https://github.com/pytorch/pytorch/issues/64427. + // Non-static read so tests can toggle the env var at runtime. + enabled &= c10::utils::check_env("PYTORCH_MIOPEN_SUGGEST_NHWC").value_or(false); + return _conv_suggest_memory_format_impl(input, weight, enabled); +} + +// deprecated, but to remove would be BC-breaking +inline bool miopen_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) { + return miopen_conv_suggest_memory_format(input, weight) != at::MemoryFormat::Contiguous; +} + +// Shared "is either tensor channels-last (2d or 3d)?" check. +// enabled: backend gate (e.g. dtype/device checks) -- if false, return false. +// exact_match=true requires exact-stride classification (needed by MPS; +// see https://github.com/pytorch/pytorch/issues/180984 -- MPS reads raw +// buffers assuming packed NHWC, so misclassifying a channel slice or +// degenerate 1x1 weight would corrupt the read). +inline bool _conv_use_channels_last_impl( + const at::Tensor& input, const at::Tensor& weight, bool enabled, bool exact_match) { + if (!enabled) { + return false; + } + if (!input.defined() || input.is_sparse()) { + return false; + } + auto is_channel_last = [exact_match](const at::Tensor& t) { + auto fmt = t.suggest_memory_format(exact_match); + return fmt == at::MemoryFormat::ChannelsLast || fmt == at::MemoryFormat::ChannelsLast3d; + }; + return is_channel_last(input) || is_channel_last(weight); +} + +inline bool mkldnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) { + // Disable NHWC for float64 input and for MkldnnCPU tensors. + bool enabled = input.scalar_type() != at::kDouble && weight.scalar_type() != at::kDouble && + !input.is_mkldnn() && !weight.is_mkldnn(); + return _conv_use_channels_last_impl(input, weight, enabled, /*exact_match=*/false); +} + +inline bool thnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) { + + auto input_memory_format = input.suggest_memory_format(); + auto weight_memory_format = weight.suggest_memory_format(); + + bool can_use_thnn_channels_last_2d = input.device().is_cpu() && ( + (input_memory_format == at::MemoryFormat::ChannelsLast) || ( + weight_memory_format == at::MemoryFormat::ChannelsLast)); + + return can_use_thnn_channels_last_2d; +} + +inline bool xpu_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) { + return _conv_use_channels_last_impl( + input, weight, input.is_xpu() && weight.is_xpu(), /*exact_match=*/false); +} + +inline bool mps_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) { + return _conv_use_channels_last_impl( + input, weight, input.is_mps() && weight.is_mps(), /*exact_match=*/true); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Convolution.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Convolution.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c21b24fa287b229ab81e3656d38cfe70abb1a0a2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Convolution.cpp @@ -0,0 +1,2366 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#if AT_NNPACK_ENABLED() +#include +#endif + +#if AT_MKLDNN_ENABLED() +#include +#endif + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +constexpr int MIOPEN_DIM_MAX = 5; + +namespace at::native { + + +static constinit std::atomic conv_benchmark_empty_cache{true}; + +// Check workload to activate fast depthwise FP16 cudnn conv kernels +template +static bool check_cudnn_depthwise_workload(const at::Tensor& input, T stride) { + auto w = at::symint::size(input, 3); // same as h + auto ch = at::symint::size(input, 1); + auto bs = at::symint::size(input, 0); + if (stride==1) { + if (w >= 7) { + // All batch sizes and nb_channels + if (w >= 112) { + return true; + } + + // large nb_channels + if (ch >= 1024) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if (w >= 56) { + return true; + } else if (bs >= 32) { + return true; + } + } + + // batch_size specific + if (bs >= 128) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if (ch >= 512) { + return true; + } else if (ch >= 64) { + if (w >= 14) { + return true; + } + } else if ((ch >= 32) && (w >=28)) { + return true; + } + } else if (bs >= 64) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 256) && (w >= 14)) { + return true; + } else if ((ch >= 32) && (w >= 28)) { + return true; + } + } else if (bs >= 32) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 256) && (w >= 14)) { + return true; + } else if ((ch >= 128) && (w >= 28)) { + return true; + } else if ((ch >= 32) && (w >= 56)) { + return true; + } + } else if (bs >= 16) { + if ((ch >= 1024) && (w >= 14)) { + return true; + } + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 256) && (w >= 28)) { + return true; + } else if ((ch >= 32) && (w >= 56)) { + return true; + } + } else if (bs >= 8) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 512) && (w >= 28)) { + return true; + } else if ((ch >= 64) && (w >= 56)) { + return true; + } + } + } + } else if (stride==2) { + if (ch < 256) { + return false; + } + + if (w >= 7) { + if (bs >= 128) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if (ch >= 1024) { + return true; + } else if ((ch >= 512) && (w >= 14)) { + return true; + } else if (w >= 28) { + return true; + } + } else if (bs >= 64) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 512) && (w >= 14)) { + return true; + } else if (w >= 28) { + return true; + } + } else if (bs >= 32) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 1024) && (w >= 14)) { + return true; + } else if (w >= 28) { + return true; + } + } else if (bs >= 16) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 512) && (w >= 28)) { + return true; + } else if (w >= 56) { + return true; + } + } else if (bs >= 8) { + // NOLINTNEXTLINE(bugprone-branch-clone,cppcoreguidelines-avoid-magic-numbers) + if ((ch >= 1024) && (w >= 28)) { + return true; + } else if (w >= 56) { + return true; + } + } else if (bs >= 1) { + if ((ch >= 512) && (w >=112)) { + return true; + } + } + } + } + return false; +} + +// simplified version for cudnn 8.2 and above +template +static bool check_cudnn_depthwise_workload_with_filter(const at::Tensor& input, T stride, const at::Tensor& weight) { + // 1D conv + if(at::symint::size(input, 2) == 1 && stride == 1){ + return true; + } + + // 2d conv + // only square filters + if (at::symint::size(weight, 2) != at::symint::size(weight, 3)) return false; + auto filter = at::symint::size(weight, 3); + // only 1/3/5 filter + if (filter != 1 && filter != 3 && filter != 5) return false; + // we don't enforce square input but only check width to reduce heuristic space + if (at::symint::size(input, 3) < 7) return false; // min width 7 + auto w = at::symint::size(input, 3); + // only 1/2 stride, use cudnn for all stride 1 + if (stride == 1) return true; + if (stride != 2) return false; + + auto ch = at::symint::size(input, 1); + auto bs = at::symint::size(input, 0); + // special case since bs1 show good perf in lots of cases + if (bs == 1) { + if (filter == 1 && w <= 28) return true; + if (filter == 3 || filter == 5) return true; + } else { + if (filter == 1 && bs <= 16 && ch >= 128 && w <= 7) return true; + if (filter == 3 || filter == 5) { + if ((ch >= 512) || (ch >= 256 && w >= 28)) return true; + } + } + return false; +} + + +#if defined(C10_MOBILE) +static bool xnnpack_use_convolution2d( + const Tensor& input, + const Tensor& weight, + const at::OptionalIntArrayRef bias_sizes_opt, + const IntArrayRef padding, + const IntArrayRef stride, + const IntArrayRef dilation, + const int64_t groups, + const bool transposed) { + return xnnpack::use_convolution2d(input, weight, bias_sizes_opt, padding, stride, dilation, groups, transposed); +} + +static bool xnnpack_use_convolution2d( + const Tensor& input, + const Tensor& weight, + const at::OptionalSymIntArrayRef bias_sizes_opt, + const SymIntArrayRef padding, + const SymIntArrayRef stride, + const SymIntArrayRef dilation, + const c10::SymInt groups, + const bool transposed) { + // Never use xnnpack for symbolic tracing + return false; +} +#endif + +// This struct is templated so that we can run backend selection in a dynamic +// shapes context; all of the real kernel selection in eager mode runs with +// int64_t +template +struct ConvParams { + std::vector stride; + std::vector padding; + std::vector dilation; + bool transposed{}; + std::vector output_padding; + T groups{}; + bool benchmark{}; + bool deterministic{}; + bool cudnn_enabled{}; + bool allow_tf32{}; + + bool is_strided() const { + return std::any_of( + stride.cbegin(), stride.cend(), [](const T& s) { return s != 1; }); + } + + bool is_dilated() const { + return std::any_of( + dilation.cbegin(), dilation.cend(), [](const T& d) { return d != 1; }); + } + + bool is_padded() const { + return std::any_of( + padding.cbegin(), padding.cend(), [](const T& p) { return p != 0; }); + } + + bool is_output_padding_neg() const { + return std::any_of( + output_padding.cbegin(), + output_padding.cend(), + [](const T& p) { return p < 0; }); + } + + bool is_output_padding_big() const { + // Revisit this with std::views::zip at C++20. + for (auto i: c10::irange(output_padding.size())) { + if (output_padding[i] >= stride[i]) { + return true; + } + } + return false; + } + + bool is_padding_neg() const { + return std::any_of( + padding.cbegin(), padding.cend(), [](const T& p) { return p < 0; }); + } + + bool is_dilation_neg() const { + return std::any_of( + dilation.cbegin(), dilation.cend(), [](const T& d) { return d < 0; }); + } + + bool is_stride_nonpos() const { + return std::any_of( + stride.cbegin(), stride.cend(), [](const T& s) { return s <= 0; }); + } + + void view1d_as_2d() { + if (stride.size() == 1) { + stride.insert(stride.begin(), 1); + padding.insert(padding.begin(), 0); + dilation.insert(dilation.begin(), 1); + output_padding.insert(output_padding.begin(), 0); + } + } + + bool use_cpu_depthwise3x3_winograd(const at::Tensor& input, const at::Tensor& weight, const std::optional& bias) const { +#if defined(__ARM_NEON__) || (defined(__riscv_v_intrinsic) && __riscv_v_intrinsic>=12000) + // Currently only 3x3 depthwise convolutions on tensors of float are supported. + return (input.ndimension() == 4) && + (at::symint::size(input, 1) == groups) && + (weight.ndimension() == 4 ) && + (at::symint::size(weight, 0) % at::symint::size(input, 1) == 0) && + (at::symint::size(weight, 1) == 1) && + (at::symint::size(weight, 2) == 3) && + (at::symint::size(weight, 3) == 3) && + (input.device().is_cpu()) && + (input.scalar_type() == at::kFloat) && + input.is_contiguous() && + (weight.device().is_cpu()) && + (weight.scalar_type() == at::kFloat) && + weight.is_contiguous() && + (!bias.has_value() || bias->is_contiguous()) && + !is_strided() && + !is_dilated() && + !transposed; +#else + return false; +#endif + } + + bool needs_64bit_indexing_no_split(const at::Tensor& input, const at::Tensor& weight) const { + constexpr int64_t int_max = std::numeric_limits::max(); + auto numel_input = at::symint::numel(input); + // empty input + if (numel_input == 0) { + return false; + } + // input size can not be reduced to the range of int by splitting the batch dim + auto n = at::symint::size(input, 0); + if (numel_input / n > int_max) { + return true; + } + // output size can not be reduced to the range of int by splitting the batch dim + T outsize = 1; + if (transposed) { + auto o = conv_input_size(at::symint::sizes(input), at::symint::sizes(weight), padding, output_padding, stride, dilation, groups); + outsize = c10::multiply_integers(o.begin() + 1, o.end()); + } else { + auto o = conv_output_size(at::symint::sizes(input), at::symint::sizes(weight), padding, stride, dilation); + outsize = c10::multiply_integers(o.begin() + 1, o.end()); + } + return outsize > int_max; + } + + bool use_cudnn(const at::Tensor& input, const at::Tensor& weight) const { + // Note [Mobile check segfaults] + // cudnn and miopen are guaranteed not to be on mobile, and T102591915 / T110194934 suggest + // that maybe the compiledWithCuDNN() check sometimes segfaults (though I can't imagine how) +#if !defined(C10_MOBILE) + if (!detail::getCUDAHooks().compiledWithCuDNN() || !input.is_cuda() || !cudnn_enabled) { + return false; + } + static long cudnn_version = detail::getCUDAHooks().versionRuntimeCuDNN(); + if (needs_64bit_indexing_no_split(input, weight)) { + if (!(cudnn_version >= 90300 && at::native::cudnnv8_enabled_check_debug())) { + TORCH_WARN_ONCE("cuDNN cannot be used for large non-batch-splittable convolutions" + " if the V8 API is not enabled or before cuDNN version 9.3+." + " Consider upgrading cuDNN and/or enabling the V8 API for better efficiency."); + return false; + } + } + if (input.scalar_type() == at::kBFloat16 || weight.scalar_type() == at::kBFloat16) { + if (!(detail::getCUDAHooks().supportsBFloat16ConvolutionWithCuDNNv8() && at::native::cudnnv8_enabled_check_debug())) { + return false; + } + } + if (cudnn_conv_suggest_memory_format(input, weight) == at::MemoryFormat::Contiguous) { + if (is_dilated()) { + return detail::getCUDAHooks().supportsDilatedConvolutionWithCuDNN() && !is_output_padding_big(); + } + } + return !is_output_padding_big(); +#else + return false; +#endif + } + + // Use cudnn for FP16 depthwise convolutions + bool use_cudnn_depthwise(const at::Tensor& input, const at::Tensor& weight) const { + if (!cudnn_enabled || !detail::getCUDAHooks().compiledWithCuDNN() || !input.is_cuda()) { + return false; + } + // native kernel doesn't support 64-bit non-splittable case + if (!(canUse32BitIndexMath(input) && canUse32BitIndexMath(weight))) { + static long cudnn_version = detail::getCUDAHooks().compiledWithCuDNN() ? detail::getCUDAHooks().versionRuntimeCuDNN() : -1; + // TODO(eqy): remove this once cuDNN fixes 64-bit depthwise support, first broken in 9.11x + if (cudnn_conv_suggest_memory_format(input, weight) != at::MemoryFormat::Contiguous) { + if (cudnn_version < 0 || (cudnn_version > 91000 && cudnn_version < 91500)) { + return false; + } + } + + if (!(cudnn_version >= 90300 && at::native::cudnnv8_enabled_check_debug())) { + TORCH_WARN_ONCE("cuDNN cannot be used for large non-batch-splittable convolutions" + " if the V8 API is not enabled or before cuDNN version 9.3+." + " Upgrade cuDNN or enable the V8 API to use cuDNN for 64-bit depthwise convolutions."); + return false; + } else { + return true; + } + } + if (cudnn_conv_suggest_memory_format(input, weight) != at::MemoryFormat::Contiguous) { + // always use cudnn_depthwise for channels_last format + return true; + } + if (detail::getCUDAHooks().supportsDepthwiseConvolutionWithCuDNN()) { + bool kernel_cond = (use_cudnn(input, weight) && + input.scalar_type() == kHalf && // only for FP16 + weight.scalar_type() == kHalf && + is_depthwise(input, weight) && + input.ndimension() == 4 && // TODO: 5-D contiguous depthwise is not supported yet, need benchmarks + !is_dilated() && // no dilation supported + (stride[0] == stride[1] || at::symint::size(input, 2) == 1) && // square or 1d + at::symint::size(input, 1) >= 32); // min 32 channels supported) + if (kernel_cond) { + auto depthwise_kernel = at::globalContext().cudnnDepthwiseKernel(); + if (depthwise_kernel == at::CuDNNDepthwiseKernel::NATIVE) { + return false; + } else if (depthwise_kernel == at::CuDNNDepthwiseKernel::CUDNN) { + return true; + } + return check_cudnn_depthwise_workload_with_filter(input, stride[1], weight); + } + return false; + } else { + return false; + } + } + + bool use_miopen(const at::Tensor& input, const at::Tensor& weight, bool bias_defined) const { + // MIOpen supports 64-bit indexing via miopenSetTensorDescriptorV2 API + // Reference: https://github.com/ROCm/MIOpen/pull/2838 + return ((input.scalar_type() == at::kFloat) || (input.scalar_type() == at::kHalf) || (input.scalar_type() == at::kBFloat16)) + && cudnn_enabled + && input.is_cuda() + && detail::getCUDAHooks().compiledWithMIOpen() + && input.dim() <= MIOPEN_DIM_MAX + && !(groups > 1 && is_dilated()) // MIOpen currently does not support dilation with groups of size > 1 + ; + } + bool use_mkldnn(const at::Tensor& input, const at::Tensor& weight) const { +#if AT_MKLDNN_ENABLED() + if (!at::globalContext().userEnabledMkldnn()) { + return false; + } + if (transposed && is_output_padding_big()) { + return false; + } + if (input.device().is_cpu() && + ((input.scalar_type() == at::kBFloat16 && mkldnn_bf16_device_check()) || + (input.scalar_type() == at::kHalf && mkldnn_fp16_device_check()))) { + return true; + } + return (input.is_mkldnn()) || // input is mkldnn Tensor + (input.device().is_cpu() && + input.scalar_type() == kFloat && // only on CPU Float Tensors + // For 1x1 filters, MKLDNN is faster than THNN when multi-threaded, + // but THNN is faster when single-threaded. + [&]() { + if constexpr (std::is_same_v) { + return is_strided() || is_dilated() || + TORCH_GUARD_OR_FALSE(at::symint::size(input, 0).sym_ge(16)) || + TORCH_GUARD_OR_FALSE(at::symint::size(weight, -1).sym_ne(1)) || + TORCH_GUARD_OR_FALSE(at::symint::size(weight, -2).sym_ne(1)) || + at::get_num_threads() > 1; + } else { + return is_strided() || is_dilated() || + at::symint::size(input, 0) >= 16 || + at::symint::size(weight, -1) != 1 || + at::symint::size(weight, -2) != 1 || + at::get_num_threads() > 1; + } + }() && + [&]() { + if constexpr (std::is_same_v) { + return groups > 1 + || (TORCH_GUARD_OR_FALSE(at::symint::size(weight, -1).sym_gt(3)) && + TORCH_GUARD_OR_FALSE(at::symint::size(weight, -2).sym_gt(3))) + || TORCH_GUARD_OR_FALSE(at::symint::size(input, 0).sym_gt(1)) + || TORCH_GUARD_OR_FALSE((at::symint::size(input, 0)*at::symint::size(input, 1)*at::symint::size(input, 2)*at::symint::size(input, 3)).sym_gt(20480)); + } else { + return groups > 1 + || (at::symint::size(weight, -1) > 3 && at::symint::size(weight, -2) > 3) + || at::symint::size(input, 0) > 1 + || at::symint::size(input, 0)*at::symint::size(input, 1)*at::symint::size(input, 2)*at::symint::size(input, 3) > 20480; + } + }() // for some case, native is faster + ); + +#endif + return false; + } + bool use_nnpack(const at::Tensor& input, const at::Tensor& weight) const { +#if AT_NNPACK_ENABLED() + return at::globalContext().userEnabledNNPACK() && + at::_nnpack_available() && + input.device().is_cpu() && + input.scalar_type() == kFloat && // only on CPU Float Tensors + !is_dilated() && // or dilation + !transposed && // or transposed tensors + input.ndimension() == 4 && // must be in NCHW format + weight.ndimension() == 4 && + (at::symint::size(weight, 2) < 17) && (at::symint::size(weight, 3) < 17) && // NNPACK only supports kernels up to 16x16 + (padding[0] < at::symint::size(weight, 2)) && (padding[1] < at::symint::size(weight, 3)) // NNPACK only supports padding < kernel_size. See https://github.com/pytorch/pytorch/issues/90142. +#if !defined(C10_MOBILE) + && at::symint::size(input, 0) >= 16 // ensure large enough batch size to ensure perf, tuneable +#endif + ; +#endif + return false; + } + bool use_xnnpack(const at::Tensor& input, const at::Tensor& weight, + const at::OptionalArrayRef bias_sizes_opt) const { +#if defined(C10_MOBILE) + if (!transposed) { + // NB: for the call here, it MATTERS that we are templated. If you + // untemplate this to always use SymInt, the function + // xnnpack_use_convolution2d will always return false + return (at::symint::size(input, 1) == groups) && + xnnpack_use_convolution2d( + input, + weight, + bias_sizes_opt, + padding, + stride, + dilation, + groups, + transposed); + } +#endif + return false; + } + + bool use_mps(const at::Tensor& input, const at::Tensor& weight) const { + // These checks need to be expanded. Currently we have very limited set of + // checks for MPS. +#ifdef USE_MPS + if (needs_64bit_indexing_no_split(input, weight)) { + return false; + } + if (!input.is_mps()) { + return false; + } + return true; +#else + return false; +#endif + } + + // We currently only have depthwise support for the case where groups == + // nInputPlane and nInputPlane == nOutputPlane (the latter due to the lack of + // a depthwise multiplier) + bool is_depthwise(const at::Tensor& input, const at::Tensor& weight) const { + return input.is_cuda() && + !transposed && + (input.ndimension() == 4 || input.ndimension() == 5) && + at::symint::size(input, 1) == groups && + groups > 1 && // no point if there is only a single group + at::symint::size(weight, 0) % at::symint::size(input, 1) == 0; // output channels must be a multiple of input channels + } +}; + +DEFINE_DISPATCH(conv_depthwise2d_backward_stub); +DEFINE_DISPATCH(conv_depthwise3d_backward_stub); +DEFINE_DISPATCH(cudnn_convolution_backward_stub); +DEFINE_DISPATCH(cudnn_convolution_transpose_backward_stub); +DEFINE_DISPATCH(slow_conv_transpose3d_backward_stub); +DEFINE_DISPATCH(convolution_depthwise3x3_winograd_stub); +DEFINE_DISPATCH(miopen_convolution_backward_stub); +DEFINE_DISPATCH(miopen_convolution_transpose_backward_stub); +DEFINE_DISPATCH(miopen_depthwise_convolution_backward_stub); +DEFINE_DISPATCH(mkldnn_convolution_backward_stub); +DEFINE_DISPATCH(mkldnn_convolution_transpose_stub); +DEFINE_DISPATCH(mkldnn_convolution_transpose_backward_stub); +DEFINE_DISPATCH(slow_conv_dilated2d_backward_stub); +DEFINE_DISPATCH(slow_conv_dilated3d_backward_stub); +DEFINE_DISPATCH(slow_conv_transpose2d_backward_stub); +REGISTER_NO_CPU_DISPATCH(conv_depthwise2d_backward_stub) +REGISTER_NO_CPU_DISPATCH(conv_depthwise3d_backward_stub) +REGISTER_NO_CPU_DISPATCH(cudnn_convolution_backward_stub) +REGISTER_NO_CPU_DISPATCH(cudnn_convolution_transpose_backward_stub) +REGISTER_NO_CPU_DISPATCH(miopen_convolution_backward_stub) +REGISTER_NO_CPU_DISPATCH(miopen_convolution_transpose_backward_stub) +REGISTER_NO_CPU_DISPATCH(miopen_depthwise_convolution_backward_stub) + +template +static std::ostream& operator<<(std::ostream & out, const ConvParams& params) { + out << "ConvParams {" + << " stride = " << IntArrayRef{params.stride} + << " padding = " << ArrayRef{params.padding} + << " dilation = " << IntArrayRef{params.dilation} + << " transposed = " << params.transposed + << " output_padding = " << ArrayRef{params.output_padding} + << " groups = " << params.groups + << " benchmark = " << params.benchmark + << " deterministic = " << params.deterministic + << " cudnn_enabled = " << params.cudnn_enabled + << " allow_tf32 = " << params.allow_tf32 + << '}'; + return out; +} + +template +static void check_shape_forward(const at::Tensor& input, + const c10::ArrayRef& weight_sizes, const at::Tensor& bias, + const ConvParams& params) { + int64_t k = input.ndimension(); + int64_t weight_dim = weight_sizes.size(); + auto groups = params.groups; + const auto& padding = params.padding; + const auto& dilation = params.dilation; + bool transposed = params.transposed; + + TORCH_CHECK(!params.is_padding_neg(), "negative padding is not supported"); + TORCH_CHECK(!params.is_output_padding_neg(), "negative output_padding is not supported"); + TORCH_CHECK(!params.is_stride_nonpos(), "non-positive stride is not supported"); + TORCH_CHECK(!params.is_dilation_neg(), "dilation should be greater than zero"); + TORCH_CHECK(groups > 0, "expected groups to be greater than 0, but got groups=", groups); + + TORCH_CHECK(weight_dim == k, + "Expected ", weight_dim, "-dimensional input for ", weight_dim, + "-dimensional weight ", weight_sizes, ", but got ", k, "-dimensional input of size ", + at::symint::sizes(input), " instead"); + if constexpr (std::is_same_v) { + TORCH_SYM_CHECK(weight_sizes[0].sym_ge(groups), + "Given groups=", groups, ", expected weight to be at least ", groups, + " at dimension 0, but got weight of size ", weight_sizes, " instead"); + TORCH_SYM_CHECK((weight_sizes[0] % groups).sym_eq(0), + "Given groups=", groups, ", expected weight to be divisible by ", + groups, " at dimension 0, but got weight of size [", weight_sizes, + "] instead"); + } else { + TORCH_CHECK(weight_sizes[0] >= groups, + "Given groups=", groups, ", expected weight to be at least ", groups, + " at dimension 0, but got weight of size ", weight_sizes, " instead"); + TORCH_CHECK(weight_sizes[0] % groups == 0, + "Given groups=", groups, ", expected weight to be divisible by ", + groups, " at dimension 0, but got weight of size [", weight_sizes, + "] instead"); + } + + if (!transposed) { + std::vector input_shape; + std::vector kernel_shape; + if (k > 2) { + input_shape.reserve(k - 2); + kernel_shape.reserve(k - 2); + } + bool kernel_size_correct = true; + + if constexpr (std::is_same_v) { + TORCH_SYM_CHECK(at::symint::size(input, 1).sym_eq(weight_sizes[1] * groups), + "Given groups=", groups, ", weight of size ", weight_sizes, + ", expected input", at::symint::sizes(input), " to have ", + (weight_sizes[1] * groups), " channels, but got ", at::symint::size(input, 1), + " channels instead"); + + TORCH_CHECK(!bias.defined() || (bias.ndimension() == 1 && + at::symint::size(bias, 0).sym_eq(weight_sizes[0]).expect_true(__FILE__, __LINE__)), + "Given weight of size ", weight_sizes, + ", expected bias to be 1-dimensional with ", weight_sizes[0], " elements", + ", but got bias of size ", at::symint::sizes(bias), " instead"); + } else { + TORCH_CHECK(at::symint::size(input, 1) == (weight_sizes[1] * groups), + "Given groups=", groups, ", weight of size ", weight_sizes, + ", expected input", at::symint::sizes(input), " to have ", + (weight_sizes[1] * groups), " channels, but got ", at::symint::size(input, 1), + " channels instead"); + + TORCH_CHECK(!bias.defined() || (bias.ndimension() == 1 && at::symint::size(bias, 0) == weight_sizes[0]), + "Given weight of size ", weight_sizes, + ", expected bias to be 1-dimensional with ", weight_sizes[0], " elements", + ", but got bias of size ", at::symint::sizes(bias), " instead"); + } + + for (const auto i : c10::irange(2, k)) { + // T could be int64_t or SymInt, Specialized numeric_limts in c10/core/SymInt.h + TORCH_CHECK(padding[i-2] <= (std::numeric_limits::max() - padding[i-2]), + "Given padding=", padding[i-2], " at dimension ", i-2, " , expected padding to be at most ", + (std::numeric_limits::max() / 2)); + input_shape.push_back(at::symint::size(input, i) + 2 * padding[i-2]); + // log new kernel size considering dilation + kernel_shape.push_back(dilation[i-2] * (weight_sizes[i]-1) + 1); + if constexpr (std::is_same_v) { + if (TORCH_GUARD_OR_FALSE(input_shape.back().sym_lt(kernel_shape.back()))) { + kernel_size_correct = false; + } + } else { + if (input_shape.back() < kernel_shape.back()) { + kernel_size_correct = false; + } + } + } + + TORCH_CHECK(input_shape.size() == kernel_shape.size(), "Inconsistent shape between Input and Kernel"); + + if (!kernel_size_correct) { + // If kernel size is incorrect + std::ostringstream input_ss; + std::ostringstream kernel_ss; + std::string separator; + + for (int i = 0, len = input_shape.size(); i < len; ++i) { + input_ss << separator << input_shape[i]; + kernel_ss << separator << kernel_shape[i]; + separator = " x "; + } + + TORCH_CHECK(false, "Calculated padded input size per channel: (", input_ss.str(), "). " + "Kernel size: (", kernel_ss.str(), "). Kernel size can't be greater than actual input size"); + } + } else { // transposed + for (const auto i : c10::irange(2, k)) { + TORCH_CHECK(padding[i-2] <= (std::numeric_limits::max() - padding[i-2]), + "Given padding=", padding[i-2], " at dimension ", i-2, " , expected padding to be at most ", + (std::numeric_limits::max() / 2)); + } + if constexpr (std::is_same_v) { + TORCH_SYM_CHECK(at::symint::size(input, 1).sym_eq(weight_sizes[0]), + "Given transposed=", transposed, ", weight of size ", weight_sizes, + ", expected input", at::symint::sizes(input), " to have ", weight_sizes[0], + " channels, but got ", at::symint::size(input, 1), " channels instead"); + TORCH_CHECK(!bias.defined() || (bias.ndimension() == 1 && + at::symint::size(bias, 0).sym_eq(weight_sizes[1] * groups).expect_true(__FILE__, __LINE__)), + "Given transposed=", transposed, ", weight of size ", weight_sizes, + ", expected bias to be 1-dimensional with ", weight_sizes[1] * groups, " elements", + ", but got bias of size ", at::symint::sizes(bias), " instead"); + } else { + TORCH_CHECK(at::symint::size(input, 1) == weight_sizes[0], + "Given transposed=", transposed, ", weight of size ", weight_sizes, + ", expected input", at::symint::sizes(input), " to have ", weight_sizes[0], + " channels, but got ", at::symint::size(input, 1), " channels instead"); + TORCH_CHECK(!bias.defined() || (bias.ndimension() == 1 && at::symint::size(bias, 0) == weight_sizes[1] * groups), + "Given transposed=", transposed, ", weight of size ", weight_sizes, + ", expected bias to be 1-dimensional with ", weight_sizes[1] * groups, " elements", + ", but got bias of size ", at::symint::sizes(bias), " instead"); + } + } +} + +template +static void check_shape_backward( + const at::Tensor& input, + const c10::ArrayRef& weight_sizes, + const ConvParams& params) { + check_shape_forward(input, weight_sizes, /*bias=*/ Tensor(), params); +} + +// Given an input tensor and an expected number of spatial dimensions, checks that the +// input is a valid shape and returns the batched form of the input. +// +// Args: +// input (Tensor): Input tensor +// num_spatial_dims (int): Number of spatial dimensions expected for the input +// func_name (string): Function name to produce a nice error message for invalid input +// +// Returns a std::tuple containing: +// batched_input (Tensor): Input with a batch dimension +// is_batched (bool): Indicates whether the original input was already batched +static std::tuple batchify( + const Tensor& input, + const int64_t num_spatial_dims, + const std::string& func_name) { + // assume NTs are always batched + if (input.is_nested()) { + return std::make_tuple(input, true); + } + const auto dim_count_no_batch = num_spatial_dims + 1; + const auto dim_count_batch = dim_count_no_batch + 1; + const auto is_batched = (input.dim() == dim_count_batch); + TORCH_CHECK(input.dim() == dim_count_no_batch || is_batched, + "Expected ", dim_count_no_batch, "D (unbatched) or ", dim_count_batch, + "D (batched) input to ", func_name, ", but got input of size: ", input.sizes()); + return std::make_tuple(is_batched ? input : input.unsqueeze(0), is_batched); +} + +static void check_input_same_type_as_parameters( + const Tensor& input, + const Tensor& weight, + const Tensor& bias) { + TORCH_CHECK(input.options().type_equal(weight.options()), + "Input type (", input.toString(), ") and weight type (", weight.toString(), + ") should be the same"); + TORCH_CHECK(!bias.defined() || (input.options().type_equal(bias.options())), + "Input type (", input.toString(), ") and bias type (", bias.toString(), + ") should be the same"); +} + +static void check_input_same_type_as_parameters( + const Tensor& input, + const Tensor& weight) { + check_input_same_type_as_parameters(input, weight, /*bias=*/ Tensor()); +} + +#if AT_MKLDNN_ENABLED() +static void check_input_same_type_as_parameters( + const Tensor& input, + const Tensor& weight, + const Tensor& bias, + const ConvBackend backend) { + if (backend == ConvBackend::Mkldnn || backend == ConvBackend::MkldnnTranspose) { + TORCH_CHECK(input.options().type_equal(weight.options()) + || (input.is_mkldnn() && weight.device().is_cpu() && weight.scalar_type() == kFloat), + "Input type (", input.toString(), ") and weight type (", weight.toString(), + ") should be the same or input should be a MKLDNN tensor and weight is a dense tensor"); + TORCH_CHECK(!bias.defined() || (input.options().type_equal(bias.options())) + || (input.is_mkldnn() && bias.device().is_cpu() && bias.scalar_type() == kFloat), + "Input type (", input.toString(), ") and bias type (", bias.toString(), + ") should be the same or input should be a MKLDNN tensor and bias is a dense tensor"); + } else { + check_input_same_type_as_parameters(input, weight, bias); + } +} +#endif + +static auto view4d(const at::Tensor& tensor) -> at::Tensor { + TORCH_CHECK(tensor.ndimension() == 3, + "expected 3D tensor, got tensor with ", tensor.ndimension(), + " dimensions instead"); + return tensor.unsqueeze(2); +} + +static auto view3d(const at::Tensor& tensor) -> at::Tensor { + TORCH_CHECK(tensor.ndimension() == 4, + "expected 4D tensor, got tensor with ", tensor.ndimension(), + " dimensions instead"); + return tensor.squeeze(2); +} + +static at::Tensor subtensor(at::Tensor& tensor, int64_t dim, int64_t groups, int64_t g) { + if (!tensor.defined()) { + return at::Tensor(); + } + const auto memory_format = tensor.suggest_memory_format(); + int64_t n = tensor.sizes()[dim] / groups; + return tensor.narrow(dim, n * g, n).contiguous(memory_format); +} + +namespace { + +std::pair complex_to_real(const Tensor& inp) { + auto inp_view_as_complex = at::view_as_real(inp); + auto dim_i = inp_view_as_complex.dim() - 1; + auto i_r = inp_view_as_complex.select(dim_i, 0); + auto i_i = inp_view_as_complex.select(dim_i, 1); + return std::make_pair(i_r, i_i); +} + +at::Tensor complex_convolution( + const Tensor& input, + const Tensor& weight, + const Tensor& bias, + SymIntArrayRef stride, + SymIntArrayRef padding, + SymIntArrayRef dilation, + bool transposed, + SymIntArrayRef output_padding, + const c10::SymInt& groups) { + check_input_same_type_as_parameters(input, weight, bias); + auto [i_r, i_i] = complex_to_real(input.resolve_conj()); + auto [w_r, w_i] = complex_to_real(weight.resolve_conj()); + + // [NOTE] Complex Convolution + // conv(W, x, b) = conv(Wr, xr, br) - conv(Wi, xi, 0) + i(conv(Wi, xr, bi) + conv(Wr, xi, 0)) + // where W, x and b are all complex inputs. + // With Gauss Trick: + // a = conv(Wr, xr, br), + // b = conv(Wi, xi, 0), + // c = conv(Wr + Wi, xr + xi, bi + br) + // conv(W, x, b) = a - b + i(c - a - b) + Tensor a, b, c; + if (!bias.defined()) { + a = at::convolution_symint(i_r, w_r, bias, stride, padding, dilation, transposed, output_padding, groups); + b = at::convolution_symint(i_i, w_i, bias, stride, padding, dilation, transposed, output_padding, groups); + c = at::convolution_symint(i_r + i_i, w_r + w_i, bias, stride, padding, dilation, transposed, output_padding, groups); + } else { + auto [b_r, b_i] = complex_to_real(bias.resolve_conj()); + a = at::convolution_symint(i_r, w_r, b_r, stride, padding, dilation, transposed, output_padding, groups); + b = at::convolution_symint(i_i, w_i, Tensor(), stride, padding, dilation, transposed, output_padding, groups); + c = at::convolution_symint(i_r + i_i, w_r + w_i, b_r + b_i, stride, padding, dilation, transposed, output_padding, groups); + } + + auto i = c10::Scalar(c10::complex(0, 1)); + return a - b + i * (c - a - b); +} + +at::Tensor complex_convolution_mode( + const at::Tensor& input, + const at::Tensor& weight, + const std::optional& bias_opt, + c10::SymIntArrayRef stride, + std::string_view padding, + c10::SymIntArrayRef dilation, + const c10::SymInt& groups) { + auto bias = bias_opt.value_or(Tensor()); + check_input_same_type_as_parameters(input, weight, bias); + auto [i_r, i_i] = complex_to_real(input.resolve_conj()); + auto [w_r, w_i] = complex_to_real(weight.resolve_conj()); + + // See [NOTE] Complex Convolution + Tensor a, b, c; + if (!bias.defined()) { + a = at::_convolution_mode_symint(i_r, w_r, bias, stride, padding, dilation, groups); + b = at::_convolution_mode_symint(i_i, w_i, bias, stride, padding, dilation, groups); + c = at::_convolution_mode_symint(i_r + i_i, w_r + w_i, bias, stride, padding, dilation, groups); + } else { + auto [b_r, b_i] = complex_to_real(bias.resolve_conj()); + a = at::_convolution_mode_symint(i_r, w_r, b_r, stride, padding, dilation, groups); + b = at::_convolution_mode_symint(i_i, w_i, Tensor(), stride, padding, dilation, groups); + c = at::_convolution_mode_symint(i_r + i_i, w_r + w_i, b_r + b_i, stride, padding, dilation, groups); + } + + auto i = c10::Scalar(c10::complex(0, 1)); + return a - b + i * (c - a - b); +} + +} // namespace + +at::Tensor conv1d_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef dilation, c10::SymInt groups) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + TORCH_CHECK( + !bias.defined() || bias.dtype() == input_.dtype(), + "Input type (", + input_.dtype().name(), + ") and bias type (", + bias.dtype().name(), + ") should be the same"); + + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 1, "conv1d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution(input, weight, bias, stride, padding, dilation, false, {0}, groups); + } else { + output = at::convolution_symint(input, weight, bias, stride, padding, dilation, false, {0}, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv2d_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef dilation, c10::SymInt groups) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + TORCH_CHECK( + !bias.defined() || bias.dtype() == input_.dtype(), + "Input type (", + input_.dtype().name(), + ") and bias type (", + bias.dtype().name(), + ") should be the same"); + + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 2, "conv2d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution(input, weight, bias, stride, padding, dilation, false, {{0, 0}}, groups); + } else { + output = at::convolution_symint(input, weight, bias, stride, padding, dilation, false, {{0, 0}}, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv3d_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef dilation, c10::SymInt groups) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + TORCH_CHECK( + !bias.defined() || bias.dtype() == input_.dtype(), + "Input type (", + input_.dtype().name(), + ") and bias type (", + bias.dtype().name(), + ") should be the same"); + + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 3, "conv3d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution(input, weight, bias, stride, padding, dilation, false, {{0, 0, 0}}, groups); + } else { + output = at::convolution_symint(input, weight, bias, stride, padding, dilation, false, {{0, 0, 0}}, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + + +static Tensor convolution_same( + const Tensor &input, const Tensor &weight, const Tensor &bias, + SymIntArrayRef stride, SymIntArrayRef dilation, const c10::SymInt& groups) { + + auto k = weight.dim(); + TORCH_CHECK(k > 2, "weight should have at least three dimensions"); + TORCH_CHECK(groups > 0, "non-positive groups is not supported"); + auto dim = static_cast(k - 2); + auto weight_sizes = weight.sym_sizes(); + auto input_sizes = input.sym_sizes(); + TORCH_CHECK(k == input.dim(), + "Expected ", k, "-dimensional input for ", + k, "-dimensional weight", weight_sizes, ", but got ", + input.dim(), "-dimensional input of size ", + input.sizes(), " instead"); + TORCH_CHECK(stride.size() == dim || stride.size() == 1U, + "stride cannot broadcast to ", dim, " dimensions"); + TORCH_CHECK(dilation.size() == dim || dilation.size() == 1U, + "dilation cannot broadcast to ", dim, " dimensions"); + for (auto i: c10::irange(stride.size())) { + TORCH_CHECK(stride[i] == 1, "padding='same' is not supported for strided convolutions"); + } + + // Calculate the correct padding + SymDimVector padding_l, padding_r; + bool symmetric_padding = true; + for (auto i: c10::irange(dim)) { + auto s = stride.size() == 1 ? stride[0] : stride[i]; + auto d = dilation.size() == 1 ? dilation[0] : dilation[i]; + auto pad = pooling_same_mode_padding_lr( + input_sizes[i + 2], weight_sizes[i + 2], s, d); + padding_l.push_back(pad.first); + padding_r.push_back(pad.second); + if (!TORCH_GUARD_OR_FALSE(pad.first.sym_eq(pad.second))) { + symmetric_padding = false; + } + } + + if (symmetric_padding) { + // All backends handle symmetric padding natively + SymDimVector output_padding(dim); + return at::convolution_symint(input, weight, bias, stride, padding_l, dilation, + false, output_padding, groups); + } + + TORCH_WARN_ONCE("Using padding='same' with even kernel lengths and odd dilation may" + " require a zero-padded copy of the input be created"); + SmallVector pad_nd(static_cast(2 * dim)); + for (auto i: c10::irange(dim)) { + // pad_r >= pad_l always (floor division), so pad the right side by the + // difference and use pad_l as the symmetric base for convolution. + auto pad_idx = 2 * (dim - 1 - i); // F.pad goes from last dim to first + pad_nd[pad_idx + 1] = padding_r[i] - padding_l[i]; + } + auto padded_input = at::constant_pad_nd_symint(input, pad_nd, 0); + SymDimVector output_padding(dim); + return at::convolution_symint(padded_input, weight, bias, stride, padding_l, + dilation, false, output_padding, groups); +} + +Tensor _convolution_mode_symint( + const Tensor& input, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, std::string_view padding, SymIntArrayRef dilation, + c10::SymInt groups) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + if (padding == "same") { + return at::native::convolution_same( + input, weight, bias, stride, dilation, groups); + } else if (padding == "valid") { + return at::convolution_symint( + input, weight, bias, stride, {{0}}, dilation, false, {{0}}, groups); + } + TORCH_CHECK(false, "Invalid padding string: '", padding, "'"); +} + +at::Tensor conv1d_padding_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias, + c10::SymIntArrayRef stride, std::string_view padding, c10::SymIntArrayRef dilation, + c10::SymInt groups) { + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 1, "conv1d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution_mode(input, weight, bias, stride, padding, dilation, groups); + } else { + output = at::_convolution_mode_symint(input, weight, bias, stride, padding, dilation, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv2d_padding_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias, + c10::SymIntArrayRef stride, std::string_view padding, c10::SymIntArrayRef dilation, + c10::SymInt groups) { + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 2, "conv2d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution_mode(input, weight, bias, stride, padding, dilation, groups); + } else { + output = at::_convolution_mode_symint(input, weight, bias, stride, padding, dilation, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv3d_padding_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias, + c10::SymIntArrayRef stride, std::string_view padding, c10::SymIntArrayRef dilation, + c10::SymInt groups) { + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 3, "conv3d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution_mode(input, weight, bias, stride, padding, dilation, groups); + } else { + output = at::_convolution_mode_symint(input, weight, bias, stride, padding, dilation, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv_transpose1d_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef output_padding, c10::SymInt groups, SymIntArrayRef dilation) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 1, "conv_transpose1d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution( + input, weight, bias, stride, padding, dilation, true, output_padding, groups); + } else { + output = at::convolution_symint( + input, weight, bias, stride, padding, dilation, true, output_padding, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv_transpose2d_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef output_padding, c10::SymInt groups, SymIntArrayRef dilation) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 2, "conv_transpose2d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution( + input, weight, bias, stride, padding, dilation, true, output_padding, groups); + } else { + output = at::convolution_symint( + input, weight, bias, stride, padding, dilation, true, output_padding, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor conv_transpose3d_symint( + const Tensor& input_, const Tensor& weight, const std::optional& bias_opt, + SymIntArrayRef stride, SymIntArrayRef padding, SymIntArrayRef output_padding, c10::SymInt groups, SymIntArrayRef dilation) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto [input, is_batched] = batchify(input_, /*num_spatial_dims=*/ 3, "conv_transpose3d"); + Tensor output; + if (at::isComplexType(input_.scalar_type())) { + output = complex_convolution( + input, weight, bias, stride, padding, dilation, true, output_padding, groups); + } else { + output = at::convolution_symint( + input, weight, bias, stride, padding, dilation, true, output_padding, groups); + } + return is_batched ? std::move(output) : output.squeeze(0); +} + +at::Tensor convolution( + const Tensor& input, const Tensor& weight, const std::optional& bias_opt, + IntArrayRef stride, IntArrayRef padding, IntArrayRef dilation, + bool transposed, IntArrayRef output_padding, int64_t groups) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto& ctx = at::globalContext(); + // See Note [Enabling Deterministic Operations] + bool deterministic = ctx.deterministicCuDNN() || ctx.deterministicAlgorithms(); + return at::_convolution(input, weight, bias, stride, padding, dilation, + transposed, output_padding, groups, + ctx.benchmarkCuDNN(), deterministic, ctx.userEnabledCuDNN(), ctx.allowTF32CuDNN(at::Float32Op::CONV)); +} + +at::Tensor convolution_overrideable( + const Tensor& input, const Tensor& weight, const std::optional& bias_opt, + IntArrayRef stride, IntArrayRef padding, IntArrayRef dilation, + bool transposed, IntArrayRef output_padding, int64_t groups) { + TORCH_CHECK_NOT_IMPLEMENTED(false, "convolution_overrideable not implemented. You are likely triggering this with tensor backend other than CPU/CUDA/MKLDNN, if this is intended, please use TORCH_LIBRARY_IMPL to override this function "); +} + +// Function to select the convolution backend based on the inputs and params. +// This overload is used within the convolution internals but not exposed to python. +// NB: The forward pass provides a bias tensor while the backward pass provides +// a bool indicating whether the bias is defined. This is done to save memory by +// avoiding saving the full bias tensor for backward. +template +static ConvBackend _select_conv_backend( + const Tensor& input, + const Tensor& weight, + const std::optional& bias, + const at::OptionalArrayRef bias_sizes_opt, + const bool need_backward, + const ConvParams& params) { + + // don't send empty inputs through backends + if constexpr (std::is_same_v) { + if (TORCH_GUARD_OR_FALSE(at::symint::size(input, 0).sym_eq(0)) || + TORCH_GUARD_OR_FALSE(at::symint::size(input, 1).sym_eq(0))) { + return input.is_mkldnn() ? ConvBackend::MkldnnEmpty : ConvBackend::Empty; + } else if (TORCH_GUARD_OR_FALSE(at::symint::numel(input).sym_eq(0))) { + TORCH_CHECK(false, "Only zero batch or zero channel inputs are supported, but got input shape: ", at::symint::sizes(input)); + } + } else { + if (at::symint::size(input, 0) == 0 || at::symint::size(input, 1) == 0) { + return input.is_mkldnn() ? ConvBackend::MkldnnEmpty : ConvBackend::Empty; + } else if (at::symint::numel(input) == 0) { + TORCH_CHECK(false, "Only zero batch or zero channel inputs are supported, but got input shape: ", at::symint::sizes(input)); + } + } + + if (params.is_depthwise(input, weight)) { + if (params.use_cudnn_depthwise(input, weight)) { + return ConvBackend::Cudnn; + } else if (params.use_miopen(input, weight, bias_sizes_opt.has_value())) { + return ConvBackend::MiopenDepthwise; + } else { + if (input.ndimension() == 4) { + return ConvBackend::CudaDepthwise2d; + } else if (input.ndimension() == 5) { + return ConvBackend::CudaDepthwise3d; + } else { + // unsupported + } + } + } else if (params.use_cudnn(input, weight)) { + if (params.transposed) { + return ConvBackend::CudnnTranspose; + } else { + return ConvBackend::Cudnn; + } + } else if (params.use_miopen(input, weight, bias_sizes_opt.has_value())) { + if (params.transposed) { + return ConvBackend::MiopenTranspose; + } else { + return ConvBackend::Miopen; + } + } else if (params.use_mkldnn(input, weight)) { + if (params.transposed) { + return ConvBackend::MkldnnTranspose; + } else { + return ConvBackend::Mkldnn; + } + } else if (!need_backward && params.use_xnnpack(input, weight, bias_sizes_opt)) { + // Using prepacked conv is preferred, but XNNPACK is still the fastest + // option for NHWC. + return ConvBackend::Xnnpack2d; + // 3x3 depthwith convolutions implementation is inference only + } else if (!need_backward && params.use_cpu_depthwise3x3_winograd(input, weight, bias)) { + return ConvBackend::Winograd3x3Depthwise; + } else if ( + !params.transposed && (input.ndimension() == 5) && + (input.device().is_cpu()) && + !params.is_dilated()) { + // fast path for grouped conv3d + return ConvBackend::Slow3d; + } else if (input.device().is_cpu() || input.is_cuda()) { + // backends without support for groups + if (params.transposed) { + if (input.ndimension() == 4) { + return ConvBackend::SlowTranspose2d; + } else if (input.ndimension() == 5) { + return ConvBackend::SlowTranspose3d; + } else { + // unsupported + } + } else { /* Not transposed */ + if (input.ndimension() == 4) { + if (params.is_dilated()) { + return ConvBackend::SlowDilated2d; + } else { /* dim == 4, non-dilated */ + if (params.use_nnpack(input, weight)) { + return ConvBackend::NnpackSpatial; + } else { + /* CPU implementation has specialized MM kernels + for non-dilated case here */ + return ConvBackend::Slow2d; + } + } + } else if (input.ndimension() == 5 && (input.is_cuda() || params.is_dilated())) { + return ConvBackend::SlowDilated3d; + } else if (input.ndimension() == 5) { /* dim == 5, CPU, non-dilated */ + /* CPU implementation has specialized MM kernels + for non-dilated case here */ + return ConvBackend::Slow3d; + } else { + // unsupported + } + } + } else if (params.use_mps(input, weight)) { + if (params.transposed) { + return ConvBackend::MpsTranspose; + } else { + return ConvBackend::Mps; + } + } else { + // Only reach here when input is backend with out-of-source implementation. + return ConvBackend::Overrideable; + } + + // Error out if no suitable backend was found. + TORCH_CHECK(false, "unsupported ConvNd parameters"); +} + +// Selects a backend for convolution based on the inputs and params. +ConvBackend select_conv_backend( + const Tensor& input_r, const Tensor& weight_r, const std::optional& bias_opt, + SymIntArrayRef stride_, SymIntArrayRef padding_, SymIntArrayRef dilation_, + bool transposed_, SymIntArrayRef output_padding_, c10::SymInt groups_, const at::OptionalSymIntArrayRef bias_sizes_opt) { + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto& ctx = at::globalContext(); + auto k = weight_r.ndimension(); + int64_t dim = k - 2; + ConvParams params; + params.stride = expand_param_if_needed(stride_, "stride", dim); + params.padding = expand_param_if_needed(padding_, "padding", dim); + params.dilation = expand_param_if_needed(dilation_, "dilation", dim); + params.transposed = transposed_; + params.output_padding = expand_param_if_needed(output_padding_, "output_padding", dim); + params.groups = std::move(groups_); + params.benchmark = ctx.benchmarkCuDNN(); + params.deterministic = ctx.deterministicCuDNN() || ctx.deterministicAlgorithms(); + params.cudnn_enabled = ctx.userEnabledCuDNN(); + params.allow_tf32 = ctx.allowTF32CuDNN(at::Float32Op::CONV); + + auto input = input_r; + auto weight = weight_r; + check_shape_forward(input, weight.sym_sizes(), bias, params); + + // Expand 1d -> 2d. + // This is only done for backends that don't natively support 1d spatial input. + if (k == 3 && !input.is_mkldnn() && !input.is_xpu()) { + // avoid accidentally going through NHWC for permuted 3d input. + input = input.contiguous(); + params.view1d_as_2d(); + input = view4d(input); + weight = view4d(weight); + } + + auto bias_sizes = bias.defined() ? std::optional(bias.sym_sizes()) : bias_sizes_opt; + bool need_backward = GradMode::is_enabled() && + (input.requires_grad() || weight.requires_grad() || (bias.defined() && bias.requires_grad())); + return _select_conv_backend(input, weight, bias, bias_sizes, need_backward, params); +} + +// For BC reasons, have a copy that does not require bias_opt +static ConvBackend select_conv_backend( + const Tensor& input, + const Tensor& weight, + const at::OptionalIntArrayRef bias_sizes_opt, + const bool need_backward, + const ConvParams& params) { + return _select_conv_backend(input, weight, {}, bias_sizes_opt, need_backward, params); +} + +static at::Tensor _convolution_nogroup_backend( + const Tensor& input, + const Tensor& weight, + const Tensor& bias, + const ConvBackend backend, + const ConvParams& params) { + auto kernel_size = weight.sizes().slice(2); + switch(backend) { + case ConvBackend::NnpackSpatial: +#if AT_NNPACK_ENABLED() + return at::_nnpack_spatial_convolution(input, weight, bias, params.padding, params.stride); +#else + TORCH_INTERNAL_ASSERT(false, "NnpackSpatial backend was selected in PyTorch compiled without nnpack support"); +#endif + case ConvBackend::Slow2d: + return at::thnn_conv2d(input, weight, kernel_size, bias, params.stride, params.padding); + case ConvBackend::SlowDilated2d: + return at::slow_conv_dilated2d( + input, weight, kernel_size, bias, params.stride, params.padding, params.dilation); + case ConvBackend::SlowDilated3d: + return at::slow_conv_dilated3d( + input, weight, kernel_size, bias, params.stride, params.padding, params.dilation); + case ConvBackend::SlowTranspose2d: + return at::slow_conv_transpose2d( + input, weight, kernel_size, bias, params.stride, params.padding, params.output_padding, params.dilation); + case ConvBackend::SlowTranspose3d: + return at::slow_conv_transpose3d( + input, weight, kernel_size, bias, params.stride, params.padding, params.output_padding, params.dilation); + default: + TORCH_CHECK(false, "Unsupported conv nogroup backend encountered"); + } +} + +static inline std::vector calc_output_size( + const Tensor& input, + const Tensor& weight, + const ConvParams& params) { + std::vector output_size = params.transposed ? + conv_input_size(input.sizes(), weight.sizes(), params.padding, params.output_padding, + params.stride, params.dilation, params.groups) : + conv_output_size(input.sizes(), weight.sizes(), params.padding, params.stride, params.dilation); + + // Handle empty # of channels. + if (input.size(input_channels_dim) == 0) { + output_size[output_channels_dim] = 0; + } + return output_size; +} + +static inline at::MemoryFormat determine_backend_memory_format( + const Tensor& input, + const Tensor& weight, + const ConvBackend backend) { + auto backend_memory_format = at::MemoryFormat::Contiguous; +#if !defined(C10_MOBILE) + auto k = weight.ndimension(); + // See Note [Mobile check segfaults] + switch(backend) { + case ConvBackend::Cudnn: + case ConvBackend::CudnnTranspose: + if (detail::getCUDAHooks().compiledWithCuDNN()) { + backend_memory_format = cudnn_conv_suggest_memory_format(input, weight); + } + break; + case ConvBackend::Miopen: + case ConvBackend::MiopenDepthwise: + case ConvBackend::MiopenTranspose: + if (detail::getCUDAHooks().compiledWithMIOpen()) { + backend_memory_format = miopen_conv_suggest_memory_format(input, weight); + } + break; + case ConvBackend::Mkldnn: + case ConvBackend::MkldnnTranspose: + if (mkldnn_conv_use_channels_last(input, weight)) { + backend_memory_format = (k == 5) ? at::MemoryFormat::ChannelsLast3d : at::MemoryFormat::ChannelsLast; + } + break; + case ConvBackend::Slow2d: + case ConvBackend::SlowDilated2d: + case ConvBackend::SlowTranspose2d: + if (thnn_conv_use_channels_last(input, weight)) { + backend_memory_format = at::MemoryFormat::ChannelsLast; + } + break; + case ConvBackend::Overrideable: + if (xpu_conv_use_channels_last(input, weight)) { + backend_memory_format = (k == 5) ? at::MemoryFormat::ChannelsLast3d : at::MemoryFormat::ChannelsLast; + } + break; + case ConvBackend::Mps: + case ConvBackend::MpsTranspose: + if (mps_conv_use_channels_last(input, weight)) { + backend_memory_format = (k == 5) ? MemoryFormat::ChannelsLast3d : MemoryFormat::ChannelsLast; + } + break; + default: + backend_memory_format = at::MemoryFormat::Contiguous; + } +#endif + return backend_memory_format; +} + +at::MemoryFormat _determine_backend_memory_format( + const Tensor& input, + const Tensor& weight, + const ConvBackend backend) { + return determine_backend_memory_format(input, weight, backend); +} + +at::Tensor _convolution( + const Tensor& input_r, const Tensor& weight_r, const std::optional& bias_r_opt, + IntArrayRef stride_, IntArrayRef padding_, IntArrayRef dilation_, + bool transposed_, IntArrayRef output_padding_, int64_t groups_, + bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_r_maybe_owned = at::borrow_from_optional_tensor(bias_r_opt); + const Tensor& bias_r = *bias_r_maybe_owned; + + auto input = input_r; + auto weight = weight_r; + auto bias = bias_r; + auto k = weight.ndimension(); + c10::IntArrayRef weight_sizes = weight.sizes(); + int64_t dim = k - 2; + + TORCH_CHECK(dim > 0, "weight should have at least three dimensions"); + TORCH_CHECK(groups_ > 0, "non-positive groups is not supported"); + + ConvParams params; + params.stride = expand_param_if_needed(stride_, "stride", dim); + params.padding = expand_param_if_needed(padding_, "padding", dim); + params.dilation = expand_param_if_needed(dilation_, "dilation", dim); + params.transposed = transposed_; + params.output_padding = expand_param_if_needed(output_padding_, "output_padding", dim); + params.groups = groups_; + params.benchmark = benchmark; + params.deterministic = deterministic; + params.cudnn_enabled = cudnn_enabled; + params.allow_tf32 = allow_tf32; + + check_shape_forward(input, weight_sizes, bias, params); + + // Expand 1d -> 2d. + // This is only done for backends that don't natively support 1d spatial input. + if (k == 3 && !input.is_mkldnn() && !input.is_xpu()) { + // avoid accidentally going through NHWC for permuted 3d input. + input = input.contiguous(); + params.view1d_as_2d(); + input = view4d(input); + weight = view4d(weight); + } + + // Select appropriate backend to use. + auto bias_sizes_opt = bias.defined() ? std::optional(bias.sizes()) : std::nullopt; + bool need_backward = GradMode::is_enabled() && + (input.requires_grad() || weight.requires_grad() || (bias.defined() && bias.requires_grad())); + ConvBackend backend = _select_conv_backend(input, weight, bias, c10::OptionalIntArrayRef(bias_sizes_opt), need_backward, params); + at::MemoryFormat backend_memory_format = determine_backend_memory_format(input, weight, backend); + + // Call the backend. + Tensor output; + auto kernel_size = weight.sizes().slice(2); + switch (backend) { + case ConvBackend::CudaDepthwise2d: + output = at::_conv_depthwise2d(input.contiguous(), weight, kernel_size, bias, + params.stride, params.padding, params.dilation); + break; + case ConvBackend::CudaDepthwise3d: + output = at::conv_depthwise3d(input.contiguous(), weight, kernel_size, bias, + params.stride, params.padding, params.dilation); + break; + case ConvBackend::Cudnn: + check_input_same_type_as_parameters(input, weight, bias); + output = at::cudnn_convolution( + input.contiguous(backend_memory_format), weight, params.padding, params.stride, + params.dilation, params.groups, params.benchmark, params.deterministic, params.allow_tf32); + if (bias.defined()) { + output.add_(reshape_bias(input.dim(), bias)); + } + break; + case ConvBackend::CudnnTranspose: + check_input_same_type_as_parameters(input, weight, bias); + output = at::cudnn_convolution_transpose( + input.contiguous(backend_memory_format), weight, params.padding, params.output_padding, + params.stride, params.dilation, params.groups, params.benchmark, params.deterministic, params.allow_tf32); + if (bias.defined()) { + output.add_(reshape_bias(input.dim(), bias)); + } + break; + case ConvBackend::Empty: + { + Tensor weight_view; + // Use permute and clone to avoid at::_unsafe_view(weight, -1) failure for non-contiguous cases where + // view size is not compatible with input tensor's size and stride. + if(weight.is_contiguous()) { + weight_view = at::_unsafe_view(weight, -1); + } else if (weight.is_contiguous(at::MemoryFormat::ChannelsLast)) { + weight_view = at::_unsafe_view(at::permute(weight, {0, 2, 3, 1}), -1); + } else if (weight.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + weight_view = at::_unsafe_view(at::permute(weight, {0, 2, 3, 4, 1}), -1); + } else { + weight_view = at::_unsafe_view(weight.clone(at::MemoryFormat::Contiguous), -1); + } + + output = (input.size(1) == 0) ? (input.view(-1) * weight_view) : (input * weight_view[0]); + if (bias.defined()) { + output.add_(bias[0]); + } + output = output.view(calc_output_size(input, weight, params)); + break; + } + case ConvBackend::Miopen: + check_input_same_type_as_parameters(input, weight, bias); + output = at::miopen_convolution( + input.contiguous(backend_memory_format), weight, bias, params.padding, params.stride, + params.dilation, params.groups, params.benchmark, params.deterministic); + break; + case ConvBackend::MiopenDepthwise: + output = at::miopen_depthwise_convolution( + input.contiguous(backend_memory_format), weight, bias, params.padding, params.stride, + params.dilation, params.groups, params.benchmark, params.deterministic); + break; + case ConvBackend::MiopenTranspose: + check_input_same_type_as_parameters(input, weight, bias); + output = at::miopen_convolution_transpose( + input.contiguous(backend_memory_format), weight, bias, params.padding, params.output_padding, + params.stride, params.dilation, params.groups, params.benchmark, params.deterministic); + break; + case ConvBackend::Mkldnn: +#if AT_MKLDNN_ENABLED() + check_input_same_type_as_parameters(input, weight, bias, backend); + if (!input.is_mkldnn()) { + // need to ensure contiguous for non-mkldnn tensors + input = input.contiguous(backend_memory_format); + weight = weight.contiguous(backend_memory_format); + bias = bias.defined() ? bias.contiguous() : bias; + } + output = at::mkldnn_convolution( + input, weight, bias, params.padding, params.stride, params.dilation, params.groups); +#else + TORCH_INTERNAL_ASSERT(false, "Mkldnn backend was selected in PyTorch compiled without mkldnn support"); +#endif + break; + case ConvBackend::MkldnnTranspose: +#if AT_MKLDNN_ENABLED() + check_input_same_type_as_parameters(input, weight, bias, backend); + if (!input.is_mkldnn()) { + // need to ensure contiguous for non-mkldnn tensors + input = input.contiguous(backend_memory_format); + weight = weight.contiguous(backend_memory_format); + bias = bias.defined() ? bias.contiguous() : bias; + } + output = mkldnn_convolution_transpose_stub(input.device().type(), + input, weight, bias, params.padding, params.output_padding, params.stride, params.dilation, params.groups); +#else + TORCH_INTERNAL_ASSERT(false, "Mkldnn backend was selected in PyTorch compiled without mkldnn support"); +#endif + break; + case ConvBackend::MkldnnEmpty: +#if AT_MKLDNN_ENABLED() + output = empty_mkldnn( + calc_output_size(input, weight, params), optTypeMetaToScalarType(input.options().dtype_opt()), + input.options().layout_opt(), input.options().device_opt(), input.options().pinned_memory_opt()); +#else + TORCH_INTERNAL_ASSERT(false, "Mkldnn backend was selected in PyTorch compiled without mkldnn support"); +#endif + break; + case ConvBackend::Overrideable: + output = at::convolution_overrideable( + input, weight, bias, params.stride, params.padding, params.dilation, params.transposed, + params.output_padding, params.groups); + break; + case ConvBackend::Slow3d: + output = at::slow_conv3d(input, weight, kernel_size, bias, params.stride, params.padding); + break; + case ConvBackend::Winograd3x3Depthwise: + output = convolution_depthwise3x3_winograd_stub( + input.device().type(), input, weight, bias, params.stride, params.padding, params.groups); + break; + case ConvBackend::Xnnpack2d: + output = xnnpack::convolution2d( + input, weight, bias, params.padding, params.stride, params.dilation, params.groups); + break; + // Handle backends that don't natively support groups > 1. + case ConvBackend::NnpackSpatial: + case ConvBackend::Slow2d: + case ConvBackend::SlowDilated2d: + case ConvBackend::SlowDilated3d: + case ConvBackend::SlowTranspose2d: + case ConvBackend::SlowTranspose3d: + input = input.contiguous(backend_memory_format); + weight = weight.contiguous(backend_memory_format); + if (params.groups == 1) { + output = _convolution_nogroup_backend(input, weight, bias, backend, params); + } else { + std::vector outputs(params.groups); + for (const auto g : c10::irange(params.groups)) { + auto input_g = subtensor(input, 1, params.groups, g); + auto weight_g = subtensor(weight, 0, params.groups, g); + auto bias_g = subtensor(bias, 0, params.groups, g); + outputs[g] = _convolution_nogroup_backend(input_g, weight_g, bias_g, backend, params); + } + output = at::cat(outputs, 1); + } + break; + case ConvBackend::Mps: +#ifdef USE_MPS + check_input_same_type_as_parameters(input, weight, bias); + output = at::_mps_convolution(input, weight, bias.defined() ? bias.contiguous() : bias, + params.padding, params.stride, params.dilation, + params.groups); +#else + TORCH_INTERNAL_ASSERT(false, "MPS backend was selected in PyTorch without support"); +#endif + break; + case ConvBackend::MpsTranspose: +#ifdef USE_MPS + check_input_same_type_as_parameters(input, weight, bias); + output = at::_mps_convolution_transpose( + input.contiguous(backend_memory_format), weight, + params.padding, params.output_padding, + params.stride, params.dilation, params.groups); + if (bias.defined()) { + output.add_(reshape_bias(input.dim(), bias)); + } +#else + TORCH_INTERNAL_ASSERT(false, "MPS backend was selected in PyTorch without support"); +#endif + break; + } + + if (k == 3 && !input.is_mkldnn() && !input.is_xpu()) { + output = view3d(output); + } + + return output; +} + +at::Tensor _convolution( + const Tensor& input_r, const Tensor& weight_r, const std::optional& bias_r_opt, + IntArrayRef stride_, IntArrayRef padding_, IntArrayRef dilation_, + bool transposed_, IntArrayRef output_padding_, int64_t groups_, + bool benchmark, bool deterministic, bool cudnn_enabled) +{ + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_r_maybe_owned = at::borrow_from_optional_tensor(bias_r_opt); + const Tensor& bias_r = *bias_r_maybe_owned; + + return at::_convolution(input_r, weight_r, bias_r, stride_, padding_, dilation_, transposed_, output_padding_, groups_, benchmark, deterministic, cudnn_enabled, at::globalContext().allowTF32CuDNN(at::Float32Op::CONV)); +} + +std::tuple convolution_backward_overrideable( + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + IntArrayRef stride, IntArrayRef padding, IntArrayRef dilation, + bool transposed, IntArrayRef output_padding, int64_t groups, std::array output_mask) { + TORCH_CHECK_NOT_IMPLEMENTED(false, "convolution_backward_overrideable: You are likely triggering this with tensor backend other than CPU/CUDA/MKLDNN, if this is intended, please use TORCH_LIBRARY_IMPL to override this function "); +} + +static Tensor subvariable(const Tensor& var, int64_t dim, int64_t groups, int64_t g) { + int64_t n = var.sizes()[dim] / groups; + auto result = var.narrow(dim, n * g, n); + return result; +} + +std::tuple _convolution_double_backward( const std::optional& ggI_opt, const std::optional& ggW_r_opt, const std::optional& ggb_opt, + const Tensor& gO_r, const Tensor& weight_r, const Tensor& input, + IntArrayRef stride_, IntArrayRef padding_, IntArrayRef dilation_, + bool transposed_, IntArrayRef output_padding_, int64_t groups_, + std::array output_mask) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned ggI_maybe_owned = at::borrow_from_optional_tensor(ggI_opt); + const Tensor& ggI = *ggI_maybe_owned; + Tensor ggW = ggW_r_opt.value_or(Tensor()); + const Tensor& ggb = ggb_opt.value_or(Tensor()); + + + auto gO = gO_r; + auto weight = weight_r; + + int64_t dim = weight.ndimension() - 2; + ConvParams params; + params.stride = expand_param_if_needed(stride_, "stride", dim); + params.padding = expand_param_if_needed(padding_, "padding", dim); + params.dilation = expand_param_if_needed(dilation_, "dilation", dim); + params.transposed = transposed_; + params.output_padding = expand_param_if_needed(output_padding_, "output_padding", dim); + // TODO: hacky way of inferring the groups number for grouped Conv3D + // See: https://github.com/pytorch/pytorch/pull/36355 + if (!params.transposed && input.dim() > 4) { + // Avoid undefined behavior when num channels == 0; params are unused for that case. + params.groups = (weight.size(1) > 0) ? input.size(1) / weight.size(1) : -1; + } else { + params.groups = groups_; + } + + // Compute ggO = conv(ggI, w) + conv(i, ggW) + ggb + const bool input_nonempty = + TORCH_GUARD_OR_TRUE(input.sym_numel().sym_ne(0)); + Tensor ggO; + if (input_nonempty) { + if (ggI.defined()) { + if (weight.is_cuda()) { + weight = weight.contiguous(); + } + ggO = at::convolution(ggI, weight, Tensor(), params.stride, params.padding, params.dilation, params.transposed, params.output_padding, params.groups); + } + + if (ggW.defined()) { + if (ggW.is_cuda()) { + ggW = ggW.contiguous(); + } + auto ggW_term = at::convolution(input, ggW, Tensor(), params.stride, params.padding, params.dilation, params.transposed, params.output_padding, params.groups); + if (ggO.defined()) { + ggO = ggO + ggW_term; + } else { + ggO = ggW_term; + } + } + } + + if (ggb.defined()) { + // View as (1, ggb.size(0), 1, 1...) + + // Expand + std::vector new_size(gO.ndimension(), 1); + new_size[1] = ggb.sizes()[0]; + auto ggb_contiguous = ggb.contiguous(); + auto ggb_view = ggb_contiguous.view(new_size); + + // Expand + auto ggb_expanded = ggb_view.expand(gO.sizes()); + + if (ggO.defined()) { + ggO = ggO + ggb_expanded; + } else { + ggO = ggb_expanded; + } + } + + // Compute gW = conv(ggI, gO) + Tensor gW; + if (ggI.defined()) { + + // Modified params with correct padding + ConvParams gw_conv_params(params); + + // Disable groups as they are handled separately + auto groups = gw_conv_params.groups; + gw_conv_params.groups = 1; + std::swap(gw_conv_params.dilation, gw_conv_params.stride); + + // Transpose gO and ggI to accumulate over batch + auto gOt = gO.transpose(0, 1); + auto ggIt = ggI.transpose(0, 1); + + Tensor gWt; + // Compute conv + if (input_nonempty) { + if (groups == 1) { + + if (gOt.is_cuda()) { + gOt = gOt.contiguous(); + } + // Compute conv + if (params.transposed) { + gw_conv_params.transposed = false; + gWt = at::convolution(gOt, ggIt, Tensor(), gw_conv_params.stride, gw_conv_params.padding, gw_conv_params.dilation, gw_conv_params.transposed, gw_conv_params.output_padding, gw_conv_params.groups); + } else { + gWt = at::convolution(ggIt, gOt, Tensor(), gw_conv_params.stride, gw_conv_params.padding, gw_conv_params.dilation, gw_conv_params.transposed, gw_conv_params.output_padding, gw_conv_params.groups); + } + } else { + std::vector gWt_list(groups); + for (const auto g : c10::irange(groups)) { + auto ggIt_g = subvariable(ggIt, 0, groups, g); + auto gOt_g = subvariable(gOt, 0, groups, g); + if (gOt_g.is_cuda()) { + gOt_g = gOt_g.contiguous(); + } + + // Compute conv + if (params.transposed) { + gw_conv_params.transposed = false; + gWt_list[g] = at::convolution(gOt_g, ggIt_g, Tensor(), gw_conv_params.stride, gw_conv_params.padding, gw_conv_params.dilation, gw_conv_params.transposed, gw_conv_params.output_padding, gw_conv_params.groups); + } else { + gWt_list[g] = at::convolution(ggIt_g, gOt_g, Tensor(), gw_conv_params.stride, gw_conv_params.padding, gw_conv_params.dilation, gw_conv_params.transposed, gw_conv_params.output_padding, gw_conv_params.groups); + } + } + + gWt = at::cat(gWt_list, 1); + } + + // Transpose gW to match chan_in and chan_out + gW = gWt.transpose(0, 1); + + // narrow gW to only relevant portion + // we do it this way instead of narrowing the input itself because + // the ConvForward kernels don't support asymmetric padding. + auto gW_size = gW.sizes(); + auto w_size = weight.sizes(); + for (const auto i : c10::irange(2, static_cast(gW_size.size()))) { + if (gW_size[i] > w_size[i]) { + gW = gW.narrow(i, 0, w_size[i]); + gW_size = gW.sizes(); + } + } + } + } + + // Compute gI = convT(gO, ggW) if !transposed + // gI = conv(gO, ggw) if transposed + Tensor gI; + if (input_nonempty) { + if (ggW.defined()) { + ConvParams gi_conv_params(params); + gi_conv_params.transposed = !params.transposed; + + if (params.transposed) { + if (gO.is_cuda()) { + gO = gO.contiguous(); + } + gI = at::convolution(gO, ggW, Tensor(), gi_conv_params.stride, gi_conv_params.padding, gi_conv_params.dilation, gi_conv_params.transposed, gi_conv_params.output_padding, gi_conv_params.groups); + + // narrow gI to only relevant portion + // we do it this way because negative output_padding is not supported + // TODO: figure out if we can narrow gO and save some compute, + // rather than narrowing the computed gI + auto gI_size = gI.sizes(); + auto i_size = input.sizes(); + for (const auto i : c10::irange(2, static_cast(gI_size.size()))) { + if (gI_size[i] > i_size[i]) { + gI = gI.narrow(i, 0, i_size[i]); + gI_size = gI.sizes(); + } + } + } else { + // calculate output_padding + // TODO: figure out why this needs to be computed... + auto kernel_size = weight.sizes().slice(2); + auto input_shape = input.sizes().slice(2); + auto grad_output_shape = gO.sizes().slice(2); + + for (const auto i : c10::irange(kernel_size.size())) { + // Check if whole input has been used or not + auto expected_input_shape = (kernel_size[i] - 1) * gi_conv_params.dilation[i] + - 2 * gi_conv_params.padding[i] + + (gi_conv_params.stride[i] * (grad_output_shape[i] - 1) + 1); + if (expected_input_shape != input_shape[i]) { + gi_conv_params.output_padding[i] = input_shape[i] - expected_input_shape; + } + } + + if (gO.is_cuda()) { + gO = gO.contiguous(); + } + + gI = at::convolution(gO, ggW, Tensor(), gi_conv_params.stride, gi_conv_params.padding, gi_conv_params.dilation, gi_conv_params.transposed, gi_conv_params.output_padding, gi_conv_params.groups); + } + } + } + + return std::tuple{std::move(ggO), std::move(gI), std::move(gW)}; +} + +static std::tuple _convolution_backward_nogroup_backend( + const Tensor& grad_output, + const Tensor& input, + const Tensor& weight, + const std::array output_mask, + const ConvBackend backend, + const ConvParams& params) { + auto kernel_size = weight.sizes().slice(2); + switch(backend) { + case ConvBackend::Slow2d: + return at::_slow_conv2d_backward( + grad_output, input, weight, kernel_size, params.stride, params.padding, output_mask); + // NB: nnpack backward does not support strided convolutions; use slow impl instead + case ConvBackend::NnpackSpatial: + case ConvBackend::SlowDilated2d: + return slow_conv_dilated2d_backward_stub( + input.device().type(), + grad_output, input, weight, kernel_size, params.stride, params.padding, params.dilation, output_mask); + case ConvBackend::SlowDilated3d: + return slow_conv_dilated3d_backward_stub( + input.device().type(), + grad_output, input, weight, kernel_size, params.stride, params.padding, params.dilation, output_mask); + case ConvBackend::SlowTranspose2d: + return slow_conv_transpose2d_backward_stub( + input.device().type(), grad_output, input, weight, kernel_size, params.stride, params.padding, + params.output_padding, params.dilation, output_mask); + case ConvBackend::SlowTranspose3d: + return slow_conv_transpose3d_backward_stub( + input.device().type(), grad_output, input, weight, kernel_size, params.stride, params.padding, + params.output_padding, params.dilation, output_mask); + default: + TORCH_CHECK(false, "Unsupported conv nogroup backend encountered"); + } +} + +// Backward pass for convolution. Computes gradients for input, weight, and bias depending on the +// output_mask setting. This function supports 1D, 2D, or 3D spatial convolution and currently requires +// a single batch dimension to be present. +// +// Args: +// grad_output_: tensor of shape (N, C_out, L_out), (N, C_out, H_out, W_out), or (N, C_out, D_out, H_out, W_out) +// input_: tensor of shape (N, C_in, L_in), (N, C_in, H_in, W_in), or (N, C_in, D_in, H_in, W_in) +// weight_: tensor of shape (C_out, C_in // groups, *kernel_size); dimension of kernel_size must match the number +// of input spatial dimensions +// bias_sizes_opt: if specified, indicates that a bias was used in the forward pass and contains the shape +// of the bias. While the bias shape can be computed from other inputs, it is provided to this function for +// ease of use. The bias shape is (weight.shape[0]) for normal convolution and (weight.shape[1] * groups) +// for transposed convolution. +// stride: single value or an array with dimension matching the number of input spatial dimensions +// padding: single value or an array with dimension matching the number of input spatial dimensions +// dilation: single value or an array with dimension matching the number of input spatial dimensions +// transposed: boolean indicating whether the convolution is transposed +// output_padding: single value or dimension == number of input spatial dimensions; only supported when +// transposed is true +// groups: number of groups for grouped convolution +// output_mask: 3-dim boolean array specifying which gradients to compute in input, weight, bias order +std::tuple convolution_backward( + const Tensor& grad_output_, const Tensor& input_, const Tensor& weight_, + const at::OptionalIntArrayRef bias_sizes_opt, + IntArrayRef stride, IntArrayRef padding, IntArrayRef dilation, bool transposed, IntArrayRef output_padding, + int64_t groups, std::array output_mask) { + auto grad_output = grad_output_; + auto input = input_; + auto weight = weight_; + + auto k = weight.ndimension(); + int64_t dim = k - 2; + + TORCH_CHECK(dim > 0, "weight should have at least three dimensions"); + + auto& ctx = at::globalContext(); + ConvParams params; + params.stride = expand_param_if_needed(stride, "stride", dim); + params.padding = expand_param_if_needed(padding, "padding", dim); + params.dilation = expand_param_if_needed(dilation, "dilation", dim); + params.transposed = transposed; + params.output_padding = expand_param_if_needed(output_padding, "output_padding", dim); + params.groups = groups; + params.benchmark = ctx.benchmarkCuDNN(); + params.deterministic = ctx.deterministicCuDNN() || ctx.deterministicAlgorithms(); + params.cudnn_enabled = ctx.userEnabledCuDNN(); + params.allow_tf32 = ctx.allowTF32CuDNN(at::Float32Op::CONV); + + // Unbatched input (no leading batch dim) is supported by the slow dilated + // backward kernels, which insert the batch dim internally and return an + // unbatched grad_input. Route such inputs directly to them; the generic path + // below requires a batch dim. Other backends fall through and raise the usual + // dimensionality error. + if (!transposed && groups == 1 && (k == 4 || k == 5) && + input.dim() == k - 1 && grad_output.dim() == k - 1) { + ConvBackend dilated_backend = select_conv_backend( + input.unsqueeze(0), weight, bias_sizes_opt, /*need_backward=*/true, params); + if (dilated_backend == ConvBackend::SlowDilated2d || + dilated_backend == ConvBackend::SlowDilated3d) { + return _convolution_backward_nogroup_backend( + grad_output, input, weight, output_mask, dilated_backend, params); + } + } + + // Validate inputs. + check_shape_backward(input, weight.sizes(), params); + TORCH_CHECK(input.dim() == grad_output.dim(), + "Expected input and grad_output to have the same number of dimensions, but got: ", + input.dim(), " and ", grad_output.dim()); + + // output_padding is only supported for transposed convolutions + if (!params.transposed) { + for (auto pad : params.output_padding) { + TORCH_CHECK(pad == 0, "output_padding is not supported for non-transposed convolutions; got: ", + params.output_padding); + } + } + + // Expand 1d -> 2d. + // This is only done for backends that don't natively support 1d spatial input. + if (k == 3 && !input.is_mkldnn() && !input.is_xpu()) { + // avoid accidentally going through NHWC for permuted 3d input. + input = input.contiguous(); + params.view1d_as_2d(); + grad_output = view4d(grad_output); + input = view4d(input); + weight = view4d(weight); + } + + // Select appropriate backend to use. + ConvBackend backend = select_conv_backend(input, weight, bias_sizes_opt, /*need_backward=*/ true, params); + at::MemoryFormat backend_memory_format = determine_backend_memory_format(input, weight, backend); + + // Call the backend. + Tensor backend_grad_input, backend_grad_weight, backend_grad_bias; + auto kernel_size = weight.sizes().slice(2); + switch(backend) { + case ConvBackend::CudaDepthwise2d: + { + std::array input_weight_output_mask = {output_mask[0], output_mask[1]}; + std::tie(backend_grad_input, backend_grad_weight) = + conv_depthwise2d_backward_stub(input.device().type(), grad_output, input, + weight, kernel_size, params.stride, params.padding, params.dilation, input_weight_output_mask); + break; + } + case ConvBackend::CudaDepthwise3d: + TORCH_CHECK(input.ndimension() == 5); + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + conv_depthwise3d_backward_stub( + input.device().type(), grad_output, input, weight, kernel_size, params.stride, + params.padding, params.dilation, output_mask); + break; + case ConvBackend::Cudnn: + { + check_input_same_type_as_parameters(input, weight); + std::array input_weight_output_mask = {output_mask[0], output_mask[1]}; + std::tie(backend_grad_input, backend_grad_weight) = cudnn_convolution_backward_stub( + input.device().type(), + // Only make input contiguous when it is necessary for the backwards computation + output_mask[1] ? input.contiguous(backend_memory_format) : input, + grad_output, weight, params.padding, params.stride, + params.dilation, params.groups, params.benchmark, params.deterministic, params.allow_tf32, + input_weight_output_mask); + break; + } + case ConvBackend::Mps: + { +#ifdef USE_MPS + check_input_same_type_as_parameters(input, weight); + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + at::mps_convolution_backward(input, grad_output, weight, params.padding, + params.stride, params.dilation, params.groups, output_mask); +#else + TORCH_INTERNAL_ASSERT(false, "MPS backend was selected in PyTorch without support"); +#endif + break; + } + case ConvBackend::MpsTranspose: + { +#ifdef USE_MPS + check_input_same_type_as_parameters(input, weight); + std::array input_weight_output_mask = {output_mask[0], output_mask[1]}; + std::tie(backend_grad_input, backend_grad_weight) = at::mps_convolution_transpose_backward( + // Only make input contiguous when it is necessary for the backwards computation + output_mask[1] ? input.contiguous(backend_memory_format) : input, + grad_output, weight, params.padding, params.output_padding, + params.stride, params.dilation, params.groups, input_weight_output_mask); +#else + TORCH_INTERNAL_ASSERT(false, "MPS backend was selected in PyTorch without support"); +#endif + break; + } + case ConvBackend::CudnnTranspose: + { + check_input_same_type_as_parameters(input, weight); + std::array input_weight_output_mask = {output_mask[0], output_mask[1]}; + std::tie(backend_grad_input, backend_grad_weight) = cudnn_convolution_transpose_backward_stub( + input.device().type(), + // Only make input contiguous when it is necessary for the backwards computation + output_mask[1] ? input.contiguous(backend_memory_format) : input, + grad_output, weight, params.padding, params.output_padding, + params.stride, params.dilation, params.groups, params.benchmark, params.deterministic, params.allow_tf32, + input_weight_output_mask); + break; + } + case ConvBackend::Empty: + if (output_mask[0]) { + backend_grad_input = at::zeros_like(input); + } + if (output_mask[1]) { + backend_grad_weight = at::zeros_like(weight); + } + if (output_mask[2]) { + backend_grad_bias = at::zeros(*bias_sizes_opt, weight.options()); + } + break; + case ConvBackend::MkldnnEmpty: +#if AT_MKLDNN_ENABLED() + if (output_mask[0]) { + if (input.is_mkldnn()) { + backend_grad_input = empty_mkldnn(input.sizes(), optTypeMetaToScalarType(input.options().dtype_opt()), + input.options().layout_opt(), input.options().device_opt(), input.options().pinned_memory_opt()); + backend_grad_input.zero_(); + } else { + backend_grad_input = at::zeros_like(input); + } + } + if (output_mask[1]) { + // mkldnn weight is not supported during training by the mkldnn backend + backend_grad_weight = at::zeros_like(weight); + } + if (output_mask[2]) { + // mkldnn bias is not supported during training by the mkldnn backend + backend_grad_bias = at::zeros(*bias_sizes_opt, weight.options()); + } +#else + TORCH_INTERNAL_ASSERT(false, "Mkldnn backend was selected in PyTorch compiled without mkldnn support"); +#endif + break; + case ConvBackend::Miopen: + check_input_same_type_as_parameters(input, weight); + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + miopen_convolution_backward_stub( + input.device().type(), + input.contiguous(backend_memory_format), grad_output, weight, params.padding, params.stride, + params.dilation, params.groups, params.benchmark, params.deterministic, output_mask); + break; + case ConvBackend::MiopenDepthwise: + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + miopen_depthwise_convolution_backward_stub( + input.device().type(), + input.contiguous(backend_memory_format), grad_output, weight, params.padding, params.stride, + params.dilation, params.groups, params.benchmark, params.deterministic, output_mask); + break; + case ConvBackend::MiopenTranspose: + check_input_same_type_as_parameters(input, weight); + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + miopen_convolution_transpose_backward_stub( + input.device().type(), + input.contiguous(backend_memory_format), grad_output, weight, params.padding, params.output_padding, + params.stride, params.dilation, params.groups, params.benchmark, params.deterministic, output_mask); + break; + case ConvBackend::Mkldnn: + TORCH_CHECK(!weight.is_mkldnn(), + "The MKLDNN backend does not support weight as an MKLDNN tensor during training"); + if (!input.is_mkldnn()) { + input = input.contiguous(backend_memory_format); + weight = weight.contiguous(backend_memory_format); + } + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + mkldnn_convolution_backward_stub(input.device().type(), input, grad_output, weight, params.padding, + params.stride, params.dilation, params.groups, output_mask); + break; + case ConvBackend::MkldnnTranspose: + TORCH_CHECK(!weight.is_mkldnn(), + "The MKLDNN backend does not support weight as an MKLDNN tensor during training"); + if (!input.is_mkldnn()) { + input = input.contiguous(backend_memory_format); + weight = weight.contiguous(backend_memory_format); + } + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + mkldnn_convolution_transpose_backward_stub(input.device().type(), input, grad_output, weight, params.padding, + params.output_padding, params.stride, params.dilation, params.groups, output_mask); + break; + case ConvBackend::Overrideable: + // Only reach here when input is backend with out-of-source implementation. + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + at::convolution_backward_overrideable(grad_output, input, weight, params.stride, params.padding, + params.dilation, params.transposed, params.output_padding, params.groups, output_mask); + break; + case ConvBackend::Slow3d: + // Note that no CUDA implementation of this kernel exists currently. + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + slow_conv3d_backward_cpu( + grad_output, input, weight, kernel_size, + params.stride, params.padding, output_mask); + break; + // Handle backends that don't natively support groups > 1. + case ConvBackend::NnpackSpatial: + case ConvBackend::Slow2d: + case ConvBackend::SlowDilated2d: + case ConvBackend::SlowDilated3d: + case ConvBackend::SlowTranspose2d: + case ConvBackend::SlowTranspose3d: + { + input = input.contiguous(backend_memory_format); + weight = weight.contiguous(backend_memory_format); + if (params.groups == 1) { + std::tie(backend_grad_input, backend_grad_weight, backend_grad_bias) = + _convolution_backward_nogroup_backend( + grad_output, input, weight, output_mask, backend, params); + } else { + std::vector backend_grad_inputs(params.groups); + std::vector backend_grad_weights(params.groups); + std::vector backend_grad_biases(params.groups); + for (int g = 0; g < params.groups; ++g) { + auto grad_output_g = subtensor(grad_output, 1, params.groups, g); + auto input_g = subtensor(input, 1, params.groups, g); + auto weight_g = subtensor(weight, 0, params.groups, g); + std::tie(backend_grad_inputs[g], backend_grad_weights[g], backend_grad_biases[g]) = + _convolution_backward_nogroup_backend( + grad_output_g, input_g, weight_g, output_mask, backend, params); + } + if (output_mask[0]) { + backend_grad_input = at::cat(backend_grad_inputs, 1); + } + if (output_mask[1]) { + backend_grad_weight = at::cat(backend_grad_weights, 0); + } + if (output_mask[2]) { + backend_grad_bias = at::cat(backend_grad_biases, 0); + } + } + break; + } + // Backward is not supported for these backends. + case ConvBackend::Winograd3x3Depthwise: + TORCH_CHECK(false, "Backward is not supported for depthwise 3x3 winograd"); + break; + case ConvBackend::Xnnpack2d: + TORCH_CHECK(false, "Backward is not supported for xnnpack"); + break; + } + + // Convert 2D inputs back to 1D for backends that don't natively support 1D + // spatial inputs. + if (output_mask[0]) { + if (k == 3 && !input.is_mkldnn() && !input.is_xpu()) { + backend_grad_input = view3d(backend_grad_input); + } + } + if (output_mask[1]) { + if (k == 3 && !input.is_mkldnn() && !input.is_xpu()) { + backend_grad_weight = view3d(backend_grad_weight); + } + } + if (output_mask[2]) { + if (!backend_grad_bias.defined()) { + // Calculate bias gradients outside of the backend for those that don't support it. + backend_grad_bias = grad_output.sum((dim == 3) ? IntArrayRef{0, 2, 3, 4} : IntArrayRef{0, 2, 3}); + } + } + + return std::make_tuple(std::move(backend_grad_input), std::move(backend_grad_weight), std::move(backend_grad_bias)); +} + +void _cudnn_set_conv_benchmark_empty_cache(bool enable) { + conv_benchmark_empty_cache.store(enable, std::memory_order_relaxed); +} + +bool _cudnn_get_conv_benchmark_empty_cache() { + return conv_benchmark_empty_cache.load(std::memory_order_relaxed); +} + + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cd5e5d1d88a849e8b2e5261c0371a83d48591c3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM2d.cpp @@ -0,0 +1,753 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +Tensor compute_columns2d( + const Tensor& input, + IntArrayRef padding, + IntArrayRef stride, + IntArrayRef kernel_size, + bool is_channels_last) { + const int64_t kernel_height = kernel_size[0]; + const int64_t kernel_width = kernel_size[1]; + const int64_t pad_height = padding[0]; + const int64_t pad_width = padding[1]; + const int64_t stride_height = stride[0]; + const int64_t stride_width = stride[1]; + const int64_t batch_size = input.size(0); + const int64_t n_input_plane = input.size(1); + const int64_t input_height = input.size(2); + const int64_t input_width = input.size(3); + const int64_t output_height = (input_height + 2 * pad_height - kernel_height) / stride_height + 1; + const int64_t output_width = (input_width + 2 * pad_width - kernel_width) / stride_width + 1; + + Tensor columns; + if ((kernel_height == 1) && (stride_height == 1) && (pad_height == 0) && + (kernel_width == 1) && (stride_width == 1) && (pad_width == 0)) { + // Columns are just a view on the input for the 1x1 kernel special case. + if (is_channels_last) { + columns = input.as_strided({batch_size, output_height * output_width, n_input_plane}, + {output_height * output_width * n_input_plane, n_input_plane, 1}).detach(); + } else { + columns = input.view({batch_size, n_input_plane, output_height * output_width}).detach(); + } + } else { + int64_t row = is_channels_last ? + output_height * output_width : n_input_plane * kernel_height * kernel_width; + int64_t col = is_channels_last ? + kernel_height * kernel_width * n_input_plane : output_height * output_width; + columns = at::empty({batch_size, row, col}, input.options()); + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "slow_conv2d_cpu", [&]{ + auto input_a = input.accessor(); + auto columns_a = columns.accessor(); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto t : c10::irange(start, end)) { + auto input_t = input_a[t]; + auto columns_t = columns_a[t]; + unfolded2d_copy_stub( + kCPU, + c10::CppTypeToScalarType::value, + columns_t.data(), + input_t.data(), + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + n_input_plane, + input_height, + input_width, + output_height, + output_width, + is_channels_last); + } + }); + }); + } + + return columns.contiguous(); +} + +inline void slow_conv2d_shape_check( + const Tensor& input, + const Tensor& grad_output, + const Tensor& weight, + const Tensor& bias, + int64_t kernel_height, + int64_t kernel_width, + int64_t stride_height, + int64_t stride_width, + int64_t pad_height, + int64_t pad_width, + bool weight_optional) { + TORCH_CHECK( + kernel_width > 0 && kernel_height > 0, + "kernel size should be greater than zero, but got kernel_height: ", + kernel_height, + " kernel_width: ", + kernel_width); + TORCH_CHECK( + stride_width > 0 && stride_height > 0, + "stride should be greater than zero, but got stride_height: ", + stride_height, + " stride_width: ", + stride_width); + + if (weight.defined()) { + TORCH_CHECK( + weight.numel() > 0 && (weight.dim() == 2 || weight.dim() == 4), + "non-empty 2D or 4D weight tensor expected, but got: ", + weight.sizes()); + if (bias.defined()) { + check_dim_size(bias, 1, 0, weight.size(0)); + } + } else { + TORCH_CHECK(weight_optional, "weight tensor is undefined"); + } + + const int64_t ndim = input.dim(); + const int64_t dim_planes = 1; + const int64_t dim_height = 2; + const int64_t dim_width = 3; + + // Allow for empty batch size and channel size but not other dimensions + TORCH_CHECK(ndim == 4, "Expected 4D input tensor, but got: ", input.sizes()); + for (const auto dim : c10::irange(2, ndim)) { + TORCH_CHECK(input.size(dim) != 0, + "Expected non-zero size for input dimension ", dim, + ", but got input shape: ", input.sizes(), ". Only the batch and channel dimensions support size 0."); + } + + const int64_t input_height = input.size(dim_height); + const int64_t input_width = input.size(dim_width); + + const int64_t exact_input_height = input_height + 2 * pad_height; + const int64_t exact_input_width = input_width + 2 * pad_width; + + TORCH_CHECK( + exact_input_height >= kernel_height && exact_input_width >= kernel_width, + "Calculated padded input size per channel: (", + exact_input_height, + " x ", + exact_input_width, + "). ", + "Kernel size: (", + kernel_height, + " x ", + kernel_width, + "). Kernel size can't be greater than actual input size"); + + const int64_t output_height = + div_rtn(exact_input_height - kernel_height, stride_height) + 1; + const int64_t output_width = + div_rtn(exact_input_width - kernel_width, stride_width) + 1; + + TORCH_CHECK( + output_width >= 1 && output_height >= 1, + "Given input size per channel: (", + input_height, + " x ", + input_width, + "). " + "Calculated output size per channel: (", + output_height, + " x ", + output_width, + "). Output size is too small"); + + if (weight.defined()) { + int64_t n_input_plane = weight.size(1); + if (weight.dim() == 2) { + n_input_plane /= kernel_height; + n_input_plane /= kernel_width; + } + if (input.size(1) != 0) { + check_dim_size(input, ndim, dim_planes, n_input_plane); + } + } + + if (grad_output.defined()) { + if (weight.defined()) { + int64_t n_output_plane = weight.size(0); + check_dim_size(grad_output, ndim, dim_planes, n_output_plane); + } else if (bias.defined()) { + TORCH_CHECK(bias.numel() > 0, "non-empty bias tensor expected"); + const int64_t n_output_plane = bias.dim() == 0 ? 1 : bias.size(0); + check_dim_size(grad_output, ndim, dim_planes, n_output_plane); + } + check_dim_size(grad_output, ndim, dim_height, output_height); + check_dim_size(grad_output, ndim, dim_width, output_width); + } +} + +inline Tensor view_weight_2d(const Tensor& weight_, + at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) { + Tensor weight = weight_.contiguous(memory_format); + if (weight.dim() == 4) { + const int64_t s1 = weight.size(0); + const int64_t s2 = weight.size(1) * weight.size(2) * weight.size(3); + return memory_format == at::MemoryFormat::ChannelsLast + ? weight.as_strided({s1, s2}, {s2, 1}) // CL: view as {oc, kh*kw*ic} + : weight.view({s1, s2}); // CF: view as {oc, ic*kh*kw} + } else { + return weight; + } +} + +template +void slow_conv2d_update_output_frame( + TensorAccessor input, + TensorAccessor output, + TensorAccessor weight, + bool has_bias, + TensorAccessor finput, + int64_t kernel_height, + int64_t kernel_width, + int64_t stride_height, + int64_t stride_width, + int64_t pad_height, + int64_t pad_width, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t n_output_plane, + int64_t output_height, + int64_t output_width, + bool is_channels_last) { + const int beta = has_bias ? 1 : 0; + + // Compute out = weight * input + // Note gemm expects fortran order, so all 3 matrices are transposed. + // Swapping argument order cancels this, since C == AB <=> T(C) == T(B)T(A) + if (is_channels_last) { + const int64_t m = n_output_plane; + const int64_t n = output_height * output_width; + const int64_t k = n_input_plane * kernel_height * kernel_width; + + const int64_t lda = k; + const int64_t ldb = k; + const int64_t ldc = m; + + at::native::cpublas::gemm( + TransposeType::Transpose, + TransposeType::NoTranspose, + m, n, k, + static_cast(1), + weight.data(), lda, + finput.data(), ldb, + static_cast(beta), + output.data(), ldc); + } else { + const int64_t m = output_height * output_width; + const int64_t n = n_output_plane; + const int64_t k = n_input_plane * kernel_height * kernel_width; + + const int64_t lda = m; + const int64_t ldb = k; + const int64_t ldc = m; + + at::native::cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::NoTranspose, + m, n, k, + static_cast(1), + finput.data(), lda, + weight.data(), ldb, + static_cast(beta), + output.data(), ldc); + } +} + +template +void slow_conv2d_backward_update_grad_input_frame( + TensorAccessor grad_input, + TensorAccessor grad_output, + TensorAccessor weight, + scalar_t *fgrad_input, + int64_t kernel_height, + int64_t kernel_width, + int64_t stride_height, + int64_t stride_width, + int64_t pad_height, + int64_t pad_width, + bool is_channels_last) { + // Compute fgrad_input = weight.T * grad_output.reshape({grad_output.shape(0), -1}) + // Note gemm expects fortran order, so all 3 matrices are transposed. + // Swapping argument order cancels this, since C == AB <=> T(C) == T(B)T(A) + if (is_channels_last) { + const int64_t m = weight.size(1); + const int64_t n = grad_output.size(1) * grad_output.size(2); + const int64_t k = weight.size(0); + + const int64_t lda = m; + const int64_t ldb = k; + const int64_t ldc = m; + + at::native::cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::NoTranspose, + m, n, k, + static_cast(1), + weight.data(), lda, + grad_output.data(), ldb, + static_cast(0), + fgrad_input, ldc); + } else { + const int64_t m = grad_output.size(1) * grad_output.size(2); + const int64_t n = weight.size(1); + const int64_t k = weight.size(0); + + const int64_t lda = m; + const int64_t ldb = n; + const int64_t ldc = m; + + at::native::cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::Transpose, + m, n, k, + static_cast(1), + grad_output.data(), lda, + weight.data(), ldb, + static_cast(0), + fgrad_input, ldc); + } + + unfolded2d_acc_stub( + kCPU, + c10::CppTypeToScalarType::value, + fgrad_input, + grad_input.data(), + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + grad_input.size(0), + grad_input.size(1), + grad_input.size(2), + grad_output.size(1), + grad_output.size(2), + is_channels_last); +} + +void slow_conv2d_backward_out_cpu_template( + Tensor& grad_input, + const Tensor& grad_output_, + const Tensor& input_, + const Tensor& weight_, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding) { + const int64_t kernel_height = kernel_size[0]; + const int64_t kernel_width = kernel_size[1]; + const int64_t pad_height = padding[0]; + const int64_t pad_width = padding[1]; + const int64_t stride_height = stride[0]; + const int64_t stride_width = stride[1]; + + bool use_channels_last = thnn_conv_use_channels_last(input_, weight_); + auto memory_format = use_channels_last ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::Contiguous; + + const Tensor weight = view_weight_2d(weight_, memory_format); + slow_conv2d_shape_check( + input_, + grad_output_, + weight, + Tensor(), + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + false); + + const Tensor input = input_.contiguous(memory_format); + + // Compute shape of columnized data excluding batch dim. + const int64_t batch_size = input.size(0); + const int64_t n_input_plane = input.size(1); + const int64_t input_height = input.size(2); + const int64_t input_width = input.size(3); + const int64_t output_height = (input_height + 2 * pad_height - kernel_height) / stride_height + 1; + const int64_t output_width = (input_width + 2 * pad_width - kernel_width) / stride_width + 1; + const int64_t fgrad_input_size = n_input_plane * kernel_height * kernel_width * output_height * output_width; + + const Tensor grad_output = grad_output_.contiguous(memory_format); + grad_input.resize_as_(input, memory_format); + grad_input.zero_(); + TORCH_CHECK(grad_input.is_contiguous(memory_format), "slow_conv2d: grad_input must be contiguous"); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, input.scalar_type(), "slow_conv2d_cpu_grad_input", [&] { + auto grad_output_a = grad_output.accessor(); + auto grad_input_a = grad_input.accessor(); + auto weight_a = weight.accessor(); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + auto fgrad_input = std::make_unique(fgrad_input_size); + for (const auto t : c10::irange(start, end)) { + auto grad_input_t = grad_input_a[t]; + auto grad_output_t = grad_output_a[t]; + slow_conv2d_backward_update_grad_input_frame( + grad_input_t, + grad_output_t, + weight_a, + fgrad_input.get(), + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + use_channels_last); + } + }); + }); +} + +template +void slow_conv2d_backward_weight_frame( + TensorAccessor grad_weight, + TensorAccessor grad_output, + TensorAccessor finput, + bool is_channels_last) { + // Compute grad_weight += grad_output.reshape({grad_output.shape(0), -1}) * finput.T + // Note gemm expects fortran order, so all 3 matrices are transposed. + // Swapping argument order cancels this, since C == AB <=> T(C) == T(B)T(A) + if (is_channels_last) { + const int64_t m = finput.size(1); + const int64_t n = grad_output.size(0); + const int64_t k = grad_output.size(1) * grad_output.size(2); + + const int64_t lda = m; + const int64_t ldb = n; + const int64_t ldc = m; + + at::native::cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::Transpose, + m, n, k, + static_cast(1), + finput.data(), lda, + grad_output.data(), ldb, + static_cast(1), + grad_weight.data(), ldc); + } else { + const int64_t m = finput.size(0); + const int64_t n = grad_output.size(0); + const int64_t k = grad_output.size(1) * grad_output.size(2); + + const int64_t lda = k; + const int64_t ldb = k; + const int64_t ldc = m; + + at::native::cpublas::gemm( + TransposeType::Transpose, + TransposeType::NoTranspose, + m, n, k, + static_cast(1), + finput.data(), lda, + grad_output.data(), ldb, + static_cast(1), + grad_weight.data(), ldc); + } +} + +void slow_conv2d_backward_weight_out_cpu_template( + Tensor& grad_weight, + const Tensor& input, + const Tensor& grad_output_, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding) { + const int64_t kernel_height = kernel_size[0]; + const int64_t kernel_width = kernel_size[1]; + const int64_t pad_height = padding[0]; + const int64_t pad_width = padding[1]; + const int64_t stride_height = stride[0]; + const int64_t stride_width = stride[1]; + + bool use_channels_last = thnn_conv_use_channels_last(input, grad_weight); + auto memory_format = use_channels_last ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::Contiguous; + + TORCH_CHECK(grad_weight.is_contiguous(memory_format), "slow_conv2d: grad_weight must be contiguous"); + Tensor grad_weight_2d = view_weight_2d(grad_weight, memory_format); + + slow_conv2d_shape_check( + input, + grad_output_, + grad_weight_2d, + {}, + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + true); + + auto grad_output = grad_output_.contiguous(memory_format); + Tensor finput = compute_columns2d(input, padding, stride, kernel_size, use_channels_last); + + const int64_t batch_size = input.size(0); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, input.scalar_type(), "slow_conv2d_cpu_grad_weight", [&] { + auto grad_output_a = grad_output.accessor(); + auto grad_weight_2d_a = grad_weight_2d.accessor(); + auto finput_a = finput.accessor(); + + for (const auto t : c10::irange(batch_size)) { + auto grad_output_t = grad_output_a[t]; + auto finput_t = finput_a[t]; + + slow_conv2d_backward_weight_frame( + grad_weight_2d_a, grad_output_t, finput_t, use_channels_last); + } + }); +} + +} // namespace + +Tensor& slow_conv2d_forward_out_cpu( + const Tensor& self, + const Tensor& weight_, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding, + Tensor& output) { + // See [Note: hacky wrapper removal for optional tensor] + + TORCH_CHECK(kernel_size.size() == 2, "2D kernel_size expected"); + TORCH_CHECK(stride.size() == 2, "2D stride expected"); + TORCH_CHECK(padding.size() == 2, "2D padding expected"); + + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + const int64_t kernel_height = kernel_size[0]; + const int64_t kernel_width = kernel_size[1]; + const int64_t pad_height = padding[0]; + const int64_t pad_width = padding[1]; + const int64_t stride_height = stride[0]; + const int64_t stride_width = stride[1]; + + bool use_channels_last = thnn_conv_use_channels_last(self, weight_); + auto memory_format = use_channels_last ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::Contiguous; + + const Tensor weight_2d = view_weight_2d(weight_, memory_format); + + slow_conv2d_shape_check( + self, + Tensor(), + weight_2d, + bias, + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + false); + + const Tensor input = self.contiguous(memory_format); + const int64_t batch_size = input.size(0); + const int64_t n_input_plane = input.size(1); + const int64_t input_height = input.size(2); + const int64_t input_width = input.size(3); + const int64_t n_output_plane = weight_2d.size(0); + const int64_t output_height = (input_height + 2 * pad_height - kernel_height) / stride_height + 1; + const int64_t output_width = (input_width + 2 * pad_width - kernel_width) / stride_width + 1; + + Tensor finput = compute_columns2d(input, padding, stride, kernel_size, use_channels_last); + output.resize_({batch_size, n_output_plane, output_height, output_width}, memory_format); + if (bias.defined()) { + output.copy_(bias.reshape({-1, 1, 1})); + } + TORCH_CHECK(output.is_contiguous(memory_format), "slow_conv2d output tensor must be contiguous"); + + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "slow_conv2d_cpu", [&]{ + auto input_a = input.accessor(); + auto output_a = output.accessor(); + auto finput_a = finput.accessor(); + auto weight_2d_a = weight_2d.accessor(); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto t : c10::irange(start, end)) { + auto input_t = input_a[t]; + auto output_t = output_a[t]; + auto finput_t = finput_a[t]; + slow_conv2d_update_output_frame( + input_t, + output_t, + weight_2d_a, + bias.defined(), + finput_t, + kernel_height, + kernel_width, + stride_height, + stride_width, + pad_height, + pad_width, + n_input_plane, + input_height, + input_width, + n_output_plane, + output_height, + output_width, + use_channels_last); + } + }); + }); + + return output; +} + +Tensor slow_conv2d_forward_cpu( + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto output = at::empty({0}, self.options()); + at::native::slow_conv2d_forward_out_cpu( + self, + weight, + kernel_size, + bias, + stride, + padding, + output); + + return output; +} + +std::tuple slow_conv2d_backward_out_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + Tensor& grad_input, + Tensor& grad_weight, + Tensor& grad_bias) { + if (grad_input.defined()) { + slow_conv2d_backward_out_cpu_template( + grad_input, + grad_output, + self, + weight, + kernel_size, + stride, + padding); + } + + if (grad_bias.defined()) { + at::sum_out(grad_bias, grad_output, IntArrayRef{0, 2, 3}); + } + + if (grad_weight.defined()) { + grad_weight.resize_(weight.sizes(), weight.suggest_memory_format()); + grad_weight.zero_(); + slow_conv2d_backward_weight_out_cpu_template( + grad_weight, + self, + grad_output, + kernel_size, + stride, + padding); + } + + return std::tuple( + grad_input, grad_weight, grad_bias); +} + +std::tuple slow_conv2d_backward_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + std::array output_mask) { + Tensor grad_input; + Tensor grad_weight; + Tensor grad_bias; + + if (output_mask[0]) { + grad_input = at::empty({0}, grad_output.options()); + } + + if (output_mask[1]) { + grad_weight = at::empty({0}, grad_output.options()); + } + + if (output_mask[2]) { + grad_bias = at::empty({0}, grad_output.options()); + } + + at::native::slow_conv2d_backward_out_cpu( + grad_output, + self, + weight, + kernel_size, + stride, + padding, + grad_input, + grad_weight, + grad_bias); + + return std::make_tuple( + std::move(grad_input), std::move(grad_weight), std::move(grad_bias)); +} + +Tensor & thnn_conv2d_out(const Tensor & self, const Tensor & weight, IntArrayRef kernel_size, const std::optional& bias_opt, IntArrayRef stride, IntArrayRef padding, Tensor & output) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + return at::_slow_conv2d_forward_out(output, self, weight, kernel_size, bias, stride, padding); +} + +Tensor thnn_conv2d(const Tensor & self, const Tensor & weight, IntArrayRef kernel_size, const std::optional& bias_opt, IntArrayRef stride, IntArrayRef padding) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + return at::_slow_conv2d_forward(self, weight, kernel_size, bias, stride, padding); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM3d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM3d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da5bd500689ace9d6f6ed26e9a35273d6b0fa92b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM3d.cpp @@ -0,0 +1,863 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +constexpr int64_t CONV3D_GRAIN_SALT = 20; + +namespace at::native { + +namespace { + +Tensor compute_columns3d( + const Tensor& input_, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef kernel_size, + const int64_t groups) { + const Tensor input = input_.contiguous(); + const int64_t kernel_depth = kernel_size[0]; + const int64_t kernel_height = kernel_size[1]; + const int64_t kernel_width = kernel_size[2]; + const int64_t pad_depth = padding[0]; + const int64_t pad_height = padding[1]; + const int64_t pad_width = padding[2]; + const int64_t stride_depth = stride[0]; + const int64_t stride_height = stride[1]; + const int64_t stride_width = stride[2]; + const int64_t dim_planes = 1; + const int64_t dim_depth = 2; + const int64_t dim_height = 3; + const int64_t dim_width = 4; + const int64_t n_input_plane = input.size(dim_planes); + const int64_t input_depth = input.size(dim_depth); + const int64_t input_height = input.size(dim_height); + const int64_t input_width = input.size(dim_width); + const int64_t output_depth = + (input_depth + 2 * pad_depth - kernel_depth) / stride_depth + 1; + const int64_t output_height = + (input_height + 2 * pad_height - kernel_height) / stride_height + 1; + const int64_t output_width = + (input_width + 2 * pad_width - kernel_width) / stride_width + 1; + const int64_t batch_size = input.size(0); + + Tensor columns; + if ((kernel_depth == 1) && (kernel_height == 1) && (kernel_width == 1) && + (pad_depth == 0) && (pad_height == 0) && (pad_width == 0) && + (stride_depth == 1) && (stride_height == 1) && (stride_width == 1) && (groups == 1)) { + // Columns are just a view on the input for this special case. + columns = input.view({batch_size, n_input_plane, output_height * output_width * output_depth}).detach(); + } else { + columns = at::empty({batch_size, + n_input_plane * kernel_depth * kernel_height * kernel_width, + output_depth * output_height * output_width}, + input.options()); + + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "compute_columns3d", [&] { + auto input_a = input.accessor(); + auto columns_a = columns.accessor(); + + at::parallel_for(0, batch_size, CONV3D_GRAIN_SALT, [&](int64_t start, int64_t end) { + for (const auto t : c10::irange(start, end)) { + auto input_t = input_a[t]; + auto columns_t = columns_a[t]; + Unfold3dCopyCPU( + c10::CppTypeToScalarType::value, + input_t.data(), + n_input_plane, + input_depth, + input_height, + input_width, + output_depth, + output_height, + output_width, + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + columns_t.data()); + } + }); + }); + } + + return columns; +} + +inline void slow_conv3d_shape_check( + const Tensor& input, + const Tensor& grad_output, + const Tensor& weight, + const Tensor& bias, + int64_t kernel_depth, + int64_t kernel_height, + int64_t kernel_width, + int64_t stride_depth, + int64_t stride_height, + int64_t stride_width, + int64_t pad_depth, + int64_t pad_height, + int64_t pad_width, + int64_t groups, + bool weight_optional) { + TORCH_CHECK( + kernel_width > 0 && kernel_height > 0 && kernel_depth > 0, + "kernel size should be greater than zero, but got: ", + kernel_depth, + " x ", + kernel_height, + " x ", + kernel_width, + " (TxHxW)"); + TORCH_CHECK( + stride_width > 0 && stride_height > 0 && stride_depth > 0, + "stride should be greater than zero, but got: ", + stride_depth, + " x ", + stride_height, + " x ", + stride_width, + " (TxHxW)"); + if (weight.defined()) { + TORCH_CHECK( + weight.numel() > 0 && (weight.dim() == 2 || weight.dim() == 5), + "non-empty 2D or 5D weight tensor expected, but got: ", + weight.sizes()); + if (bias.defined()) { + check_dim_size(bias, 1, 0, weight.size(0)); + } + } else { + TORCH_CHECK(weight_optional, "weight tensor is undefined"); + } + + const int64_t ndim = input.dim(); + const int64_t dim_batch = 0; + const int64_t dim_planes = 1; + const int64_t dim_depth = 2; + const int64_t dim_height = 3; + const int64_t dim_width = 4; + + // Allow for empty batch size but not other dimensions + bool valid_empty = ndim == 5 && input.size(dim_batch) == 0 && + input.size(dim_planes) != 0 && input.size(dim_depth) != 0 && + input.size(dim_height) != 0 && input.size(dim_width) != 0; + + TORCH_CHECK( + (input.numel() > 0 || valid_empty) && ndim == 5, + "non-empty 5D input tensor expected but got: ", + input.sizes()); + + const int64_t input_depth = input.size(dim_depth); + const int64_t input_height = input.size(dim_height); + const int64_t input_width = input.size(dim_width); + + constexpr int64_t MAX_SAFE_PAD = (1LL << 61); + + TORCH_CHECK_VALUE( + pad_height <= MAX_SAFE_PAD, + "Padding height too large: pad_height=", + pad_height); + + TORCH_CHECK_VALUE( + pad_width <= MAX_SAFE_PAD, + "Padding width too large: pad_width=", + pad_width); + + TORCH_CHECK_VALUE( + pad_depth <= MAX_SAFE_PAD, + "Padding depth too large: pad_depth=", + pad_depth); + + const int64_t exact_input_depth = input_depth + 2 * pad_depth; + const int64_t exact_input_height = input_height + 2 * pad_height; + const int64_t exact_input_width = input_width + 2 * pad_width; + + TORCH_CHECK( + exact_input_depth >= kernel_depth && + exact_input_height >= kernel_height && + exact_input_width >= kernel_width, + "Calculated padded input size per channel: (", + exact_input_depth, + " x ", + exact_input_height, + " x ", + exact_input_width, + "). ", + "Kernel size: (", + kernel_depth, + " x ", + kernel_height, + " x ", + kernel_width, + "). Kernel size can't be greater than actual input size"); + + const int64_t output_depth = + div_rtn(exact_input_depth - kernel_depth, stride_depth) + 1; + const int64_t output_height = + div_rtn(exact_input_height - kernel_height, stride_height) + 1; + const int64_t output_width = + div_rtn(exact_input_width - kernel_width, stride_width) + 1; + + TORCH_CHECK( + output_depth >= 1 && output_width >= 1 && output_height >= 1, + "Given input size per channel: (", + input_depth, + " x ", + input_height, + " x ", + input_width, + "). " + "Calculated output size per channel: (", + output_depth, + " x ", + output_height, + " x ", + output_width, + "). Output size is too small"); + + uint64_t kernel_product; + TORCH_CHECK( + !c10::mul_overflows(kernel_height, kernel_width, &kernel_product), + "Kernel height x width product is too large: kernel_height=", + kernel_height, + ", kernel_width=", + kernel_width); + + if (weight.defined()) { + int64_t n_input_plane = weight.size(1); + if (weight.dim() == 2) { + n_input_plane /= (kernel_height * kernel_width); + } + // to support grouped conv we need to check if input.size(dim_planes) + // is multiple of weight.size(dim_planes) + TORCH_CHECK(groups > 0, "none zero group size expected"); + check_dim_size(input, ndim, dim_planes, n_input_plane * groups); + } + + if (grad_output.defined()) { + if (weight.defined()) { + int64_t n_output_plane = weight.size(0); + check_dim_size(grad_output, ndim, dim_planes, n_output_plane); + } else if (bias.defined()) { + TORCH_CHECK(bias.numel() > 0, "non-empty bias tensor expected"); + const int64_t n_output_plane = bias.dim() == 0 ? 1 : bias.size(0); + check_dim_size(grad_output, ndim, dim_planes, n_output_plane); + } + check_dim_size(grad_output, ndim, dim_depth, output_depth); + check_dim_size(grad_output, ndim, dim_height, output_height); + check_dim_size(grad_output, ndim, dim_width, output_width); + } +} + +Tensor view_weight_2d(const Tensor& weight_) { + Tensor weight = weight_.contiguous(); + if (weight.dim() == 5) { + const int64_t s1 = weight.size(0); + const int64_t s2 = + weight.size(1) * weight.size(2) * weight.size(3) * weight.size(4); + return weight.view({s1, s2}); + } else { + return weight; + } +} + +template +void slow_conv3d_update_output_frame( + TensorAccessor input, + TensorAccessor output, + TensorAccessor weight, + bool has_bias, + TensorAccessor finput, + int64_t kernel_depth, + int64_t kernel_height, + int64_t kernel_width, + int64_t stride_depth, + int64_t stride_height, + int64_t stride_width, + int64_t pad_depth, + int64_t pad_height, + int64_t pad_width, + int64_t n_input_plane, + int64_t groups, + int64_t input_depth, + int64_t input_height, + int64_t input_width, + int64_t n_output_plane, + int64_t output_depth, + int64_t output_height, + int64_t output_width) { + const int beta = has_bias ? 1 : 0; + + // Compute out = weight * input + // Note gemm expects fortran order, so all 3 matrices are transposed. + // Swapping argument order cancels this, since C == AB <=> T(C) == T(B)T(A) + const int64_t m = output_depth * output_height * output_width; + const int64_t n = (n_output_plane / groups); + const int64_t k = (n_input_plane / groups) * kernel_depth * kernel_height * kernel_width; + + const int64_t lda = m; + const int64_t ldb = k; + const int64_t ldc = m; + + at::native::cpublas::gemm_batched_with_stride( + TransposeType::NoTranspose, + TransposeType::NoTranspose, + groups, m, n, k, + static_cast(1), + finput.data(), lda, finput.stride(0) * k, + weight.data(), ldb, weight.stride(0) * n, + static_cast(beta), + output.data(), ldc, output.stride(0) * n); +} + +template +void slow_conv3d_backward_update_grad_input_frame( + TensorAccessor grad_input, + TensorAccessor grad_output, + TensorAccessor weight, + TensorAccessor fgrad_input, + int64_t kernel_depth, + int64_t kernel_height, + int64_t kernel_width, + int64_t stride_depth, + int64_t stride_height, + int64_t stride_width, + int64_t pad_depth, + int64_t pad_height, + int64_t pad_width, + int64_t groups) { + // Compute fgrad_input = weight.T * grad_output.reshape({grad_output.shape(0), -1}) + // Note gemm expects fortran order, so all 3 matrices are transposed. + // Swapping argument order cancels this, since C == AB <=> T(C) == T(B)T(A) + const int64_t m = grad_output.size(1) * grad_output.size(2) * grad_output.size(3); + const int64_t n = weight.size(1); + const int64_t k = weight.size(0) / groups; + + const int64_t lda = m; + const int64_t ldb = n; + const int64_t ldc = m; + + at::native::cpublas::gemm_batched_with_stride( + TransposeType::NoTranspose, + TransposeType::Transpose, + groups, m, n, k, + static_cast(1), + grad_output.data(), lda, grad_output.stride(0) * k, + weight.data(), ldb, weight.stride(0) * k, + static_cast(0), + fgrad_input.data(), ldc, fgrad_input.stride(0) * n); + + Unfold3dAccCPU( + c10::CppTypeToScalarType::value, + fgrad_input.data(), + grad_input.size(0), + grad_input.size(1), + grad_input.size(2), + grad_input.size(3), + grad_output.size(1), + grad_output.size(2), + grad_output.size(3), + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + grad_input.data()); +} + +void slow_conv3d_backward_out_cpu_template( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + int64_t groups) { + const int64_t kernel_depth = kernel_size[0]; + const int64_t kernel_height = kernel_size[1]; + const int64_t kernel_width = kernel_size[2]; + const int64_t pad_depth = padding[0]; + const int64_t pad_height = padding[1]; + const int64_t pad_width = padding[2]; + const int64_t stride_depth = stride[0]; + const int64_t stride_height = stride[1]; + const int64_t stride_width = stride[2]; + + slow_conv3d_shape_check( + input, + grad_output, + weight, + Tensor(), + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + groups, + false); + + const Tensor weight2d = view_weight_2d(weight); + const Tensor grad_output_contiguous = grad_output.contiguous(); + grad_input.resize_as_(input); + TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous") + + const int64_t dim_planes = 1; + const int64_t dim_depth = 2; + const int64_t dim_height = 3; + const int64_t dim_width = 4; + const int64_t n_input_plane = input.size(dim_planes); + const int64_t input_depth = input.size(dim_depth); + const int64_t input_height = input.size(dim_height); + const int64_t input_width = input.size(dim_width); + const int64_t output_depth = + (input_depth + 2 * pad_depth - kernel_depth) / stride_depth + 1; + const int64_t output_height = + (input_height + 2 * pad_height - kernel_height) / stride_height + 1; + const int64_t output_width = + (input_width + 2 * pad_width - kernel_width) / stride_width + 1; + const int64_t batch_size = input.size(0); + + Tensor fgrad_input = at::empty({batch_size, + n_input_plane * kernel_depth * kernel_height * kernel_width, + output_depth * output_height * output_width}, input.options()); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, input.scalar_type(), "slow_conv3d_cpu_grad_input", [&] { + auto grad_input_a = grad_input.accessor(); + auto grad_output_a = grad_output_contiguous.accessor(); + auto fgrad_input_a = fgrad_input.accessor(); + auto weight_2d_a = weight2d.accessor(); + at::parallel_for(0, batch_size, CONV3D_GRAIN_SALT, + [&](int64_t start, int64_t end) { + + for (const auto t : c10::irange(start, end)) { + auto grad_input_t = grad_input_a[t]; + auto grad_output_t = grad_output_a[t]; + auto fgrad_input_t = fgrad_input_a[t]; + slow_conv3d_backward_update_grad_input_frame( + grad_input_t, + grad_output_t, + weight_2d_a, + fgrad_input_t, + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + groups); + } + }); + }); +} + +template +void slow_conv3d_backward_weight_frame( + TensorAccessor grad_weight, + TensorAccessor grad_output, + TensorAccessor finput, + int64_t groups) { + // Compute grad_weight += grad_output.reshape({grad_output.shape(0), -1}) * finput.T + // Note gemm expects fortran order, so all 3 matrices are transposed. + // Swapping argument order cancels this, since C == AB <=> T(C) == T(B)T(A) + const int64_t m = grad_weight.size(1); + const int64_t n = grad_weight.size(0) / groups; + const int64_t k = grad_output.size(1) * grad_output.size(2) * grad_output.size(3); + + const int64_t lda = k; + const int64_t ldb = k; + const int64_t ldc = m; + + at::native::cpublas::gemm_batched_with_stride( + TransposeType::Transpose, + TransposeType::NoTranspose, + groups, m, n, k, + static_cast(1), + finput.data(), lda, finput.stride(0) * m, + grad_output.data(), ldb, grad_output.stride(0) * n, + static_cast(1), + grad_weight.data(), ldc, grad_weight.stride(0) * n); +} + +void slow_conv3d_backward_parameters_out_cpu_template( + Tensor& grad_weight, + const Tensor& input, + const Tensor& grad_output, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + int64_t groups) { + CheckedFrom c = "slow_conv3d_backward_parameters_cpu"; + auto grad_weight_arg = TensorArg(grad_weight, "grad_weight_arg", 0); + + const int64_t kernel_depth = kernel_size[0]; + const int64_t kernel_height = kernel_size[1]; + const int64_t kernel_width = kernel_size[2]; + const int64_t pad_depth = padding[0]; + const int64_t pad_height = padding[1]; + const int64_t pad_width = padding[2]; + const int64_t stride_depth = stride[0]; + const int64_t stride_height = stride[1]; + const int64_t stride_width = stride[2]; + + slow_conv3d_shape_check( + input, + grad_output, + grad_weight, + {}, + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + groups, + true); + + Tensor grad_weight_2d = view_weight_2d(grad_weight); + checkContiguous(c, grad_weight_arg); + + auto grad_output_contiguous = grad_output.contiguous(); + + const int64_t batch_size = input.size(0); + Tensor finput = compute_columns3d(input, stride, padding, kernel_size, groups); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, input.scalar_type(), "slow_conv3d_cpu_grad_weight", [&] { + auto grad_weight_2d_a = grad_weight_2d.accessor(); + auto grad_output_a = grad_output_contiguous.accessor(); + auto finput_a = finput.accessor(); + for (const auto t : c10::irange(batch_size)) { + auto grad_output_t = grad_output_a[t]; + auto finput_t = finput_a[t]; + slow_conv3d_backward_weight_frame( + grad_weight_2d_a, grad_output_t, finput_t, groups); + } + }); +} + +} // namespace + +Tensor& slow_conv3d_forward_out_cpu(const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding, + Tensor& output) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + TORCH_CHECK( + kernel_size.size() == 3, + "It is expected kernel_size equals to 3, but got size ", + kernel_size.size()); + + TORCH_CHECK( + padding.size() == 3, + "It is expected padding equals to 3, but got size ", + padding.size()); + + TORCH_CHECK( + stride.size() == 3, + "It is expected stride equals to 3, but got size ", + stride.size()); + + const int64_t kernel_depth = kernel_size[0]; + const int64_t kernel_height = kernel_size[1]; + const int64_t kernel_width = kernel_size[2]; + const int64_t pad_depth = padding[0]; + const int64_t pad_height = padding[1]; + const int64_t pad_width = padding[2]; + const int64_t stride_depth = stride[0]; + const int64_t stride_height = stride[1]; + const int64_t stride_width = stride[2]; + + // TODO: hacky way of deciding the groups + // Assuming the group size is checked in upstream functions + const int64_t groups = weight.size(1) > 0 ? self.size(1) / weight.size(1) : 0; + + slow_conv3d_shape_check( + self, + Tensor(), + weight, + bias, + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + groups, + false); + + const Tensor input = self.contiguous(); + const Tensor weight_2d = view_weight_2d(weight); + + const int64_t dim_planes = 1; + const int64_t dim_depth = 2; + const int64_t dim_height = 3; + const int64_t dim_width = 4; + + const int64_t n_input_plane = input.size(dim_planes); + const int64_t input_depth = input.size(dim_depth); + const int64_t input_height = input.size(dim_height); + const int64_t input_width = input.size(dim_width); + const int64_t n_output_plane = weight_2d.size(0); + const int64_t output_depth = + (input_depth + 2 * pad_depth - kernel_depth) / stride_depth + 1; + const int64_t output_height = + (input_height + 2 * pad_height - kernel_height) / stride_height + 1; + const int64_t output_width = + (input_width + 2 * pad_width - kernel_width) / stride_width + 1; + + Tensor finput = compute_columns3d(input, stride, padding, kernel_size, groups); + const int64_t batch_size = input.size(0); + output.resize_( + {batch_size, n_output_plane, output_depth, output_height, output_width}); + if (bias.defined()) { + output.copy_(bias.reshape({-1, 1, 1, 1})); + } + + TORCH_CHECK(output.is_contiguous(), "slow_conv3d output must be contiguous"); + + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "slow_conv3d_cpu", [&] { + auto input_a = input.accessor(); + auto output_a = output.accessor(); + auto finput_a = finput.accessor(); + auto weight_2d_a = weight_2d.accessor(); + + at::parallel_for( + 0, batch_size, CONV3D_GRAIN_SALT, [&](int64_t start, int64_t end) { + for (const auto t : c10::irange(start, end)) { + auto input_t = input_a[t]; + auto output_t = output_a[t]; + auto finput_t = finput_a[t]; + slow_conv3d_update_output_frame( + input_t, + output_t, + weight_2d_a, + bias.defined(), + finput_t, + kernel_depth, + kernel_height, + kernel_width, + stride_depth, + stride_height, + stride_width, + pad_depth, + pad_height, + pad_width, + n_input_plane, + groups, + input_depth, + input_height, + input_width, + n_output_plane, + output_depth, + output_height, + output_width); + } + }); + }); + + return output; +} + +Tensor slow_conv3d_forward_cpu( + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + auto output = at::empty({0}, self.options()); + at::native::slow_conv3d_forward_out_cpu( + self, + weight, + kernel_size, + bias, + stride, + padding, + output); + return output; +} + +static std::tuple slow_conv3d_backward_out_cpu(const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + Tensor& grad_input, + Tensor& grad_weight, + Tensor& grad_bias) { + TORCH_CHECK( + kernel_size.size() == 3, + "It is expected kernel_size equals to 3, but got size ", + kernel_size.size()); + + TORCH_CHECK( + padding.size() == 3, + "It is expected padding equals to 3, but got size ", + padding.size()); + + TORCH_CHECK( + stride.size() == 3, + "It is expected stride equals to 3, but got size ", + stride.size()); + + // TODO: hacky way of determine the group size + int64_t groups = self.size(1) / weight.size(1); + if (grad_input.defined()) { + slow_conv3d_backward_out_cpu_template( + grad_input, + grad_output, + self, + weight, + kernel_size, + stride, + padding, + groups); + } + + if (grad_bias.defined()) { + at::sum_out(grad_bias, grad_output, IntArrayRef{0, 2, 3, 4}); + } + + if (grad_weight.defined()) { + grad_weight.resize_(weight.sizes()); + grad_weight.zero_(); + slow_conv3d_backward_parameters_out_cpu_template( + grad_weight, + self, + grad_output, + kernel_size, + stride, + padding, + groups); + } + + return std::tuple( + grad_input, grad_weight, grad_bias); +} + +std::tuple slow_conv3d_backward_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + std::array output_mask) { + Tensor grad_input; + Tensor grad_weight; + Tensor grad_bias; + + if (output_mask[0]) { + grad_input = at::empty({0}, grad_output.options()); + } + + if (output_mask[1]) { + grad_weight = at::empty({0}, grad_output.options()); + } + + if (output_mask[2]) { + grad_bias = at::empty({0}, grad_output.options()); + } + + at::native::slow_conv3d_backward_out_cpu( + grad_output, + self, + weight, + kernel_size, + stride, + padding, + grad_input, + grad_weight, + grad_bias); + + return std::make_tuple( + std::move(grad_input), std::move(grad_weight), std::move(grad_bias)); +} + +Tensor& slow_conv3d_out(const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding, + Tensor& output) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + return at::slow_conv3d_forward_out( + output, + self, + weight, + kernel_size, + bias, + stride, + padding); +} + +Tensor slow_conv3d( + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + return at::slow_conv3d_forward(self, weight, kernel_size, bias, stride, padding); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM3d.h b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM3d.h new file mode 100644 index 0000000000000000000000000000000000000000..6db6f69d96a67c04ef0e689d88c1cf40392d9e18 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionMM3d.h @@ -0,0 +1,14 @@ +#include + +namespace at::native { + +std::tuple slow_conv3d_backward_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + std::array output_mask); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionTBC.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionTBC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b342414df8f61232dabe6e3116e5f33dd066f4d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ConvolutionTBC.cpp @@ -0,0 +1,121 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { + +Tensor conv_tbc(const Tensor& self, const Tensor& weight, const Tensor& bias, int64_t pad) { + TORCH_CHECK(self.dim() == 3, "Input must have 3 dims: time, batch, " + "in_channel"); + TORCH_CHECK(weight.dim() == 3, "Weight tensor must have 3 dims: kernel_width," + " in_channels, out_channels."); + TORCH_CHECK(bias.dim() == 1, "Bias must be 1-D"); + + auto input_size = self.sizes(); + auto weight_size = weight.sizes(); + + auto ilen = input_size[0]; + auto batchSize = input_size[1]; + auto inputPlanes = input_size[2]; + auto outputPlanes = weight_size[2]; + auto kw = weight_size[0]; + auto olen = input_size[0] - kw + 1 + pad * 2; + auto real_pad = (olen - ilen + kw - 1) / 2; + + // Make sure shapes are correct. + // Input = (time, batch, in_channels) + // Weight = (kernel_width, in_channels, out_channels) + // Bias = (out_channels) + TORCH_CHECK(inputPlanes == weight_size[1], "Input dim 2 (input channels) " + "is not == dim 1 in the weight tensor"); + TORCH_CHECK(weight_size[2] == bias.sizes()[0], "Bias size must equal dim 2 in " + "the weight tensor (output channels)."); + + // input * weights + bias -> output_features + Tensor output = at::empty({ + olen, + input_size[1], + weight_size[2], + }, self.options()); + output.copy_(bias.expand(output.sizes())); + for (const auto k : c10::irange(kw)) { + int iShift = std::max(0, static_cast(k - real_pad)); + int oShift = std::max(0, static_cast(real_pad - k)); + long t = std::min(ilen + real_pad - k, olen) - oShift; + // Note: gemm assumes column-major matrices + // input is l*m (row-major) + // weight is m*r (row-major) + // output is l*r (row-major) + if (t > 0) { + auto W = weight[k]; + auto I = self.narrow(0, iShift, t).view({t * batchSize, inputPlanes}); + auto O = output.narrow(0, oShift, t).view({t * batchSize, outputPlanes}); + O.addmm_(I, W); + } + } + return output; +} + +std::tuple conv_tbc_backward(const Tensor& dOutput, const Tensor& input, const Tensor& weight, const Tensor& bias, int64_t pad) { + auto input_size = input.sizes(); + auto weight_size = weight.sizes(); + + auto ilen = input_size[0]; + auto batchSize = input_size[1]; + auto inputPlanes = input_size[2]; + auto outputPlanes = weight_size[2]; + auto kw = weight.sizes()[0]; + auto olen = input_size[0] - kw + 1 + pad * 2; + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + int real_pad = (olen - ilen + kw - 1) / 2; + + Tensor dInput = at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + for (int k = 0; k < kw; k++) { + int iShift = std::max(0, k - real_pad); + int oShift = std::max(0, real_pad - k); + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + int t = std::min(ilen + real_pad - k, olen) - oShift; + // dOutput * T(weight) -> dInput + if (t > 0) { + auto dO = dOutput.narrow(0, oShift, t).view({t * batchSize, outputPlanes}); + auto dI = dInput.narrow(0, iShift, t).view({t * batchSize, inputPlanes}); + dI.addmm_(dO, weight[k].t()); + } + } + + Tensor dWeight = at::zeros_like(weight, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + for (int k = 0; k < kw; k++) { + int iShift = std::max(0, k - real_pad); + int oShift = std::max(0, real_pad - k); + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + int t = std::min(ilen + real_pad - k, olen) - oShift; + // T(input) * dOutput -> dWeight + if (t > 0) { + auto dW = dWeight[k]; + auto dO = dOutput.narrow(0, oShift, t).view({t * batchSize, outputPlanes}); + auto I = input.narrow(0, iShift, t).view({t * batchSize, inputPlanes}).t(); + dW.addmm_(I, dO); + } + } + + Tensor dBias = at::zeros_like(bias, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + auto tmp = dOutput.sum(0, false); + dBias.copy_(tmp.sum(0)); + + return std::make_tuple( + std::move(dInput), std::move(dWeight), std::move(dBias)); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Copy.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Copy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc0e850cced5a88579e1cc6228ba67b6e9c17b4b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Copy.cpp @@ -0,0 +1,388 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#ifdef USE_FBGEMM +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi") +#include +#include +C10_DIAGNOSTIC_POP() +#endif + +namespace { + +using namespace at; + +bool copy_transpose_valid(const Tensor& self, const Tensor& src) { + const int MIN_SZ = 60 * 60; + return self.is_contiguous() && src.numel() != 0 && src.dim() == 2 && + src.stride(0) == 1 && src.stride(1) == src.size(0) && + self.scalar_type() == src.scalar_type() && + !isBitsType(self.scalar_type()) && + self.sizes().equals(src.sizes()) && + self.is_neg() == src.is_neg() && + self.is_conj() == src.is_conj() && + self.numel() >= MIN_SZ; +} + +#if !defined(C10_MOBILE) +#define _AT_DISPATCH_CP_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_V2( \ + TYPE, NAME, AT_WRAP(__VA_ARGS__), kComplexHalf, kBComplex32, kHalf, kBool, kBFloat16, \ + AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)) +#else +#define _AT_DISPATCH_CP_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5( \ + kComplexHalf, kBComplex32, kHalf, \ + kBool, kBFloat16, TYPE, NAME, \ + __VA_ARGS__) +#endif + +// special case copy where tensor is contiguous and src is a transposed matrix +// This can be generalized to most copies, but it's trickier +void copy_same_type_transpose_(Tensor& self, const Tensor& src) { + int64_t BLOCK_SZ = 0; + if (self.scalar_type() == kByte) { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) + BLOCK_SZ = 120; + } else { + // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) + BLOCK_SZ = 60; + } + Tensor buf = empty({BLOCK_SZ, BLOCK_SZ}, self.options()); + + // The code below is implemented with the assumption that sizes are equal + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(self.sizes().equals(src.sizes())); + + _AT_DISPATCH_CP_TYPES(self.scalar_type(), "copy_", [&] { + const scalar_t* sp = src.const_data_ptr(); + scalar_t* rp = self.data_ptr(); + scalar_t* bp = buf.data_ptr(); + + int64_t NR = src.size(0); + int64_t NC = src.size(1); + for (int64_t R = 0; R < NR; R += BLOCK_SZ) { + for (int64_t C = 0; C < NC; C += BLOCK_SZ) { + const scalar_t* spo = sp + R + C * NR; + scalar_t* rpo = rp + C + R * NC; + + int nr = std::min(NR - R, BLOCK_SZ); + int nc = std::min(NC - C, BLOCK_SZ); + + // 1. copy columns from src to buf + for (const auto c : c10::irange(nc)) { + memcpy(bp + c * BLOCK_SZ, spo + c * NR, nr * sizeof(scalar_t)); + } + + // 2. transpose buf in place + int rc_max = std::max(nr, nc); + int rc_min = std::min(nr, nc); + for (const auto r : c10::irange(rc_max)) { + int end = std::min(r, rc_min); + for (const auto c : c10::irange(end)) { + scalar_t tmp = bp[r + BLOCK_SZ * c]; + bp[r + BLOCK_SZ * c] = bp[r * BLOCK_SZ + c]; + bp[r * BLOCK_SZ + c] = tmp; + } + } + + // 3. copy rows from buf to dst + for (const auto r : c10::irange(nr)) { + memcpy(rpo + r * NC, bp + r * BLOCK_SZ, nc * sizeof(scalar_t)); + } + } + } + }); +} + +// Devices directly supported by this copy implementation. Other device types +// (e.g. XLA) may be supported by overriding copy_ and _copy_from. +bool is_supported_device(Device device) { + DeviceType device_type = device.type(); + return device_type == kCPU || device_type == kCUDA || device_type == kHIP || device_type == kVulkan || device_type == kMetal || device_type == kMPS || device_type == kXPU; +} + +} // namespace + +namespace at::native { + +static Tensor & copy_impl(Tensor & self, const Tensor & src, bool non_blocking) { + // TODO: this should be handled during dispatch, but that's missing... + TORCH_CHECK(self.defined(), "self is undefined"); + TORCH_CHECK(src.defined(), "src is undefined"); + + // FBGeMM kernel support exists only for the following case, + // 1. Memory Format for source and destination tensors is contiguous. + // 2. Device for both the source and destination tensor is CPU. + // 3. dtype conversion between FP32->FP16 and FP16->FP32. + // This checks that self.sizes() == src.sizes() because this code path doesn't + // support broadcasting. This also guards against out of bounds memory access + // when copying, see fbgemm::Float16ToFloat_ref. + // https://github.com/pytorch/pytorch/issues/88543 + #ifdef USE_FBGEMM + if (((self.dtype() == at::kFloat && src.dtype() == at::kHalf) || + (self.dtype() == at::kHalf && src.dtype() == at::kFloat)) && + (self.device().is_cpu() && src.device().is_cpu()) && + ((self.is_contiguous() && src.is_contiguous()) || + (self.is_non_overlapping_and_dense() && self.strides() == src.strides())) && + (self.sizes() == src.sizes())) { + if (src.dtype() == at::kFloat && self.dtype() == at::kHalf) { + auto* output_ptr = + reinterpret_cast(self.data_ptr()); + if (self.numel() < at::internal::GRAIN_SIZE) { + fbgemm::FloatToFloat16_simd(src.const_data_ptr(), output_ptr, self.numel()); + } else { + at::parallel_for( + 0, + self.numel(), + at::internal::GRAIN_SIZE, + [&](int64_t begin, int64_t end) { + fbgemm::FloatToFloat16_simd( + src.const_data_ptr() + begin, + output_ptr + begin, + end - begin); + }); + } + } else { + auto in_data = reinterpret_cast( + src.const_data_ptr()); + auto* output_ptr = self.data_ptr(); + if (self.numel() < at::internal::GRAIN_SIZE) { + fbgemm::Float16ToFloat_simd(in_data, output_ptr, self.numel()); + } else { + at::parallel_for( + 0, + self.numel(), + at::internal::GRAIN_SIZE, + [&](int64_t begin, int64_t end) { + fbgemm::Float16ToFloat_simd( + in_data + begin, output_ptr + begin, end - begin); + }); + } + } + return self; + } + #endif + + if (self.is_same(src)) { + return self; + } + + // Copies into meta self are OK and just ignored (similar to inplace) + if (self.is_meta()) { + auto shape = infer_size_symdimvector(self.sym_sizes(), src.sym_sizes()); + TORCH_CHECK( + self.sym_sizes().equals(shape), + "output with shape ", + self.sym_sizes(), + " doesn't match the broadcast shape ", + shape); + return self; + } + + if (src.is_meta()) { + TORCH_CHECK_NOT_IMPLEMENTED(false, "Cannot copy out of meta tensor; no data!") + } + + // Re-dispatch copies when either src or self device not implemented here (e.g. XLA). + // _copy_from has a proper device dispatch setup. + // This includes: + // cpu_tensor.copy_(xla_tensor) => xla_tensor._copy_from(cpu_tensor) + // xla_tensor.copy_(cpu_tensor) => cpu_tensor._copy_from(xla_tensor) + // Both the _copy_from calls above will be dispatched to XLA's _copy_from kernels. + + if (!is_supported_device(src.device()) || !is_supported_device(self.device())) { + at::_copy_from(src, self, non_blocking); + return self; + } + + if (self.is_quantized() && !src.is_quantized()) { + return quantized_copy_from_float_(self, src); + } + + if (self.is_quantized() && src.is_quantized()) { + TORCH_CHECK(self.qscheme() == src.qscheme(), + "Quantized Copy only works with same qscheme"); + TORCH_CHECK(self.scalar_type() == src.scalar_type()); + set_quantizer_(self, src.quantizer()); + } + + if (!self.is_quantized() && src.is_quantized()) { + TORCH_CHECK(false, "Copying from quantized Tensor to non-quantized Tensor is not allowed, please use dequantize to get a float Tensor from a quantized Tensor"); + } + + if (self.device().type() == at::kVulkan || src.device().type() == at::kVulkan) { + #ifdef USE_VULKAN_API + return vulkan::ops::copy_(self, src); + #else + return at::vulkan::vulkan_copy_(self, src); + #endif + } + + if (self.device().type() == at::kMetal || src.device().type() == at::kMetal) { + return at::metal::metal_copy_(self, src); + } + + // Exit early if self and src are views of the same data + const bool is_same_data = ( + self.is_alias_of(src) && + self.storage_offset() == src.storage_offset() && + self.strides().equals(src.strides()) && + self.sizes().equals(src.sizes()) && + self.scalar_type() == src.scalar_type() && + self.is_conj() == src.is_conj() && + self.is_neg() == src.is_neg() + ); + if (is_same_data) { + return self; + } + + + auto iter = TensorIteratorConfig() + .add_output(self) + .add_const_input(src) + .resize_outputs(false) + .check_all_same_dtype(false) + .check_all_same_device(false) + .build(); + + if (iter.numel() == 0) { + return self; + } + + DeviceType device_type = iter.device_type(0); + if (iter.device_type(1) == kCUDA) { + device_type = kCUDA; + } else if (iter.device_type(1) == kHIP) { + device_type = kHIP; + } else if (iter.device_type(1) == kMPS) { + device_type = kMPS; + } else if (iter.device_type(1) == kXPU){ + device_type = kXPU; + } + + // TODO: if we need to, we can also enable this path for quantized tensor + if (device_type == kCPU && copy_transpose_valid(self, src) && !self.is_quantized()) { + copy_same_type_transpose_(self, src); + return self; + } + +#ifdef USE_MPS + if (self.device().type() == at::kMPS || src.device().type() == at::kMPS) { + return at::native::mps::mps_copy_(self, src, non_blocking); + } +#endif + + if(!(self.is_complex() || self.dtype() == at::kBool) && src.is_complex()) { + TORCH_WARN_ONCE("Casting complex values to real discards the imaginary part"); + } + copy_stub(device_type, iter, non_blocking); + return self; +} + +Tensor copy_meta(const Tensor& self, const Tensor& src, bool non_blocking) { + // Must directly use self(), so we can dispatch properly is self is a subclass + auto r = clone_preserve_strides(self); + r.copy_(src, non_blocking); + return r; +} + +Tensor copy(const Tensor& self, const Tensor& src, bool non_blocking) { + at::Tensor r; + // copy() is the "functional" form of copy_(). It exists so we can properly functionalize copy_(), but: + // (1) It isn't exposed to the frontend (no python bindings) + // (2) It isn't exposed to the backend (it's a composite, that decomposes into to() and expand_as() calls. + auto self_storage = self.unsafeGetTensorImpl()->unsafe_storage().unsafeGetStorageImpl(); + // If self has no real storage, we can't actually clone it. + // Instead, generate an empty tensor with the right sizes/strides, since we should be able to assume + // that copy_() will fully overwrite all data with that of src + if (self_storage->nbytes() == 0) { + r = at::empty_strided(self.sizes(), self.strides(), self.options()); + } else { + r = clone_preserve_strides(self); + } + r.copy_(src, non_blocking); + return r; +} + +::std::vector _foreach_copy(at::TensorList self, at::TensorList src, bool non_blocking) { + std::vector outs; + outs.reserve(self.size()); + // This is a very slow implementation, but needs to directly call the copy() kernel above to handle + // when self has zero storage. + // This kernel should never really be run, except with debugging using compile(backend="aot_eager") + for (const auto i : c10::irange(src.size())) { + const auto& curr_src = src[i]; + const auto& curr_self = self[i]; + outs.push_back(at::copy(curr_self, curr_src, non_blocking)); + } + return outs; +} + +Tensor& copy_(Tensor& self, const Tensor& src, bool non_blocking) { + { + if (self._is_zerotensor()) { + TORCH_CHECK(false, "ZeroTensors are immutable. Please materialize the tensor using `.clone()`, if you want a mutable zero tensor."); + } + if (src._is_zerotensor()) { + return self.zero_(); + } + copy_impl(self, src, non_blocking); + } + return self; +} + +void copy_ignoring_overlaps(const TensorBase &dst, const TensorBase &src) { + // Called when we are copying into an overlapping index `dst`, but we don't + // care which writer wins. Hacky but it works. This is only used by + // CUDA_tensor_apply2 in case that there are write overlaps. + // FIXME: really, overlapping writes should be illegal/an error in Torch + auto iter = TensorIteratorConfig() + .add_output(dst) + .add_const_input(src) + .resize_outputs(false) + .set_check_mem_overlap(false) + .check_all_same_dtype(true) + .check_all_same_device(true) + .build(); + copy_stub(iter.device_type(), iter, /*non_blocking=*/false); +} + +void _propagate_xla_data(const Tensor& input, const Tensor& output) { + TORCH_INTERNAL_ASSERT(input.device().type() == kXLA, "This op should only be called by XLA") +} + +DEFINE_DISPATCH(copy_stub); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Copy.h b/western_ai/usa/pytorch/aten/src/ATen/native/Copy.h new file mode 100644 index 0000000000000000000000000000000000000000..2aeae0097c817cd8b642cf8da67b124b6e19a6f3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Copy.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace at { + +class Tensor; +struct TensorIterator; +class TensorBase; + +namespace native { + +using copy_fn = void (*)(TensorIterator&, bool non_blocking); + +DECLARE_DISPATCH(copy_fn, copy_stub) + +TORCH_API void copy_ignoring_overlaps(const TensorBase &dst, const TensorBase &src); + +} // namespace native +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Correlation.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Correlation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b8aeadcada9db33e85c61d66d80cca238e601a3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Correlation.cpp @@ -0,0 +1,189 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +Tensor cov( + const Tensor& self, + int64_t correction, + const std::optional& fweights, + const std::optional& aweights) { + constexpr int64_t OBSERVATIONS_DIM = 1; + + TORCH_CHECK( + self.ndimension() <= 2, + "cov(): expected input to have two or fewer dimensions but got an input with ", + self.ndimension(), + " dimensions"); + + TORCH_CHECK( + self.scalar_type() != kBool, + "cov(): bool dtype is not supported for input"); + + // View input tensor as 2D (variables, observations) + auto in = self.ndimension() < 2 ? self.view({1, -1}) : self; + const auto num_observations = in.size(OBSERVATIONS_DIM); + + // The product of frequencies (fweights) and weights (aweights). + Tensor w; + + if (fweights.has_value()) { + w = fweights.value(); + TORCH_CHECK( + w.ndimension() <= 1, + "cov(): expected fweights to have one or fewer dimensions but got fweights with ", + w.ndimension(), + " dimensions"); + TORCH_CHECK( + at::isIntegralType(w.scalar_type(), false), + "cov(): expected fweights to have integral dtype but got fweights with ", + w.scalar_type(), + " dtype"); + TORCH_CHECK( + w.numel() == num_observations, + "cov(): expected fweights to have the same numel as there are observations in the input but got ", + w.numel(), + " != ", + num_observations); + TORCH_CHECK( + num_observations == 0 || at::is_scalar_tensor_true(w.min().ge(0)), + "cov(): fweights cannot be negative"); + } + + if (aweights.has_value()) { + const auto& aw = aweights.value(); + TORCH_CHECK( + aw.ndimension() <= 1, + "cov(): expected aweights to have one or fewer dimensions but got aweights with ", + aw.ndimension(), + " dimensions"); + TORCH_CHECK( + at::isFloatingType(aw.scalar_type()), + "cov(): expected aweights to have floating point dtype but got aweights with ", + aw.scalar_type(), + " dtype"); + TORCH_CHECK( + aw.numel() == num_observations, + "cov(): expected aweights to have the same numel as there are observations in the input but got ", + aw.numel(), + " != ", + num_observations); + TORCH_CHECK( + num_observations == 0 || at::is_scalar_tensor_true(aw.min().ge(0)), + "cov(): aweights cannot be negative"); + w = w.defined() ? w * aw : aw; + } + + // Compute a weighted average of the observations + const auto w_sum = w.defined() + ? w.sum() + : at::scalar_tensor(num_observations, in.options().dtype(kLong)); + + TORCH_CHECK( + !w.defined() || at::is_scalar_tensor_true(w_sum.ne(0)), + "cov(): weights sum to zero, can't be normalized"); + + const auto avg = (w.defined() ? in * w : in).sum(OBSERVATIONS_DIM) / w_sum; + + // Compute the normalization factor + Tensor norm_factor; + + if (!w.defined()) { + norm_factor = at::scalar_tensor(num_observations - correction, in.options().dtype(kLong)); + } + else if (correction == 0) { + norm_factor = w_sum; + } + else if (!aweights.has_value()) { + norm_factor = w_sum - correction; + } + else { + if (!fweights.has_value() && num_observations == 1 && correction == 1) { + // corner case that was causing rounding error and deviating from numpy result + norm_factor = at::scalar_tensor(0, in.options().dtype(kLong)); + } else { + norm_factor = w_sum - correction * (w * aweights.value()).sum() / w_sum; + } + } + + if (at::is_scalar_tensor_true(norm_factor.le(0))) { + TORCH_WARN("cov(): degrees of freedom is <= 0. Correction should be strictly less than the number of observations."); + norm_factor.zero_(); + } + + // Compute covariance matrix + + // corner case that was causing rounding error and deviating from numpy result + // algebraically, if we only have one observation and only one set of weights, the weighted avg == the input + // so we get zero as a result of input - avg. Using != here as logical XOR. + if (num_observations == 1 && fweights.has_value() != aweights.has_value()) { + in.zero_(); + // the in - avg we're replacing below has the side effect of promoting int tensors to float + if (at::isIntegralType(in.scalar_type(), false)) { + in = in.to(kFloat); + } + } + else { + in = in - avg.unsqueeze(1); + } + auto c = at::mm(in, (w.defined() ? in * w : in).t().conj()); + // corner case that was causing rounding error and deviating from numpy result + // If at::mm is doing a dot product of a complex vector with its conjugate + // transpose, algebraically the imag part becomes 0, but in some cases the + // imag part was non-zero but very small 1e-7, and dividing this by 0 caused + // imag to be inf instead of nan (0/0). Zero out the imag part. + if (c.is_complex() && (in.size(0) == 1 || in.size(1) == 1)) { + auto re = at::real(c); + auto im0 = at::zeros_like(re); + c = at::complex(re, im0); + } + return at::true_divide(c, norm_factor).squeeze(); +} + +Tensor corrcoef(const Tensor& self) { + TORCH_CHECK( + self.ndimension() <= 2, + "corrcoef(): expected input to have two or fewer dimensions but got an input with ", + self.ndimension(), + " dimensions"); + + auto c = at::cov(self); + + if (c.ndimension() == 0) { + // scalar covariance, return nan if c in {nan, inf, 0}, 1 otherwise + return c / c; + } + + // normalize covariance + const auto d = c.diagonal(); + const auto stddev = at::sqrt(d.is_complex() ? at::real(d) : d); + c = c / stddev.view({-1, 1}); + c = c / stddev.view({1, -1}); + + // due to floating point rounding the values may be not within [-1, 1], so + // to improve the result we clip the values just as NumPy does. + return c.is_complex() + ? at::complex(at::real(c).clip(-1, 1), at::imag(c).clip(-1, 1)) + : c.clip(-1, 1); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Cross.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Cross.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d4ee325f3cc1125b2c95cafaa43df5ab6004852 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Cross.cpp @@ -0,0 +1,92 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::meta { + +TORCH_META_FUNC(linalg_cross) +(const Tensor & input, const Tensor & other, int64_t dim) { + auto x_d = input.dim(); + auto y_d = other.dim(); + // This is to avoid things like + // linalg.cross(torch.randn(2, 3), torch.randn(5, 2, 3), dim=2) + TORCH_CHECK(x_d == y_d, "linalg.cross: inputs must have the same number of dimensions."); + TORCH_CHECK(input.size(dim) == 3 && other.size(dim) == 3, "linalg.cross: inputs dimension ", dim, " must have length 3. Got ", input.size(dim), " and ", other.size(dim)); + + // Broadcast the batch dimension of input and other. + // Since the non-batch dimensions agree, this is the same as broadcast all the inputs + auto out_size = infer_size(input.sizes(), other.sizes()); + + set_output_raw_strided(0, out_size, {}, input.options()); +} + +} // namespace at::meta +namespace at::native { + +DEFINE_DISPATCH(cross_stub); + +static int64_t _default_cross_dim(const std::optional &dimension, SymIntArrayRef sizes) { + // If dimension is not given, it defaults to the first dimension found with the size 3. + // Note that this behaviour might be unexpected. + // _default_cross_dim is called internally inside the cross implementation to calculate + // the dim and finally cross delegates to the linalg_cross implementation with this dim + if(dimension.has_value()) { + return *dimension; + } + + for(auto i : c10::irange(sizes.size())) { + if(sizes[i] == 3) { + return i; + } + } + TORCH_CHECK(false, "no dimension of size 3 in input"); +} + +Tensor cross(const Tensor & input, const Tensor & other, const std::optional dimension) { + if (!dimension) { + TORCH_WARN_ONCE( + "Using torch.cross without specifying the dim arg is deprecated.\n", + "Please either pass the dim explicitly or simply use torch.linalg.cross.\n", + "The default value of dim will change to agree with that of linalg.cross in a future release." + ); + } + auto dim = _default_cross_dim(dimension, input.sym_sizes()); + return at::linalg_cross(input, other, dim); +} + +Tensor & cross_out(const Tensor & input, const Tensor & other, const std::optional dimension, Tensor & out) { + auto dim = _default_cross_dim(dimension, input.sym_sizes()); + return at::linalg_cross_out(out, input, other, dim); +} + + +TORCH_IMPL_FUNC(linalg_cross_out) +(const Tensor & input, const Tensor & other, int64_t dim, const Tensor & out) { + at::assert_no_internal_overlap(out); + at::assert_no_overlap(out, input); + at::assert_no_overlap(out, other); + dim = maybe_wrap_dim(dim, input.dim()); + auto out_size = out.sizes(); + Tensor input_broadcasted = input.expand(out_size); + Tensor other_broadcasted = other.expand(out_size); + + cross_stub(input.device().type(), out, input_broadcasted, other_broadcasted, dim); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Cross.h b/western_ai/usa/pytorch/aten/src/ATen/native/Cross.h new file mode 100644 index 0000000000000000000000000000000000000000..7230219704b07fbd6a48f5faac7ab9e74f047720 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Cross.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace at { +class Tensor; + +namespace native { + +using cross_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const int64_t d); + +DECLARE_DISPATCH(cross_fn, cross_stub) + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/DilatedConvolutionUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/DilatedConvolutionUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..7d524c3800f79a391b784d9151756efd7fb0c6ba --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/DilatedConvolutionUtils.h @@ -0,0 +1,230 @@ +#pragma once + +#include +#include + +#include +#include +#include + +#define TORCH_CHECK_DIM_SIZE(T, DIM, DIM_SIZE, SIZE) \ + TORCH_CHECK( \ + T.dim() == DIM && T.size(DIM_SIZE) == SIZE, \ + "Need " #T " of dimension ", \ + DIM, \ + " and " #T ".size[", \ + DIM_SIZE, \ + "] == ", \ + SIZE, \ + " but got input to be of shape ", \ + T.sizes()) + +namespace at::native::internal { +namespace { +inline bool all_positive(IntArrayRef& arr) { + return std::all_of( + arr.begin(), arr.end(), [](int64_t item) { return item > 0; }); +} + +inline bool all_nonnegative(std::vector& arr) { + return std::all_of( + arr.begin(), arr.end(), [](int64_t item) { return item >= 0; }); +} + +} // namespace + +// calculate the rear part of output tensor sizes +template +std::vector get_output_size( + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride_size, + IntArrayRef pad_size, + IntArrayRef dilation_size) { + std::vector sizes; + sizes.reserve(dim); + for (const auto index : c10::irange(dim)) { + sizes.push_back( + div_rtn( + input.size(index + input.dim() - dim) + 2 * pad_size[index] - + (dilation_size[index] * (kernel_size[index] - 1) + 1), + stride_size[index]) + + 1); + } + return sizes; +} + +// calculate the sizes of output tensor +template +std::vector get_output_size( + const Tensor& input, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride_size, + IntArrayRef pad_size, + IntArrayRef dilation_size) { + auto output_size = get_output_size( + input, kernel_size, stride_size, pad_size, dilation_size); + output_size.insert(output_size.begin(), weight.size(0)); + if (input.dim() == dim + 2) { + output_size.insert(output_size.begin(), input.size(0)); + } + return output_size; +} +/* + slow_conv_dilated_shape_check - check user-input to dilated convolution + forward and backward functions. +*/ +template +void slow_conv_dilated_shape_check( + const Tensor& input, + const Tensor& weight, + const Tensor& bias, + const Tensor& grad_output, + IntArrayRef kernel_size, + IntArrayRef stride_size, + IntArrayRef pad_size, + IntArrayRef dilation_size) { + /* + When the following tensors are defined: + + bias, grad_weight, grad_output + + then these are assumed to be contiguous without checking + because of these tensors are made contiguous by calling + .contiguous() method or by resizing of zero-sized tensors in + forward/backward functions. + + When grad_weight is defined then it is assumed without + checking to have the same shape as weight, see backward + functions. + */ + // Check size arguments + TORCH_CHECK( + kernel_size.size() == dim, + "kernel sizes length should be ", + dim, + ", but got ", + kernel_size.size()); + TORCH_CHECK( + stride_size.size() == dim, + "strides length should be ", + dim, + ", but got ", + stride_size.size()); + TORCH_CHECK( + dilation_size.size() == dim, + "dilations length should be ", + dim, + ", but got ", + dilation_size.size()); + TORCH_CHECK( + pad_size.size() == dim, + "pads length should be ", + dim, + ", but got ", + pad_size.size()); + + TORCH_CHECK( + all_positive(kernel_size), + "kernel size should be greater than zero, but got ", + kernel_size); + TORCH_CHECK( + all_positive(stride_size), + "stride should be greater than zero, but got ", + stride_size); + TORCH_CHECK( + all_positive(dilation_size), + "dilation should be greater than zero, but got ", + dilation_size); + + // check input + TORCH_CHECK(input.defined(), "input must be defined"); + bool is_batch = input.dim() == dim + 2; + int64_t n = (is_batch ? 2 : 1); + int64_t ndim = n + dim; + if (!is_batch) { + // input dim has to be dim + 1 if not batched + TORCH_CHECK( + input.dim() == dim + 1, + "input must be 4D or 5D tensor but got ", + input.dim(), + "D tensor"); + } + + // check output sizes + auto output_size = get_output_size( + input, kernel_size, stride_size, pad_size, dilation_size); + + TORCH_CHECK( + all_nonnegative(output_size), + "calculated output size ", + output_size, + " is too small (all sizes must be non-negative)"); + + // check weight + TORCH_CHECK(weight.defined(), "weight must be defined"); + TORCH_CHECK( + weight.dim() == dim + 2, + "weight must be ", + dim + 2, + "D tensor but got ", + weight.dim(), + "D tensor dim=", + dim); + TORCH_CHECK( + weight.sizes().slice(2) == kernel_size, + "weight[2:] shape ", + weight.sizes().slice(2), + " must be equal to kernel_size ", + kernel_size); + + TORCH_CHECK_DIM_SIZE(input, input.dim(), (is_batch ? 1 : 0), weight.size(1)); + + // check bias when present + if (bias.defined()) { + TORCH_CHECK( + bias.dim() == 1, + "bias must be 1D tensor but got ", + bias.dim(), + "D tensor"); + TORCH_CHECK_DIM_SIZE(bias, 1, 0, weight.size(0)); + } + + // check grad_output when present + if (grad_output.defined()) { + TORCH_CHECK( + grad_output.dim() == ndim, + "grad_output must be ", + ndim, + "D tensor but got ", + grad_output.dim(), + "D tensor"); + if (is_batch) { + TORCH_CHECK( + grad_output.size(0) == input.size(0), + "grad_output.size(0)=", + grad_output.size(0), + " must be input.size(0)=", + input.size(0)); + } + TORCH_CHECK( + grad_output.size(n - 1) == weight.size(0), + "grad_output.size(", + n - 1, + ")=", + grad_output.size(n - 1), + " must be weight.size(0)=", + weight.size(0)); + TORCH_CHECK( + grad_output.sizes().slice(n) == output_size, + "grad_output[", + n, + ":] shape", + grad_output.sizes().slice(n), + " must be equal to output size ", + output_size); + } +} + +} // namespace at::native::internal diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/DilatedMaxPool2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/DilatedMaxPool2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93c38621e05470dd2ca5439f4e06c154b7f2a364 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/DilatedMaxPool2d.cpp @@ -0,0 +1,211 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::meta { +using namespace at::native; +TORCH_META_FUNC(max_pool2d_with_indices) +(const Tensor& input, +IntArrayRef kernel_size, +IntArrayRef stride, +IntArrayRef padding, +IntArrayRef dilation, +bool ceil_mode) { + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 2, + "max_pool2d: kernel_size must either be a single int, or a tuple of two ints") + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + // NB: stride default is not expressible as an integer constant, so we accept + // empty stride for this case + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 2, + "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints") + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 2, + "max_pool2d: padding must either be a single int, or a tuple of two ints"); + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + TORCH_CHECK(dilation.size() == 1 || dilation.size() == 2, + "max_pool2d: dilation must be either a single int, or a tuple of two ints"); + const int dilationH = c10::checked_convert(dilation[0], "int"); + const int dilationW = dilation.size() == 1 ? dilationH : c10::checked_convert(dilation[1], "int"); + + const auto memory_format = input.suggest_memory_format(); + if (memory_format == at::MemoryFormat::ChannelsLast) { + TORCH_CHECK(input.ndimension() == 4, + "non-empty 4D (batch mode) tensor expected for input with channels_last layout"); + } else if (memory_format == at::MemoryFormat::Contiguous) { + TORCH_CHECK((input.ndimension() == 3 || input.ndimension() == 4), + "non-empty 3D or 4D (batch mode) tensor expected for input"); + } else { + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + + /* sizes */ + const int64_t nbatch = input.ndimension() == 4 ? input.size(-4) : 1; + const int64_t nInputPlane = input.size(-3); + const int64_t inputHeight = input.size(-2); + const int64_t inputWidth = input.size(-1); + + const int64_t outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode); + const int64_t outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode); + + pool2d_shape_check( + input, + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + nInputPlane, + inputHeight, inputWidth, + outputHeight, outputWidth, memory_format); + + /* resize output and indices */ + + if (input.ndimension() == 3) { + set_output_raw_strided(0, {nInputPlane, outputHeight, outputWidth}, {}, input.options().memory_format(memory_format)); + /* indices will contain the locations for each output point */ + set_output_raw_strided(1, {nInputPlane, outputHeight, outputWidth}, {}, input.options().memory_format(memory_format).dtype(kLong)); + } else { + set_output_raw_strided(0, {nbatch, nInputPlane, outputHeight, outputWidth}, {}, input.options().memory_format(memory_format)); + /* indices will contain the locations for each output point */ + set_output_raw_strided(1, {nbatch, nInputPlane, outputHeight, outputWidth}, {}, input.options().memory_format(memory_format).dtype(kLong)); + } +} + +TORCH_META_FUNC(max_pool2d_with_indices_backward) +(const Tensor& gradOutput, +const Tensor& input, +IntArrayRef kernel_size, +IntArrayRef stride, +IntArrayRef padding, +IntArrayRef dilation, +bool ceil_mode, +const Tensor& indices) { + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 2, + "max_pool2d: kernel_size must either be a single int, or a tuple of two ints") + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + // NB: stride default is not expressible as an integer constant, so we accept + // empty stride for this case + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 2, + "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints") + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 2, + "max_pool2d: padding must either be a single int, or a tuple of two ints"); + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + TORCH_CHECK(dilation.size() == 1 || dilation.size() == 2, + "max_pool2d: dilation must be either a single int, or a tuple of two ints"); + const int dilationH = c10::checked_convert(dilation[0], "int"); + const int dilationW = dilation.size() == 1 ? dilationH : c10::checked_convert(dilation[1], "int"); + + TORCH_CHECK(input.dtype() == gradOutput.dtype(), + "expected dtype ", input.dtype(), " for `gradOutput` but got dtype ", gradOutput.dtype()); + + const auto memory_format = input.suggest_memory_format(); + if (memory_format == at::MemoryFormat::ChannelsLast) { + TORCH_CHECK(input.ndimension() == 4, + "non-empty 4D (batch mode) tensor expected for input with channels_last layout"); + } else if (memory_format == at::MemoryFormat::Contiguous) { + TORCH_CHECK((input.ndimension() == 3 || input.ndimension() == 4), + "non-empty 3D or 4D (batch mode) tensor expected for input"); + } else { + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + + /* sizes */ + const int64_t nInputPlane = input.size(-3); + const int64_t inputHeight = input.size(-2); + const int64_t inputWidth = input.size(-1); + + /* XXX preserve the existing shape check behavior */ + const int64_t outputHeight_for_shape_check = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode); + const int64_t outputWidth_for_shape_check = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode); + + max_pool2d_backward_shape_check( + input, + gradOutput, + indices, + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + nInputPlane, + inputHeight, inputWidth, + outputHeight_for_shape_check, outputWidth_for_shape_check, + memory_format); + + set_output_raw_strided(0, input.sizes(), {}, input.options().memory_format(memory_format)); +} +} // namespace at::meta + +namespace at::native { + +TORCH_IMPL_FUNC(max_pool2d_with_indices_out_cpu) +(const Tensor& input, +IntArrayRef kernel_size, +IntArrayRef stride, +IntArrayRef padding, +IntArrayRef dilation, +bool ceil_mode, +const Tensor& output, +const Tensor& indices) { + + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + const int dilationH = c10::checked_convert(dilation[0], "int"); + const int dilationW = dilation.size() == 1 ? dilationH : c10::checked_convert(dilation[1], "int"); + + max_pool2d_kernel( + kCPU, output, indices, input, + kW, kH, + dW, dH, + padW, padH, + dilationW, dilationH); +} + +TORCH_IMPL_FUNC(max_pool2d_with_indices_backward_out_cpu) +(const Tensor& gradOutput, +const Tensor& input, +IntArrayRef kernel_size, +IntArrayRef stride, +IntArrayRef padding, +IntArrayRef dilation, +bool ceil_mode, +const Tensor& indices, +const Tensor& gradInput) { + + gradInput.zero_(); + max_pool2d_backward_kernel( + kCPU, const_cast(gradInput), + gradOutput, indices); +} + +DEFINE_DISPATCH(max_pool2d_kernel); +DEFINE_DISPATCH(max_pool2d_backward_kernel); + +} // at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/DilatedMaxPool3d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/DilatedMaxPool3d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a02599507534e9f28c9a0ab42ce187dc5cd48aac --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/DilatedMaxPool3d.cpp @@ -0,0 +1,293 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { + +namespace { + + +void max_pool3d_with_indices_out_cpu_template( + Tensor& output, + Tensor& indices, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) +{ + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, + "max_pool3d: kernel_size must either be a single int, or a tuple of three ints") + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, + "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints") + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 3, + "max_pool3d: padding must either be a single int, or a tuple of three ints"); + const int pT = c10::checked_convert(padding[0], "int"); + const int pH = padding.size() == 1 ? pT : c10::checked_convert(padding[1], "int"); + const int pW = padding.size() == 1 ? pT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK(dilation.size() == 1 || dilation.size() == 3, + "max_pool3d: dilation must be either a single int, or a tuple of three ints"); + const int dilationT = c10::checked_convert(dilation[0], "int"); + const int dilationH = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[1], "int"); + const int dilationW = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[2], "int"); + + const auto memory_format = input.suggest_memory_format(); + if (memory_format == at::MemoryFormat::ChannelsLast3d) { + TORCH_CHECK(input.ndimension() == 5, + "non-empty 5D (batch mode) tensor expected for input with channels_last_3d layout"); + } else if (memory_format == at::MemoryFormat::Contiguous) { + TORCH_CHECK((input.ndimension() == 4 || input.ndimension() == 5), + "non-empty 4D or 5D (batch mode) tensor expected for input"); + } else { + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } + + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + const int64_t otime = pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode); + const int64_t oheight = pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode); + const int64_t owidth = pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode); + + pool3d_shape_check( + input, + nslices, + kT, kH, kW, + dT, dH, dW, + pT, pH, pW, + dilationT, dilationH, dilationW, + itime, iheight, iwidth, + otime, oheight, owidth, + "max_pool3d_with_indices_out_cpu_template()"); + + + if (input.dim() == 4) { /* non-batch mode */ + /* resize output */ + output.resize_({nslices, otime, oheight, owidth}); + /* indices will contain ti,i,j locations for each output point */ + indices.resize_({nslices, otime, oheight, owidth}); + } + else { /* batch mode */ + const int64_t nbatch = input.size(0); + + /* resize output */ + output.resize_({nbatch, nslices, otime, oheight, owidth}, memory_format); + /* indices will contain ti,i,j locations for each output point */ + indices.resize_({nbatch, nslices, otime, oheight, owidth}, memory_format); + } + max_pool3d_kernel( + kCPU, output, indices, input, + kW, kH, kT, + dW, dH, dT, + pW, pH, pT, + dilationW, dilationH, dilationT); +} + +Tensor& max_pool3d_with_indices_backward_out_cpu_template( + Tensor& gradInput, + const Tensor& gradOutput, + const Tensor& input, + const Tensor& indices, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) +{ + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, + "max_pool3d: kernel_size must either be a single int, or a tuple of three ints") + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, + "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints") + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 3, + "max_pool3d: padding must either be a single int, or a tuple of three ints"); + const int pT = c10::checked_convert(padding[0], "int"); + const int pH = padding.size() == 1 ? pT : c10::checked_convert(padding[1], "int"); + const int pW = padding.size() == 1 ? pT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK(dilation.size() == 1 || dilation.size() == 3, + "max_pool3d: dilation must be either a single int, or a tuple of three ints"); + const int dilationT = c10::checked_convert(dilation[0], "int"); + const int dilationH = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[1], "int"); + const int dilationW = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[2], "int"); + + TORCH_CHECK(input.dtype() == gradOutput.dtype(), + "expected dtype ", input.dtype(), " for `gradOutput` but got dtype ", gradOutput.dtype()); + + const auto memory_format = input.suggest_memory_format(); + if (memory_format == at::MemoryFormat::ChannelsLast3d) { + TORCH_CHECK(input.ndimension() == 5, + "non-empty 5D (batch mode) tensor expected for input with channels_last_3d layout"); + } else if (memory_format == at::MemoryFormat::Contiguous) { + TORCH_CHECK((input.ndimension() == 4 || input.ndimension() == 5), + "non-empty 4D or 5D (batch mode) tensor expected for input"); + } else { + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } + + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + + /* resize */ + gradInput.resize_(input.sizes(), memory_format); + gradInput.zero_(); + + const int64_t otime = gradOutput.size(-3); + const int64_t oheight = gradOutput.size(-2); + const int64_t owidth = gradOutput.size(-1); + + max_pool3d_backward_shape_check( + input, + gradOutput, + indices, + nslices, + kT, kH, kW, + dT, dH, dW, + pT, pH, pW, + dilationT, dilationH, dilationW, + itime, iheight, iwidth, + otime, oheight, owidth, + "max_pool3d_with_indices_backward_out_cpu_template()"); + + max_pool3d_backward_kernel( + kCPU, gradInput, + gradOutput, indices); + + return gradInput; +} + +} // namespace + +std::tuple max_pool3d_with_indices_out_cpu(const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode, + Tensor& output, + Tensor& indices) +{ + max_pool3d_with_indices_out_cpu_template( + output, + indices, + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + return std::tuple(output, indices); +} + +std::tuple max_pool3d_with_indices_cpu( + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) +{ + + Tensor output = at::empty({0}, input.options()); + Tensor indices = at::empty({0}, input.options().dtype(kLong)); + max_pool3d_with_indices_out_cpu_template( + output, + indices, + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + + return std::tuple(output, indices); +} + +Tensor& max_pool3d_with_indices_backward_out_cpu(const Tensor& gradOutput_, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode, + const Tensor& indices, + Tensor& gradInput) +{ + max_pool3d_with_indices_backward_out_cpu_template( + gradInput, + gradOutput_, + input, + indices, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + return gradInput; +} + +Tensor max_pool3d_with_indices_backward_cpu( + const Tensor& gradOutput_, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode, + const Tensor& indices) +{ + auto gradInput = at::empty({0}, input.options()); + max_pool3d_with_indices_backward_out_cpu_template( + gradInput, + gradOutput_, + input, + indices, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + return gradInput; +} + +DEFINE_DISPATCH(max_pool3d_kernel); +DEFINE_DISPATCH(max_pool3d_backward_kernel); +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/DispatchStub.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/DispatchStub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..571597cebdbf9065dfc4caa86944c2bcba3d7768 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/DispatchStub.cpp @@ -0,0 +1,432 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include + +#if !defined(__s390x__) && !defined(__powerpc__) +#include +#endif +#include +#include +#include + +#ifdef HAVE_ZVECTOR_CPU_DEFINITION +#include +#endif + +namespace at::native { + +#ifdef HAVE_ZVECTOR_CPU_DEFINITION +static inline bool cpu_has_vxe() +{ + return (getauxval(AT_HWCAP) & HWCAP_S390_VXE); +} +#endif + +static CPUCapability compute_cpu_capability() { + const auto envar = c10::utils::get_env("ATEN_CPU_CAPABILITY"); + if (envar.has_value()) { +#if defined(HAVE_VSX_CPU_DEFINITION) + if (envar == "vsx") { + return CPUCapability::VSX; + } +#elif defined(HAVE_ZVECTOR_CPU_DEFINITION) + if (envar == "zvector") { + return CPUCapability::ZVECTOR; + } +#elif defined(HAVE_SVE_CPU_DEFINITION) + int sve_vl = cpuinfo_initialize() ? cpuinfo_get_max_arm_sve_length() : -1; + if (sve_vl > 0 && cpuinfo_has_arm_bf16()) { + if (envar == "sve256") { + if (sve_vl == 256) { + return CPUCapability::SVE256; + } + TORCH_WARN("SVE256 capability not available on hardware. Falling back to DEFAULT"); + return CPUCapability::DEFAULT; + } + if (envar == "sve128") { + if (sve_vl == 128) { + return CPUCapability::SVE128; + } + TORCH_WARN("SVE128 capability not available on hardware. Falling back to DEFAULT"); + return CPUCapability::DEFAULT; + } + if (envar == "sve") { + if (sve_vl == 256) { + return CPUCapability::SVE256; + } + if (sve_vl == 128) { + return CPUCapability::SVE128; + } + TORCH_WARN("SVE capability not available on hardware. Falling back to DEFAULT"); + return CPUCapability::DEFAULT; + } + } +#else +#ifdef HAVE_AVX512_CPU_DEFINITION + if (envar == "avx512") { + return CPUCapability::AVX512; + } +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + if (envar == "avx2") { + return CPUCapability::AVX2; + } +#endif +#endif + if (envar == "default") { + return CPUCapability::DEFAULT; + } + TORCH_WARN("ignoring invalid value for ATEN_CPU_CAPABILITY: ", envar.value()); + } + +#if !defined(__powerpc__) && !defined(__s390x__) && !defined(HAVE_SVE_CPU_DEFINITION) + if (cpuinfo_initialize()) { +#if defined(HAVE_AVX512_CPU_DEFINITION) + // GCC supports some AVX512 intrinsics such as _mm512_set_epi16 only in + // versions 9 & beyond. So, we want to ensure that only releases built with + // supported compilers on supported hardware return CPU Capability AVX512, + // if it's supported on the hardware PyTorch is running on. + if (cpuinfo_has_x86_avx512vl() && cpuinfo_has_x86_avx512bw() && \ + cpuinfo_has_x86_avx512dq() && cpuinfo_has_x86_fma3()) { + return CPUCapability::AVX512; + } +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + if (cpuinfo_has_x86_avx2() && cpuinfo_has_x86_fma3()) { + return CPUCapability::AVX2; + } +#endif + } +#endif + +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + // vxe is needed for fp32 vector instructions + if (cpu_has_vxe()) { + return CPUCapability::ZVECTOR; + } +#endif + +#if defined(__linux__) && defined(HAVE_SVE_CPU_DEFINITION) + if (cpuinfo_initialize() && cpuinfo_has_arm_sve() && cpuinfo_has_arm_bf16()) { + int sve_vl = cpuinfo_get_max_arm_sve_length(); + if (sve_vl == 256) + return CPUCapability::SVE256; + if (sve_vl == 128) + return CPUCapability::SVE128; + } +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + return CPUCapability::VSX; +#else + return CPUCapability::DEFAULT; +#endif +} + +CPUCapability get_cpu_capability() { + static CPUCapability capability = compute_cpu_capability(); + return capability; +} + +DispatchResult DispatchStubImpl::try_get_call_ptr( + const DeviceType device_type + , void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif +) { + constexpr auto supported_devices = c10::array_of( + c10::DeviceType::CPU, + c10::DeviceType::CUDA, + c10::DeviceType::HIP, + c10::DeviceType::MPS, + c10::DeviceType::MTIA, + c10::DeviceType::XPU, + c10::DeviceType::HPU, + c10::DeviceType::PrivateUse1 + ); + // Check if the device type is supported. + if (std::find(supported_devices.begin(), supported_devices.end(), device_type) == supported_devices.end()) { + return ErrorType::DeviceNotSupported; + } + switch (device_type) { + case DeviceType::CPU: { + // Use memory_order_relaxed here since even if two threads race, + // they will still compute the same value for cpu_dispatch_ptr. + auto fptr = cpu_dispatch_ptr.load(std::memory_order_relaxed); + if (!fptr) { + auto result = try_choose_cpu_impl( + DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , SVE128 + , SVE256 +#endif + ); + if (!std::holds_alternative(result)) { + cpu_dispatch_ptr.store(fptr, std::memory_order_relaxed); + } + return result; + } + return DispatchResult(fptr); + } + + case DeviceType::CUDA: + return cuda_dispatch_ptr != nullptr ? DispatchResult(cuda_dispatch_ptr) : ErrorType::MissingDeviceKernel; + + case DeviceType::HIP: + return hip_dispatch_ptr != nullptr ? DispatchResult(hip_dispatch_ptr) : ErrorType::MissingDeviceKernel; + +#if defined(USE_MPS) + case DeviceType::MPS: + return mps_dispatch_ptr != nullptr ? DispatchResult(mps_dispatch_ptr) : ErrorType::MissingDeviceKernel; +#endif + case DeviceType::MTIA: + return mtia_dispatch_ptr != nullptr ? DispatchResult(mtia_dispatch_ptr) : ErrorType::MissingDeviceKernel; + +#if defined(USE_XPU) + case DeviceType::XPU: + return xpu_dispatch_ptr != nullptr ? DispatchResult(xpu_dispatch_ptr) : ErrorType::MissingDeviceKernel; +#endif + + case DeviceType::HPU: + return hpu_dispatch_ptr != nullptr ? DispatchResult(hpu_dispatch_ptr) : ErrorType::MissingDeviceKernel; + + case DeviceType::PrivateUse1: + return privateuse1_dispatch_ptr != nullptr ? DispatchResult(privateuse1_dispatch_ptr) : ErrorType::MissingDeviceKernel; + + default: + TORCH_INTERNAL_ASSERT(false, "An unexpected device type was provided ", device_type); + } +} + +void* DispatchStubImpl::get_call_ptr( + const DeviceType device_type + , void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif +) { + + auto result = try_get_call_ptr( + device_type, + DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , + AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , + AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , + VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , + ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , + SVE128 + , + SVE256 +#endif + ); + if (std::holds_alternative(result)) { + auto error = std::get(result); + switch (error) { + case ErrorType::MissingDeviceKernel: + TORCH_INTERNAL_ASSERT( + false, "DispatchStub: missing kernel for ", device_type); + case ErrorType::DeviceNotSupported: + TORCH_CHECK(false, "DispatchStub: unsupported device type", device_type); + } + } + + void* fptr = std::get(result); + return fptr; +} + +DispatchResult DispatchStubImpl::try_choose_cpu_impl( + void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif + ){ + + auto capability = static_cast(get_cpu_capability()); + (void)capability; +#ifdef HAVE_AVX512_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::AVX512)) { + // Quantization kernels have also been disabled on Windows + // for AVX512 because some of their tests are flaky on Windows. + // Ideally, we should have AVX512 kernels for all kernels. + if (C10_UNLIKELY(!AVX512)) { + // dispatch to AVX2, since the AVX512 kernel is missing + return AVX2 != nullptr ? DispatchResult(AVX2) : ErrorType::MissingDeviceKernel; + } else { + return DispatchResult(AVX512); + } + } +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::AVX2)) { + return AVX2 != nullptr ? DispatchResult(AVX2) : ErrorType::MissingDeviceKernel; + } +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::VSX)) { + return VSX != nullptr ? DispatchResult(VSX) : ErrorType::MissingDeviceKernel; + } +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::ZVECTOR)) { + return ZVECTOR != nullptr ? DispatchResult(ZVECTOR) : ErrorType::MissingDeviceKernel; + } +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + if (capability == static_cast(CPUCapability::SVE128)) { + if (C10_UNLIKELY(!SVE128)) { + return DEFAULT != nullptr ? DispatchResult(DEFAULT) : ErrorType::MissingDeviceKernel; + } + return DispatchResult(SVE128); + } + if (capability == static_cast(CPUCapability::SVE256)) { + if (C10_UNLIKELY(!SVE256)) { + return DEFAULT != nullptr ? DispatchResult(DEFAULT) : ErrorType::MissingDeviceKernel; + } + return DispatchResult(SVE256); + } +#endif + return DEFAULT != nullptr ? DispatchResult(DEFAULT) : ErrorType::MissingDeviceKernel; +} + +void* DispatchStubImpl::choose_cpu_impl( + void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif +) { + auto capability = static_cast(get_cpu_capability()); + (void)capability; +#ifdef HAVE_AVX512_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::AVX512)) { + // Quantization kernels have also been disabled on Windows + // for AVX512 because some of their tests are flaky on Windows. + // Ideally, we should have AVX512 kernels for all kernels. + if (C10_UNLIKELY(!AVX512)) { + // dispatch to AVX2, since the AVX512 kernel is missing + TORCH_INTERNAL_ASSERT(AVX2, "DispatchStub: missing AVX2 kernel"); + return AVX2; + } else { + return AVX512; + } + } +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::AVX2)) { + TORCH_INTERNAL_ASSERT(AVX2, "DispatchStub: missing AVX2 kernel"); + return AVX2; + } +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::VSX)) { + TORCH_INTERNAL_ASSERT(VSX, "DispatchStub: missing VSX kernel"); + return VSX; + } +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + if (capability >= static_cast(CPUCapability::ZVECTOR)) { + TORCH_INTERNAL_ASSERT(ZVECTOR, "DispatchStub: missing ZVECTOR kernel"); + return ZVECTOR; + } +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + if (capability == static_cast(CPUCapability::SVE128)) { + if (C10_UNLIKELY(!SVE128)) { + TORCH_INTERNAL_ASSERT(DEFAULT, "DispatchStub: missing default kernel"); + return DEFAULT; + } + return SVE128; + } + if (capability == static_cast(CPUCapability::SVE256)) { + if (C10_UNLIKELY(!SVE256)) { + TORCH_INTERNAL_ASSERT(DEFAULT, "DispatchStub: missing default kernel"); + return DEFAULT; + } + return SVE256; + } +#endif + TORCH_INTERNAL_ASSERT(DEFAULT, "DispatchStub: missing default kernel"); + return DEFAULT; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/DispatchStub.h b/western_ai/usa/pytorch/aten/src/ATen/native/DispatchStub.h new file mode 100644 index 0000000000000000000000000000000000000000..70af9a6a1a5abb8fadc6c8d8a3fa0a4ee758330b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/DispatchStub.h @@ -0,0 +1,507 @@ +#pragma once + +#include +#include + +#include +#include +#include + +// Implements instruction set specific function dispatch. +// +// Kernels that may make use of specialized instruction sets (e.g. AVX2) are +// compiled multiple times with different compiler flags (e.g. -mavx2). A +// DispatchStub contains a table of function pointers for a kernel. At runtime, +// the fastest available kernel is chosen based on the features reported by +// cpuinfo. +// +// Example: +// +// In native/MyKernel.h: +// using fn_type = void(*)(const Tensor& x); +// DECLARE_DISPATCH(fn_type, stub) +// +// In native/MyKernel.cpp +// DEFINE_DISPATCH(stub); +// +// In native/cpu/MyKernel.cpp: +// namespace { +// // use anonymous namespace so that different cpu versions won't conflict +// void kernel(const Tensor& x) { ... } +// } +// REGISTER_DISPATCH(stub, &kernel); +// +// To call: +// stub(kCPU, tensor); +// +// TODO: CPU instruction set selection should be folded into whatever +// the main dispatch mechanism is. +// +// Supported device types for registration: +// - CPU: Central Processing Unit +// - CUDA: NVIDIA GPUs +// - HIP: AMD GPUs +// - MPS: Apple Silicon GPUs (Metal Performance Shaders) +// - MTIA: Meta Training and Inference Devices +// - XPU: Intel GPUs +// - HPU: Reserved for HPU (Intel Gaudi) device types +// - PrivateUse1: Reserved for private/custom device types +// +// If you want to update the list of supported devices, add a new dispatch_ptr +// member in DispatchStubImpl.h and update the get_call_ptr switch. +// As well you will need to update the inlined list in 'is_device_supported` +// +// +// ignore warnings about DispatchStub::DEFAULT, AVX, AVX2 defined elsewhere +C10_CLANG_DIAGNOSTIC_PUSH() +C10_CLANG_DIAGNOSTIC_IGNORE("-Wundefined-var-template") + +namespace at::native { + +enum class CPUCapability { + DEFAULT = 0, +#if defined(HAVE_VSX_CPU_DEFINITION) + VSX = 1, +#elif defined(HAVE_ZVECTOR_CPU_DEFINITION) + ZVECTOR = 1, +#elif defined(HAVE_SVE_CPU_DEFINITION) + SVE256 = 1, + SVE128 = 2, +#else + AVX2 = 1, + AVX512 = 2, +#endif + NUM_OPTIONS +}; + +// Enum for error types +enum class ErrorType { + MissingDeviceKernel, + DeviceNotSupported +}; + +// Alias for the return type using std::variant +using DispatchResult = std::variant; + +CPUCapability get_cpu_capability(); + +template +struct DispatchStub; + +/** + * The sole purpose of this class is to outline methods that don't need to be + * specialized or otherwise inlined and duplicated (by the compiler due to + * template expansion), since it causes size bloat if there are a significant + * number of specialization of the DispatchStub<> class. + */ +struct TORCH_API DispatchStubImpl { + + // The DispatchStubImpl::try_get_call_ptr() method is used to get the call + // pointer for a given device type. If the call pointer is not found, + // DispatchStubImpl::try_get_call_ptr() returns an ErrorType. + // The main difference between try_get_call_ptr() and get_call_ptr() is that + // try_get_call_ptr() will return the ErrorType and not raise an exception. + DispatchResult try_get_call_ptr( + c10::DeviceType device_type + , void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif + ); + + // Analogous to try_get_call_ptr(), but it will return the ErrorType and not + // raise an exception. + DispatchResult try_choose_cpu_impl( + void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif + ); + + + void* get_call_ptr( + c10::DeviceType device_type + , void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif + ); + + /** + * The CPU Dispatch actual method is chosen in decreasing order of preference by + * DispatchStubImpl::choose_cpu_impl() in case none is found by + * DispatchStubImpl::get_call_ptr() in cpu_dispatch_ptr. + */ + void* choose_cpu_impl( + void *DEFAULT +#ifdef HAVE_AVX512_CPU_DEFINITION + , void *AVX512 +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , void *AVX2 +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , void *VSX +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , void *ZVECTOR +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , void *SVE128 + , void *SVE256 +#endif + ); + + // Fixing dispatch error in Windows debug builds. + // See https://github.com/pytorch/pytorch/issues/22681 for more details. + #if defined(_MSC_VER) && defined(_DEBUG) + std::atomic cpu_dispatch_ptr; + void* cuda_dispatch_ptr; + void* hip_dispatch_ptr; + void* mps_dispatch_ptr; + void* mtia_dispatch_ptr; + #if defined(USE_XPU) + void* xpu_dispatch_ptr; + #endif + void* hpu_dispatch_ptr; + void* privateuse1_dispatch_ptr; + #else + std::atomic cpu_dispatch_ptr{nullptr}; + void* cuda_dispatch_ptr = nullptr; + void* hip_dispatch_ptr = nullptr; + void* mps_dispatch_ptr = nullptr; + void* mtia_dispatch_ptr = nullptr; + #if defined(USE_XPU) + void* xpu_dispatch_ptr = nullptr; + #endif + void* hpu_dispatch_ptr = nullptr; + void* privateuse1_dispatch_ptr = nullptr; + #endif +}; + +template +struct DispatchStub { + using FnPtr = rT (*) (Args...); + + DispatchStub() = default; + DispatchStub(const DispatchStub&) = delete; + DispatchStub& operator=(const DispatchStub&) = delete; + +private: + FnPtr get_call_ptr(const c10::DeviceType device_type) { + return reinterpret_cast( + impl.get_call_ptr(device_type + , reinterpret_cast(DEFAULT) +#ifdef HAVE_AVX512_CPU_DEFINITION + , reinterpret_cast(AVX512) +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , reinterpret_cast(AVX2) +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , reinterpret_cast(VSX) +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , reinterpret_cast(ZVECTOR) +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , reinterpret_cast(SVE128) + , reinterpret_cast(SVE256) +#endif + ) + ); + } + +public: + template + rT operator()(c10::DeviceType device_type, ArgTypes&&... args) { + FnPtr call_ptr = get_call_ptr(device_type); + return (*call_ptr)(std::forward(args)...); + } + + void set_cuda_dispatch_ptr(FnPtr fn_ptr) { + impl.cuda_dispatch_ptr = reinterpret_cast(fn_ptr); + } + + #if defined(USE_XPU) + void set_xpu_dispatch_ptr(FnPtr fn_ptr){ + impl.xpu_dispatch_ptr = reinterpret_cast(fn_ptr); + } + #endif + + void set_hpu_dispatch_ptr(FnPtr fn_ptr) { + impl.hpu_dispatch_ptr = reinterpret_cast(fn_ptr); + } + + void set_hip_dispatch_ptr(FnPtr fn_ptr) { + impl.hip_dispatch_ptr = reinterpret_cast(fn_ptr); + } + + void set_mps_dispatch_ptr(FnPtr fn_ptr) { + impl.mps_dispatch_ptr = reinterpret_cast(fn_ptr); + } + + void set_mtia_dispatch_ptr(FnPtr fn_ptr) { + impl.mtia_dispatch_ptr = reinterpret_cast(fn_ptr); + } + + void set_privateuse1_dispatch_ptr(FnPtr fn_ptr) { + impl.privateuse1_dispatch_ptr = reinterpret_cast(fn_ptr); + } + + // Returns true if the dispatcher has a kernel registered for this device + // type. + bool is_device_supported(const c10::DeviceType device_type) { + auto result = impl.try_get_call_ptr(device_type + , reinterpret_cast(DEFAULT) +#ifdef HAVE_AVX512_CPU_DEFINITION + , reinterpret_cast(AVX512) +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + , reinterpret_cast(AVX2) +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + , reinterpret_cast(VSX) +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + , reinterpret_cast(ZVECTOR) +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + , reinterpret_cast(SVE128) + , reinterpret_cast(SVE256) +#endif + ); + if (std::holds_alternative(result)){ + return false; + } + return true; + } + + static TORCH_API FnPtr DEFAULT; +#ifdef HAVE_AVX512_CPU_DEFINITION + static TORCH_API FnPtr AVX512; +#endif +#ifdef HAVE_AVX2_CPU_DEFINITION + static TORCH_API FnPtr AVX2; +#endif +#ifdef HAVE_VSX_CPU_DEFINITION + static TORCH_API FnPtr VSX; +#endif +#ifdef HAVE_ZVECTOR_CPU_DEFINITION + static TORCH_API FnPtr ZVECTOR; +#endif +#ifdef HAVE_SVE_CPU_DEFINITION + static TORCH_API FnPtr SVE128; + static TORCH_API FnPtr SVE256; +#endif +private: + DispatchStubImpl impl; +}; + +namespace { +template +struct RegisterCUDADispatch { + RegisterCUDADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) { + stub.set_cuda_dispatch_ptr(value); + } +}; + +template +struct RegisterXPUDispatch { + RegisterXPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){ + stub.set_xpu_dispatch_ptr(value); + } +}; + +template +struct RegisterHPUDispatch { + RegisterHPUDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value){ + stub.set_hpu_dispatch_ptr(value); + } +}; + +template +struct RegisterMPSDispatch { + RegisterMPSDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) { + stub.set_mps_dispatch_ptr(value); + } +}; + +template +struct RegisterHIPDispatch { + RegisterHIPDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) { + // TODO: make this point at hip_dispatch_ptr + stub.set_cuda_dispatch_ptr(value); + } +}; + +template +struct RegisterMTIADispatch { + RegisterMTIADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) { + stub.set_mtia_dispatch_ptr(value); + } +}; + +template +struct RegisterPRIVATEUSE1Dispatch { + RegisterPRIVATEUSE1Dispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) { + stub.set_privateuse1_dispatch_ptr(value); + } +}; + +} // anonymous namespace +// Compiler will complain if you put things like std::tuple in +// the `fn` argument of DECLARE_DISPATCH. Some possible workarounds, e.g., +// adding parentheses and using helper struct to get rid of the parentheses, do +// not work with MSVC. So do a `using`-declaration if you need to pass in such +// `fn`, e.g., grid_sampler_2d_backward_cpu_kernel in GridSampleKernel.h. +#define DECLARE_DISPATCH(fn, name) \ + struct name##_DECLARE_DISPATCH_type : DispatchStub { \ + name##_DECLARE_DISPATCH_type() = default; \ + name##_DECLARE_DISPATCH_type(const name##_DECLARE_DISPATCH_type&) = delete; \ + name##_DECLARE_DISPATCH_type& operator=(const name##_DECLARE_DISPATCH_type&) = delete; \ + name##_DECLARE_DISPATCH_type(name##_DECLARE_DISPATCH_type&&) = delete; \ + name##_DECLARE_DISPATCH_type& operator=(name##_DECLARE_DISPATCH_type&&) = delete; \ + ~name##_DECLARE_DISPATCH_type() = default; \ + }; \ + extern TORCH_API struct name##_DECLARE_DISPATCH_type name; + +#define DEFINE_DISPATCH(name) struct name##_DECLARE_DISPATCH_type name + +#define REGISTER_ARCH_DISPATCH(name, arch, fn) \ + template <> name##_DECLARE_DISPATCH_type::FnPtr TORCH_API DispatchStub::arch = fn; + +#ifdef HAVE_AVX512_CPU_DEFINITION +#define REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX512, fn) +#else +#define REGISTER_AVX512_DISPATCH(name, fn) +#endif + +#ifdef HAVE_AVX2_CPU_DEFINITION +#define REGISTER_AVX2_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX2, fn) +#else +#define REGISTER_AVX2_DISPATCH(name, fn) +#endif + +#ifdef HAVE_VSX_CPU_DEFINITION +#define REGISTER_VSX_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, VSX, fn) +#else +#define REGISTER_VSX_DISPATCH(name, fn) +#endif + +#ifdef HAVE_ZVECTOR_CPU_DEFINITION +#define REGISTER_ZVECTOR_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, ZVECTOR, fn) +#else +#define REGISTER_ZVECTOR_DISPATCH(name, fn) +#endif + +#ifdef HAVE_SVE_CPU_DEFINITION +#define REGISTER_SVE128_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, SVE128, fn) +#define REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, SVE256, fn) +#else +#define REGISTER_SVE128_DISPATCH(name, fn) +#define REGISTER_SVE256_DISPATCH(name, fn) +#endif + +// Macro to register the same kernel for all CPU arch types. This is useful +// if a kernel does not benefit from being recompiled across different arch types. +#define REGISTER_ALL_CPU_DISPATCH(name, fn) \ + REGISTER_ARCH_DISPATCH(name, DEFAULT, fn) \ + REGISTER_AVX512_DISPATCH(name, fn) \ + REGISTER_AVX2_DISPATCH(name, fn) \ + REGISTER_VSX_DISPATCH(name, fn) \ + REGISTER_ZVECTOR_DISPATCH(name, fn) \ + REGISTER_SVE128_DISPATCH(name, fn) \ + REGISTER_SVE256_DISPATCH(name, fn) + +#define REGISTER_NO_CPU_DISPATCH(name) \ + REGISTER_ALL_CPU_DISPATCH(name, nullptr) + +#define REGISTER_CUDA_DISPATCH(name, fn) \ + static RegisterCUDADispatch name ## __register(name, fn); + +#define REGISTER_XPU_DISPATCH(name, fn) \ + static RegisterXPUDispatch name ## __register(name, fn); + +#define REGISTER_HPU_DISPATCH(name, fn) \ + static RegisterHPUDispatch name ## __register(name, fn); + +#define REGISTER_HIP_DISPATCH(name, fn) \ + static RegisterHIPDispatch name ## __register(name, fn); + +#define REGISTER_MPS_DISPATCH(name, fn) \ + static RegisterMPSDispatch name ## __register(name, fn); + +#define REGISTER_MTIA_DISPATCH(name, fn) \ + static RegisterMTIADispatch name ## __register(name, fn); + +#define REGISTER_PRIVATEUSE1_DISPATCH(name, fn) \ + static RegisterPRIVATEUSE1Dispatch name ## __register(name, fn); + +// NB: This macro must be used in an actual 'cu' file; if you try using +// it from a 'cpp' file it will not work! +#if defined(__CUDACC__) +#define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn) +#elif defined(__HIPCC__) +// TODO: cut this over to HIP dispatch once we stop pretending that CUDA +// is HIP in the PyTorch HIPify build. +#define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn) +// #define REGISTER_DISPATCH(name, fn) REGISTER_HIP_DISPATCH(name, fn) +#elif defined(__OBJC__) && defined(USE_MPS) +// NB: this macro must be used from a 'mm' file in order to dispatch a MPS kernel +#define REGISTER_DISPATCH(name, fn) REGISTER_MPS_DISPATCH(name, fn) +#elif defined(CPU_CAPABILITY) +// REGISTER_DISPATCH now dispatches an AVX512 kernel to nullptr but registers other dispatches. +// ALSO_REGISTER_AVX512_DISPATCH should be used for ensuring AVX512 dispatch, among others. +// ALSO_REGISTER_SVE256_DISPATCH should be used for ensuring SVE256 dispatch, among others. +#ifdef CPU_CAPABILITY_AVX512 +#define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, ((void*)(fn) ? nullptr : nullptr)) +#else +#define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn) +#endif +#define ALSO_REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn) +#define ALSO_REGISTER_SVE128_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn) +#define ALSO_REGISTER_SVE256_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn) +#endif +} // namespace at::native + +C10_CLANG_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Distance.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Distance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..94570ff9c19d48023539738c59171c03cc47a2ff --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Distance.cpp @@ -0,0 +1,340 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace at::native { + +DEFINE_DISPATCH(pdist_forward_stub); +DEFINE_DISPATCH(pdist_backward_stub); +DEFINE_DISPATCH(cdist_stub); +DEFINE_DISPATCH(cdist_backward_stub); + +static inline void cdist_supported_device_check(const Tensor& x1, const Tensor& x2, const char* op) { + auto check = [&](DeviceType d, const char* which) { + TORCH_CHECK(d == kCPU || d == kCUDA || d == kXPU || d == kMPS || d == kPrivateUse1, + op, " only supports CPU, XPU, CUDA, MPS and PrivateUse1 devices, ", which, " got: ", d); + }; + check(x1.device().type(), "X1"); + check(x2.device().type(), "X2"); +} + +Tensor pairwise_distance(const Tensor& x1, const Tensor& x2, double p, double eps, bool keepdim) { + // Since either x1 or x2 could be broadcasted + auto x1_dim = x1.dim(); + auto x2_dim = x2.dim(); + auto output_dim = x1_dim > x2_dim ? x1_dim : x2_dim; + auto innermost_dim = output_dim - 1; + return at::norm(x1 - x2 + eps, p, innermost_dim, keepdim); +} + +// This is to guarantee that the contiguous memory is passed to the backward pass +Tensor pdist(const Tensor& self, const double p) { + TORCH_CHECK(self.dim() == 2, + "pdist only supports 2D tensors, got: ", self.dim(), "D"); + TORCH_CHECK(at::isFloatingType(self.scalar_type()), "pdist only supports floating-point dtypes"); + TORCH_CHECK(p >= 0, "pdist only supports non-negative p values"); + return at::_pdist_forward(self.contiguous(), p); +} + +Tensor _euclidean_dist(const Tensor& x1, const Tensor& x2) { + /** This function does the fist part of the euclidean distance calculation + * We divide it in two steps to simplify dealing with subgradients in the + * backward step */ + Tensor x1_norm = x1.pow(2).sum(-1, true); + Tensor x1_pad = at::ones_like(x1_norm, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + Tensor x2_norm = x2.pow(2).sum(-1, true); + Tensor x2_pad = at::ones_like(x2_norm, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + Tensor x1_ = at::cat({x1.mul(-2), std::move(x1_norm), std::move(x1_pad)}, -1); + Tensor x2_ = at::cat({x2, std::move(x2_pad), std::move(x2_norm)}, -1); + Tensor result = x1_.matmul(x2_.mT()); + result.clamp_min_(0).sqrt_(); + return result; +} + +static Tensor cdist_impl(const Tensor& x1, const Tensor& x2, const double p, std::optional compute_mode) { + TORCH_CHECK(at::isFloatingType(x1.scalar_type()), "cdist only supports floating-point dtypes, X1 got: ", x1.scalar_type()); + auto device1 = x1.device().type(); + TORCH_CHECK(at::isFloatingType(x2.scalar_type()), "cdist only supports floating-point dtypes, X2 got: ", x2.scalar_type()); + auto device2 = x2.device().type(); + TORCH_CHECK(p >= 0, "cdist only supports non-negative p values"); + TORCH_CHECK(device1 == device2, "X1 and X2 must have the same device type. X1: ", device1, " X2: ", device2); + // TODO: This is bad; this test should apply universally + TORCH_CHECK(!x1.is_cuda() || x1.get_device() == x2.get_device(), "device of X1 (", x1.get_device(), ") must match device of X2 (", x2.get_device(), ")"); + SymInt c1 = x1.sym_size(-1); + SymInt c2 = x2.sym_size(-1); + // 0 - default value. If p = 2 and r1 > 25 or r2 > 25 (these values are based on performance metrics), + // it will try to compute distance using matrix multiplication approach + // 1 - force to use matrix multiplication for p = 2 + // 2 - do not use matrix multiplication for p = 2 + int64_t mode = compute_mode.value_or(0); + TORCH_CHECK(mode >= 0 && mode <= 2, "possible modes: 0, 1, 2, but was: ", mode); + + SymInt r1 = x1.sym_size(-2); + SymInt r2 = x2.sym_size(-2); + + // See Note [cdist relies on cdist_impl redispatching] + // Keep this condition in sync with the condition at the Note + if (!(p == 2 && (mode == 1 || (mode == 0 && (r1 > 25 || r2 > 25))))) { + cdist_supported_device_check(x1, x2, "cdist"); + } + + auto dim1 = x1.dim(); + auto dim2 = x2.dim(); + + //For batch calculation we expand all dimensions(except the last two) to one, with size that equals to product of them. + //The last two dimensions will stay the same + SymIntArrayRef batch_tensor1(x1.sym_sizes().data(), dim1 - 2); + SymIntArrayRef batch_tensor2(x2.sym_sizes().data(), dim2 - 2); + std::vector expand_batch_portion = infer_size_symint(batch_tensor1, batch_tensor2); + std::vector tensor1_expand_size(expand_batch_portion); + tensor1_expand_size.insert(tensor1_expand_size.end(), {r1, c1}); + std::vector tensor2_expand_size(expand_batch_portion); + tensor2_expand_size.insert(tensor2_expand_size.end(), {r2, c2}); + + const SymInt expand_batch_product = c10::multiply_integers(expand_batch_portion); + std::vector tensor1_view{expand_batch_product, r1, c1}; + std::vector tensor2_view{expand_batch_product, r2, c2}; + + Tensor tensor1_expanded = x1.expand_symint(tensor1_expand_size).contiguous().view_symint(tensor1_view); + Tensor tensor2_expanded = x2.expand_symint(tensor2_expand_size).contiguous().view_symint(tensor2_view); + + std::vector output_shape(std::move(expand_batch_portion)); + output_shape.insert(output_shape.end(), {r1, r2}); + + Tensor result; + if (r1 == 0 || r2 == 0 || expand_batch_product == 0) { + result = at::empty_symint(output_shape, x1.options()); + } else if (c1 == 0) { + result = at::zeros_symint(output_shape, x1.options()); + } else if (p == 2 && (mode == 1 || (mode == 0 && (r1 > 25 || r2 > 25)))) { + // See Note [cdist relies on cdist_impl redispatching] + // Keep the condition above in sync with the condition at the Note + Tensor dist = (expand_batch_product == 1) ? at::_euclidean_dist(x1, x2) : + at::_euclidean_dist(tensor1_expanded, tensor2_expanded); + result = dist.view_symint(output_shape); + } else { + result = at::empty_symint(output_shape, x1.options()); + cdist_stub(device1, result, tensor1_expanded, tensor2_expanded, p); + } + return result; +} + +Tensor cdist(const Tensor& x1, const Tensor& x2, const double p, std::optional compute_mode) { + TORCH_CHECK(x1.dim() >= 2, "cdist only supports at least 2D tensors, X1 got: ", x1.dim(), "D"); + TORCH_CHECK(x2.dim() >= 2, "cdist only supports at least 2D tensors, X2 got: ", x2.dim(), "D"); + TORCH_CHECK(x1.sym_size(-1) == x2.sym_size(-1), "X1 and X2 must have the same number of columns. X1: ", x1.sym_size(-1), " X2: ", x2.sym_size(-1)); + auto result = [&]() { + SymInt r1 = x1.sym_size(-2); + SymInt r2 = x2.sym_size(-2); + // Special case for empty input: always call the version with explicit autograd to ensure the graph is properly connected + if (x1.sym_numel() == 0 || x2.sym_numel() == 0) { + return at::_cdist_forward(x1, x2, p, compute_mode); + } + int64_t mode = compute_mode.value_or(0); + // Note [cdist relies on cdist_impl redispatching] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // This is for pytorch to figure the backward pass itself + // when p=2. Keep this condition in sync with the See Note reference + if (p == 2 && (mode == 1 || (mode == 0 && (r1 > 25 || r2 > 25)))) { + return cdist_impl(x1, x2, p, compute_mode); + } else { + return at::_cdist_forward(x1, x2, p, compute_mode); + } + }(); + return result; +} + +Tensor _cdist_forward(const Tensor& x1, const Tensor& x2, const double p, std::optional compute_mode) { + TORCH_CHECK(x1.dim() >= 2, "cdist only supports at least 2D tensors, X1 got: ", x1.dim(), "D"); + TORCH_CHECK(x2.dim() >= 2, "cdist only supports at least 2D tensors, X2 got: ", x2.dim(), "D"); + TORCH_CHECK(x1.size(-1) == x2.size(-1), "X1 and X2 must have the same number of columns. X1: ", x1.size(-1), " X2: ", x2.size(-1)); + auto result = [&]() { + return cdist_impl(x1, x2, p, compute_mode); + }(); + return result; +} + +Tensor _cdist_backward(const Tensor& _grad, const Tensor& _x1, const Tensor& _x2, const double p, const Tensor& _cdist) { + // Broadcasting might generate non-contiguous Tensors, so handle it before doing checks + int64_t c1 = _x1.size(-1); + int64_t c2 = _x2.size(-1); + int64_t r1 = _x1.size(-2); + int64_t r2 = _x2.size(-2); + auto dim1 = _x1.dim(); + auto dim2 = _x2.dim(); + IntArrayRef batch_tensor1(_x1.sizes().data(), dim1 - 2); + IntArrayRef batch_tensor2(_x2.sizes().data(), dim2 - 2); + std::vector expand_batch_portion = infer_size(batch_tensor1, batch_tensor2); + std::vector tensor1_expand_size(expand_batch_portion); + tensor1_expand_size.insert(tensor1_expand_size.end(), {r1, c1}); + std::vector tensor2_expand_size(expand_batch_portion); + tensor2_expand_size.insert(tensor2_expand_size.end(), {r2, c2}); + + // Compute the linearized batch size + const int64_t batch_product = c10::multiply_integers(expand_batch_portion); + + // Gracefully handle empty Tensors + if (r1 == 0 || r2 == 0 || c1 == 0 || batch_product == 0) { + return at::zeros_like(_x1, _x1.options()); + } + + Tensor x1 = _x1; + if (tensor1_expand_size != x1.sizes()) { + x1 = x1.expand(tensor1_expand_size); + } + Tensor x2 = _x2; + if (tensor2_expand_size != x2.sizes()) { + x2 = x2.expand(tensor2_expand_size); + } + + x1 = x1.contiguous(); + x2 = x2.contiguous(); + auto cdist = _cdist.contiguous(); + auto grad = _grad.contiguous(); + int64_t n = x1.size(-2); + int64_t m = x1.size(-1); + cdist_supported_device_check(x1, x2, "_cdist_backward"); + + Tensor grad_x1 = + at::empty({batch_product, n, m}, x1.options(), LEGACY_CONTIGUOUS_MEMORY_FORMAT); + cdist_backward_stub(x1.device().type(), grad_x1, grad, x1, x2, p, cdist); + + // Use x1.size() here and not the original size of _x1.size() as this gradient is not taking broadcasting into account + // Broadcasting will be handled automatically by the autograd engine + return grad_x1.view(x1.sizes()); +} + +Tensor _pdist_forward(const Tensor& self, const double p) { + TORCH_CHECK(self.is_contiguous(), "_pdist_forward requires contiguous input"); + auto device = self.device().type(); + TORCH_CHECK(device == kCPU || device == kCUDA || device == kXPU || device == kPrivateUse1, "_pdist_forward only supports CPU, XPU, CUDA and PrivateUse1 devices, got: ", device); + Tensor result = at::empty({0}, self.options(), LEGACY_CONTIGUOUS_MEMORY_FORMAT); + if (self.size(0) <= 1) { + result.resize_({0}); + } else { + int64_t n = self.size(0); + int64_t c = n * (n - 1) / 2; + result.resize_({c}); + if (self.size(1) == 0) { + result.fill_(0); + } else { + pdist_forward_stub(device, result, self, p); + } + } + return result; +} + +Tensor _pdist_backward(const Tensor& grad, const Tensor& self, const double p, const Tensor& pdist) { + TORCH_CHECK(self.is_contiguous(), "_pdist_backward requires self to be contiguous"); + TORCH_CHECK(pdist.is_contiguous(), "_pdist_backward requires pdist to be contiguous"); + auto device = self.device().type(); + TORCH_CHECK(device == kCPU || device == kCUDA || device == kXPU || device == kPrivateUse1, "_pdist_backward only supports CPU, XPU, CUDA and PrivateUse1 devices, got: ", device); + Tensor result = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + pdist_backward_stub(device, result, grad, self, p, pdist); + return result; +} + +Tensor cosine_similarity(const Tensor& x1_, const Tensor& x2_, int64_t dim, double eps) { + /* + * cosine_similarity(x1, x2) = / (||x1|| * ||x2||) + * + * The current implementation is an improvement over the previous version. + * + * Previous implementation: + * 1. Compute num = , + * 2. Compute denom = ||x1|| * ||x2||, + * 3. Compute denom = max(denom, eps) to avoid division by zero, + * 4. Return num / denom. + * + * Previous implementation has the following issues: + * 1. Chance of losing precision in when ||x1|| and ||x2|| are large. + * 2. Chance of losing precision in ||x1|| * ||x2|| when ||x1|| and ||x2|| are large. + * 3. Losing precision may cause |cosing_similarity(x1, x2)| > 1.0. + * + * Current implementation: + * 1. Compute x1_normalized = x1 / max(||x1||, eps), + * x2_normalized = x2 / max(||x2||, eps), + * 2. Return . + * + * The current implementation improves over the previous one by: + * 1. Making sure that and ||x1|| * ||x2|| are not computed explicitly, + * hence avoiding floating point overflows. + * 2. Both methods might have issues with computing ||x1|| and ||x2||, but for + * the current method this is the only source of the floating point imprecision. + * 3. Makes sure |cosing_similarity(x1, x2)| <= 1.0. + * + */ + + auto commonDtype = at::result_type(x1_, x2_); + TORCH_CHECK(at::isFloatingType(commonDtype), "expected common dtype to be floating point, yet common dtype is ", commonDtype); + TORCH_CHECK(eps >= 0, "eps must be non-negative, got: ", eps); + + // We accept integral types (and bools lol) but vector_norm does not + auto x1_is_int = c10::isIntegralType(x1_.scalar_type(), /*încludeBool=*/true); + auto x2_is_int = c10::isIntegralType(x2_.scalar_type(), /*încludeBool=*/true); + auto x1_t = x1_is_int ? x1_.to(commonDtype) : x1_; + auto x2_t = x2_is_int ? x2_.to(commonDtype) : x2_; + auto [x1, x2] = expand_outplace(x1_t, x2_t); + + + // We want to divide each tensor by its norm first, as it's more numerically stable. + // This keeps the result between -1.0 and 1.0 + // We clone them, as we're going to modify them in-place + // This allows the gradients to propagate properly all the way to x1 and x2 + auto x1_norm = at::linalg_vector_norm(*x1, 2, /*dim=*/dim, /*keepdim=*/true).clone(); + auto x2_norm = at::linalg_vector_norm(*x2, 2, /*dim=*/dim, /*keepdim=*/true).clone(); + + // Convert eps to a scalar tensor to ensure consistent CPU/CUDA behavior when eps overflows the dtype. + // Use float32 if commonDtype is a reduced floating type (float16/bfloat16), otherwise use commonDtype. + // This avoids CUDA errors when creating a scalar_tensor with reduced types if the eps value overflows, + // while CPU would convert to inf. The eps_tensor is then used to clamp the norms to prevent division by zero. + auto common_is_reduced = at::isReducedFloatingType(commonDtype); + auto eps_dtype = common_is_reduced ? at::kFloat : commonDtype; + auto eps_tensor = at::scalar_tensor(eps, at::TensorOptions().dtype(eps_dtype).device(x1_norm.device())); + + { + at::NoGradGuard guard; + x1_norm.clamp_min_(eps_tensor); + x2_norm.clamp_min_(eps_tensor); + } + + return ((*x1 / x1_norm) * (*x2 / x2_norm)).sum(dim); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Distance.h b/western_ai/usa/pytorch/aten/src/ATen/native/Distance.h new file mode 100644 index 0000000000000000000000000000000000000000..e9532dcaca0f8afdfcf5a5e2c181841a1dce9169 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Distance.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace at { +class Tensor; + +namespace native { + +using pdist_forward_fn = void(*)(Tensor&, const Tensor&, const double p); +using pdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&); +using cdist_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const double p); +using cdist_backward_fn = void(*)(Tensor&, const Tensor&, const Tensor&, const Tensor&, const double p, const Tensor&); + +DECLARE_DISPATCH(pdist_forward_fn, pdist_forward_stub) +DECLARE_DISPATCH(pdist_backward_fn, pdist_backward_stub) +DECLARE_DISPATCH(cdist_fn, cdist_stub) +DECLARE_DISPATCH(cdist_backward_fn, cdist_backward_stub) + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/DistributionTemplates.h b/western_ai/usa/pytorch/aten/src/ATen/native/DistributionTemplates.h new file mode 100644 index 0000000000000000000000000000000000000000..68d4aece0cb50cb5f42c8af2096828e8bb542437 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/DistributionTemplates.h @@ -0,0 +1,400 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace at::native::templates { + +// ==================================================== Random ======================================================== + +// The purpose of `update_from` and `update_to` is to find the closest valid int64_t number that can be used as actual `from`. +// The current implementation of `random_` uses uint64_t arithmetic and casts the result to the target dtype(scalar_t). +// This casting can result in generating numbers that happen to be greater or equal to `to` value. For instance: +// +// auto actual = torch::empty({3, 3}, torch::half); +// actual.random_(0, 65504); +// +// If random's uint64_t arithmetic produces 65503 as a random value after casting to torch::half it becomes 65504 +// and violates the requirement that random value must be less than `to`. To resolve this issue `update_from` and `update_to` +// moves `from` to the right and `to` to the left to the next closest value that won't go outside [from, to) after casting to +// the target dtype. For `to` = 65504 it moves left for (1 << (log2(to) - 11 + 1)) = 32 and becomes 65472, which is previous +// available number for torch::half dtype. +template +int64_t update_from(int64_t from) { + static_assert( + std::is_floating_point_v || + std::is_same_v || + std::is_same_v, "scalar_t must be floating-point type"); + const auto from_plus_1 = static_cast(static_cast(from + 1)); + if (from_plus_1 < from) { + int64_t from_ = std::abs(from + 1); + int n = 0; + while (from_ >>= 1) ++n; + // NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult) + from = from_plus_1 + (1LL << (n - std::numeric_limits::digits + 1)); + } + return from; +} + +template +int64_t update_to(int64_t to) { + static_assert( + std::is_floating_point_v || + std::is_same_v || + std::is_same_v, "scalar_t must be floating-point type"); + const auto to_minus_1 = static_cast(static_cast(to - 1)); + if (to_minus_1 >= to) { + int64_t to_ = std::abs(to - 1); + int n = 0; + while (to_ >>= 1) ++n; + // NOLINTNEXTLINE(clang-analyzer-core.UndefinedBinaryOperatorResult) + to = to_minus_1 - (1LL << (n - std::numeric_limits::digits + 1)); + } + return to; +} + +// Return earlier for not invoking kernel. +// See https://github.com/pytorch/pytorch/issues/103418 for more details +#define CHECK_EMPTY_AND_RETURN(tensor) \ + if (tensor.numel() == 0) { \ + return tensor; \ + } + +template class random_kernel, typename RNG> +at::Tensor& random_impl(at::Tensor& self, std::optional generator) { + CHECK_EMPTY_AND_RETURN(self); + auto iter = at::TensorIterator::borrowing_nullary_op(self); + random_kernel()(iter, generator); + return self; +} + +#define CHECK_OUT_OF_BOUNDS(var, name, min, max, dtype) \ + TORCH_CHECK(var >= min && var <= max, name , " is out of bounds for ", dtype); \ + +#define WARN_OUT_OF_BOUNDS(var, name, digits, dtype) \ + if (var < -(1LL << digits) || var > (1LL << digits)) { \ + TORCH_WARN(name , " is out of bounds [-(2^", digits, "), 2^", digits, "]. ", \ + "Due to precision limitations ", dtype, " can support discrete uniform distribution only within this range. ", \ + "This warning will become an error in version 1.7 release, please fix the code in advance"); \ + } + +inline void check_from_to_in_range(int64_t from, int64_t to_inc, caffe2::TypeMeta dtype) { + const auto scalar_type = typeMetaToScalarType(dtype); + if (isFloatingType(scalar_type)) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, scalar_type, "check_random_fp_bounds", [&] { + const auto min = static_cast(std::numeric_limits::lowest()); + const auto max = static_cast(std::numeric_limits::max()); + CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype); + CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype); + + constexpr auto digits = std::numeric_limits::digits; + WARN_OUT_OF_BOUNDS(from, "from", digits, dtype); + WARN_OUT_OF_BOUNDS(to_inc, "to - 1", digits, dtype); + }); + } else if (scalar_type == kUInt64) { + // When you do a comparison between int64_t and uint64_t, the usual + // arithmetic conversions say that the int64_t value is promoted to + // unsigned. But this conversion wraps around: if I had -1 as my int64_t, + // then it will promote to 0xFFFFFFFFFFFFFFFF in uint64_t. This is never + // the right thing to do. + CHECK_OUT_OF_BOUNDS(from, "from", 0, INT64_MAX, dtype); + CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", 0, INT64_MAX, dtype); + } else if (isIntegralType(scalar_type, /*includeBool=*/true)) { + AT_DISPATCH_V2(scalar_type, "check_random_integral_bounds", AT_WRAP([&]() { + const auto min = static_cast(std::numeric_limits::lowest()); + const auto max = static_cast(std::numeric_limits::max()); + CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype); + CHECK_OUT_OF_BOUNDS(to_inc, "to - 1", min, max, dtype); + }), AT_EXPAND(AT_INTEGRAL_TYPES), kUInt16, kUInt32, kBool); + } else { + TORCH_CHECK(false, "check_random_bounds handles only integral, floating-point and boolean types"); + } +} + +template class random_from_to_kernel, typename RNG> +at::Tensor& random_from_to_impl(at::Tensor& self, int64_t from, std::optional to_opt, std::optional generator) { + uint64_t range = 0; + auto iter = at::TensorIterator::borrowing_nullary_op(self); + if (to_opt.has_value()) { + // [from, to) + int64_t to = *to_opt; + TORCH_CHECK(from < to, "random_ expects 'from' to be less than 'to', but got from=", from, " >= to=", to); + if (isFloatingType(iter.dtype())) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_update_from_to", [&] { + from = update_from(from); + to = update_to(to); + TORCH_CHECK(from < to, "random_ expects 'from' casted to dtype to be less than 'to' casted to dtype, but got from=", from, " >= to=", to); + }); + } + check_from_to_in_range(from, to - 1, self.dtype()); + CHECK_EMPTY_AND_RETURN(self); + range = static_cast(to) - static_cast(from); + random_from_to_kernel()(iter, range, from, generator); + } else if (from != std::numeric_limits::lowest()) { + // [from, std::numeric_limits::max()] + int64_t to_inc = 0; + if (isFloatingType(iter.dtype())) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "random_from_to_range_calc", [&] { + constexpr int64_t scalar_t_max = static_cast(1) << std::numeric_limits::digits; + to_inc = scalar_t_max > std::numeric_limits::max() ? std::numeric_limits::max() : static_cast(scalar_t_max); + from = update_from(from); + TORCH_CHECK(from < to_inc, "random_ expects 'from' casted to dtype to be less than or equal to 'to_inc' casted to dtype, but got from=", from, " > to_inc=", to_inc); + }); + } else if (isIntegralType(iter.dtype(), /*includeBool=*/true)) { + AT_DISPATCH_V2(self.scalar_type(), "random_from_to_range_calc", AT_WRAP([&] { + if constexpr (std::is_same_v) { + to_inc = static_cast(true); + } else { + to_inc = static_cast(std::numeric_limits::max()); + } + }), AT_EXPAND(AT_INTEGRAL_TYPES_V2), kBool); + } else { + TORCH_CHECK(false, "random_from_to_impl handles only integral, floating-point and boolean types"); + } + check_from_to_in_range(from, to_inc, self.dtype()); + CHECK_EMPTY_AND_RETURN(self); + range = static_cast(to_inc) - static_cast(from) + 1; + random_from_to_kernel()(iter, range, from, generator); + } else { + // [std::numeric_limits::lowest(), std::numeric_limits::max()] + // range = 2^64 + CHECK_EMPTY_AND_RETURN(self); + random_from_to_kernel()(iter, generator); + } + return self; +} + +// ==================================================== Normal ======================================================== + +#define CHECK_NORMAL_TENSOR_STD(std) \ + do { \ + TORCH_CHECK( \ + !std.is_complex(), \ + "normal expects standard deviation to be non-complex"); \ + if (std.numel() > 0 && !std.is_meta()) { \ + if (std.is_cuda()) { \ + at::_assert_async( \ + std.min().ge(0), \ + "normal expects all elements of std >= 0.0"); \ + } else { \ + TORCH_CHECK( \ + std.min().ge(0).item(), \ + "normal expects all elements of std >= 0.0"); \ + } \ + } \ + } while (0) + +#define CHECK_NORMAL_STD(std) \ + TORCH_CHECK(std >= 0.0, "normal expects std >= 0.0, but found std ", std); + +template class normal_kernel, typename RNG> +Tensor& normal_impl_(Tensor& self, double mean, double std, std::optional gen) { + CHECK_NORMAL_STD(std); + CHECK_EMPTY_AND_RETURN(self); + + if (self.is_complex()) { + auto float_tensor = at::view_as_real(self); + // variance for normal distribution of the real and imaginary values + // is half of the input variance + normal_kernel()(float_tensor, mean, std/(std::sqrt(2)), gen); + } else { + normal_kernel()(self, mean, std, gen); + } + return self; +} + +template class normal_kernel, typename RNG> +Tensor& normal_out_impl(Tensor& output, const Tensor& mean, double std, std::optional gen) { + CHECK_NORMAL_STD(std); + auto std_tensor = at::empty_like(output, MemoryFormat::Contiguous); + auto shape = at::infer_size(mean.sizes(), std_tensor.sizes()); + at::native::resize_output(output, shape); + normal_impl_(output, 0, std, gen); + output.add_(mean); + return output; +} + +template class normal_kernel, typename RNG> +Tensor& normal_out_impl(Tensor& output, double mean, const Tensor& std, std::optional gen) { + CHECK_NORMAL_TENSOR_STD(std); + auto mean_tensor = at::full({}, mean, output.options()); + auto shape = at::infer_size(mean_tensor.sizes(), std.sizes()); + at::native::resize_output(output, shape); + normal_impl_(output, 0, 1, gen); + // CUDA NB: addcmul_out copies the tensor to be added into the output. + // The previous function here was addcmul_out(output, mean_tensor, output, std, 1); + // The third argument is not a constant reference and hence the samples in output are overwritten. + // Consequently, the computation performed is mean_tensor + mean_tensor * std instead of mean_tensor + output * std + output.mul_(std).add_(mean_tensor); + return output; +} + +template class normal_kernel, typename RNG> +Tensor& normal_out_impl(Tensor& output, const Tensor& mean, const Tensor& std, std::optional gen) { + CHECK_NORMAL_TENSOR_STD(std); + auto shape = at::infer_size(mean.sizes(), std.sizes()); + at::native::resize_output(output, shape); + normal_impl_(output, 0, 1, gen); + // CUDA NB: addcmul_out copies the tensor to be added into the output. + // The previous function here was addcmul_out(output, mean, output, std, 1); + // The third argument is not a constant reference and hence the samples in output are overwritten. + // Consequently, the computation performed is mean + mean * std instead of mean + output * std + output.mul_(std).add_(mean); + return output; +} + +template class normal_kernel, typename RNG> +Tensor normal_impl(const Tensor& mean, double std, std::optional gen) { + CHECK_NORMAL_STD(std); + Tensor ret = at::empty_like(mean, MemoryFormat::Contiguous); + normal_out_impl(ret, mean, std, gen); + return ret; +} + +template class normal_kernel, typename RNG> +Tensor normal_impl(double mean, const Tensor& std, std::optional gen) { + CHECK_NORMAL_TENSOR_STD(std); + Tensor ret = at::empty_like(std, MemoryFormat::Contiguous); + normal_out_impl(ret, mean, std, gen); + return ret; +} + +template class normal_kernel, typename RNG> +Tensor normal_impl(const Tensor& mean, const Tensor& std, std::optional gen) { + CHECK_NORMAL_TENSOR_STD(std); + auto shape = at::infer_size(mean.sizes(), std.sizes()); + Tensor ret = at::empty(shape, mean.options(), MemoryFormat::Contiguous); + normal_out_impl(ret, mean, std, gen); + return ret; +} + +// ==================================================== Uniform ======================================================= + +template class uniform_kernel, typename RNG> +at::Tensor& uniform_impl_(at::Tensor& self, double from, double to, std::optional generator) { + if (self.is_complex()) { + CHECK_EMPTY_AND_RETURN(self); + auto float_tensor = at::view_as_real(self); + uniform_impl_(float_tensor, from, to, generator); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "check_uniform_bounds", [&] { + [[maybe_unused]] const auto dtype = self.dtype(); + const auto min = static_cast(std::numeric_limits::lowest()); + const auto max = static_cast(std::numeric_limits::max()); + CHECK_OUT_OF_BOUNDS(from, "from", min, max, dtype); + CHECK_OUT_OF_BOUNDS(to, "to", min, max, dtype); + TORCH_CHECK(from <= to, "uniform_ expects to return a [from, to) range, but found from=", from, " > to=", to); + TORCH_CHECK((to - from) <= std::numeric_limits::max(), + "uniform_ expects to-from <= std::numeric_limits<", toString(self.scalar_type()), + ">::max(), but found to=", to, " and from=", from, + " which result in to-from to exceed the limit"); + from = std::clamp(from, min, max); + to = std::clamp(to, min, max); + }); + CHECK_EMPTY_AND_RETURN(self); + auto iter = at::TensorIterator::borrowing_nullary_op(self); + uniform_kernel()(iter, from, to, generator); + } + return self; +} + +// ================================================== LogNormal ======================================================= + +template class log_normal_kernel, typename RNG> +at::Tensor& log_normal_impl_(at::Tensor& self, double mean, double std, std::optional gen) { + TORCH_CHECK(std > 0.0, "log_normal_ expects std > 0.0, but found std=", std); + CHECK_EMPTY_AND_RETURN(self); + auto iter = TensorIterator::borrowing_nullary_op(self); + log_normal_kernel()(iter, mean, std, gen); + return self; +} + +// =================================================== Geometric ====================================================== + +template class geometric_kernel, typename RNG> +Tensor& geometric_impl_(Tensor& self, double p, std::optional gen) { + TORCH_CHECK(0 < p && p < 1, "geometric_ expects p to be in (0, 1), but got p=", p); + CHECK_EMPTY_AND_RETURN(self); + auto iter = TensorIterator::borrowing_nullary_op(self); + geometric_kernel()(iter, p, gen); + return self; +} + +// ================================================== Exponential ===================================================== + +template class exponential_kernel, typename RNG> +Tensor& exponential_impl_(Tensor& self, double lambda, std::optional gen) { + TORCH_CHECK(lambda > 0.0, "exponential_ expects lambda > 0.0, but found lambda=", lambda); + CHECK_EMPTY_AND_RETURN(self); + auto iter = TensorIterator::borrowing_nullary_op(self); + exponential_kernel()(iter, lambda, gen); + return self; +} + +// ==================================================== Cauchy ======================================================== + +template class cauchy_kernel, typename RNG> +Tensor& cauchy_impl_(Tensor& self, double median, double sigma, std::optional gen) { + // TODO: instead of variable name 'sigma', use 'gamma' or 'scale' + // the variance, squared sigma, is undefined for cauchy distribution + TORCH_CHECK(sigma > 0.0, "cauchy_ expects sigma > 0.0, but found sigma=", sigma); + TORCH_CHECK(at::isFloatingType(self.scalar_type()), "Cauchy distribution is a continuous probability distribution. dtype must be a floating point but you specified ", self.dtype()); + CHECK_EMPTY_AND_RETURN(self); + auto iter = TensorIterator::borrowing_nullary_op(self); + cauchy_kernel()(iter, median, sigma, gen); + return self; +} + +// ==================================================== Bernoulli ===================================================== + +template class bernoulli_tensor_kernel, typename RNG> +Tensor& bernoulli_impl_(Tensor& self, const Tensor& p_, std::optional gen) { + CHECK_EMPTY_AND_RETURN(self); + at::assert_no_internal_overlap(self); + bernoulli_tensor_kernel()(self, p_, gen); + return self; +} + +template class bernoulli_scalar_kernel, typename RNG> +Tensor& bernoulli_impl_(Tensor& self, double p, std::optional gen) { + TORCH_CHECK(0 <= p && p <= 1, "bernoulli_ expects p to be in [0, 1], but got p=", p); + CHECK_EMPTY_AND_RETURN(self); + at::assert_no_internal_overlap(self); + bernoulli_scalar_kernel()(self, p, gen); + return self; +} + +template class bernoulli_tensor_kernel, typename RNG> +Tensor& bernoulli_out_impl(Tensor& result, const Tensor& self, std::optional gen) { + // result.resize_as_(self) requires self to have same dtype as result, so we + // use resize_ instead. + // TODO: Fix resize_as_. See pytorch/pytorch#11665. + result.resize_(self.sizes()); + bernoulli_impl_(result, self, gen); + return result; +} + +#undef CHECK_OUT_OF_BOUNDS +#undef WARN_OUT_OF_BOUNDS + +} // namespace at::native::templates diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Distributions.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Distributions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f8173f39ad12f244e77d6f376fb39f9a96ccd38 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Distributions.cpp @@ -0,0 +1,645 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include + +namespace { +/* + * This section is a counterpart to Distributions.cu + * + */ + +// The function `sample_poisson` +// is adapted from Numpy's distributions.c implementation. +// It is MIT licensed, so here is the copyright: + +/* Copyright 2005 Robert Kern (robert.kern@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +int64_t sample_poisson(double lambda, at::CPUGeneratorImpl* generator) { + TORCH_CHECK(lambda >= 0, "invalid Poisson rate, expected rate to be non-negative"); + at::uniform_real_distribution standard_uniform(0.0, 1.0); + if (lambda >= 10) { + // transformed rejection method, (Hoermann, 1993) + + double slam = std::sqrt(lambda); + double loglam = std::log(lambda); + double b = 0.931 + 2.53 * slam; + double a = -0.059 + 0.02483 * b; + double invalpha = 1.1239 + 1.1328 / (b - 3.4); + double vr = 0.9277 - 3.6224 / (b - 2); + + while (true) { + double U = standard_uniform(generator) - 0.5; + double V = standard_uniform(generator); + double us = 0.5 - std::fabs(U); + auto k = std::floor((2 * a / us + b) * U + lambda + 0.43); + if ((us >= 0.07) && (V <= vr)) { + return static_cast(k); + } + if ((k < 0) || ((us < 0.013) && (V > us))) { + continue; + } + if ((std::log(V) + std::log(invalpha) - std::log(a / (us * us) + b)) <= + (-lambda + k * loglam - std::lgamma(k + 1))) { + return static_cast(k); + } + } + } else if (lambda == 0) { + return 0; + } else { + auto enlam = std::exp(-lambda); + int64_t X = 0; + auto prod = 1.0; + while (true) { + auto U = standard_uniform(generator); + prod *= U; + if (prod > enlam) { + X += 1; + } else { + return X; + } + } + } +} + +} // namespace + +namespace at::native { + +DEFINE_DISPATCH(bernoulli_tensor_stub); +DEFINE_DISPATCH(bernoulli_scalar_stub); +DEFINE_DISPATCH(cauchy_stub); +DEFINE_DISPATCH(exponential_stub); +DEFINE_DISPATCH(multinomial_with_replacement_stub); +DEFINE_DISPATCH(geometric_stub); +DEFINE_DISPATCH(log_normal_stub); +DEFINE_DISPATCH(uniform_stub); +DEFINE_DISPATCH(normal_stub); +DEFINE_DISPATCH(random_stub); +DEFINE_DISPATCH(random_from_to_stub); +DEFINE_DISPATCH(random_full_64_bits_range_stub); + +// ==================================================== Bernoulli ===================================================== + +template +struct BernoulliStub { + void operator()(Tensor& self, const Tensor& p_, std::optional gen) { + bernoulli_tensor_stub(self.device().type(), self, p_, gen); + } + + void operator()(Tensor& self, double p, std::optional gen) { + bernoulli_scalar_stub(self.device().type(), self, p, gen); + } +}; + +Tensor bernoulli(const Tensor& self, std::optional gen) { + Tensor result = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + result.bernoulli_(self, std::move(gen)); + return result; +} + +Tensor bernoulli(const Tensor& self, double p, std::optional gen) { + Tensor result = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + result.bernoulli_(p, std::move(gen)); + return result; +} + +Tensor& bernoulli_out(const Tensor& self, std::optional gen, Tensor& result) { + return at::native::templates::bernoulli_out_impl(result, self, std::move(gen)); +} + +Tensor& bernoulli_(Tensor& self, const Tensor& p_, std::optional gen) { + return at::native::templates::bernoulli_impl_(self, p_, std::move(gen)); +} + +Tensor& bernoulli_(Tensor& self, double p, std::optional gen) { + return at::native::templates::bernoulli_impl_(self, p, std::move(gen)); +} + +// ================================================== LogNormal ======================================================= + +template +struct LogNormalStub { + void operator()(TensorIteratorBase& iter, double mean, double std, std::optional gen) { + log_normal_stub(iter.device_type(), iter, mean, std, gen); + } +}; + +Tensor& log_normal_(Tensor& self, double mean, double std, std::optional gen) { + return at::native::templates::log_normal_impl_(self, mean, std, std::move(gen)); +} + +// ==================================================== Cauchy ======================================================== + +template +struct CauchyStub { + void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional gen) { + cauchy_stub(iter.device_type(), iter, median, sigma, gen); + } +}; + +Tensor& cauchy_(Tensor& self, double median, double sigma, std::optional gen) { + return at::native::templates::cauchy_impl_(self, median, sigma, std::move(gen)); +} + +// ================================================== Exponential ===================================================== + +template +struct ExponentialStub { + void operator()(TensorIteratorBase& iter, double lambda, std::optional gen) { + exponential_stub(iter.device_type(), iter, lambda, gen); + } +}; + +Tensor& exponential_(Tensor& self, double lambda, std::optional gen) { + return at::native::templates::exponential_impl_(self, lambda, std::move(gen)); +} + +// =================================================== Geometric ====================================================== + +template +struct GeometricStub { + void operator()(TensorIteratorBase& iter, double p, std::optional gen) { + geometric_stub(iter.device_type(), iter, p, gen); + } +}; + +Tensor& geometric_(Tensor& self, double p, std::optional gen) { + return at::native::templates::geometric_impl_(self, p, std::move(gen)); +} + +// ==================================================== Uniform ======================================================= + +template +struct UniformStub { + void operator()(TensorIteratorBase& iter, double from, double to, std::optional gen) { + uniform_stub(iter.device_type(), iter, from, to, gen); + } +}; + +template +struct UniformMeta { + // No-op! + void operator()(TensorIteratorBase& iter, double from, double to, std::optional gen) { + } +}; + +Tensor& uniform_(Tensor& self, double from, double to, std::optional gen) { + return at::native::templates::uniform_impl_(self, from, to, std::move(gen)); +} + +Tensor& uniform_meta_(Tensor& self, double from, double to, std::optional gen) { + return at::native::templates::uniform_impl_(self, from, to, std::move(gen)); +} + +// ==================================================== Normal ======================================================== + +template +struct NormalStub { + void operator()(Tensor& self, double mean, double std, std::optional gen) { + normal_stub(self.device().type(), self, mean, std, gen); + } +}; + +template +struct NormalMeta { + // No-op! + void operator()(Tensor& self, double mean, double std, std::optional gen) { + } +}; + +// inplace +Tensor& normal_(Tensor& self, double mean, double std, std::optional gen) { + return at::native::templates::normal_impl_(self, mean, std, std::move(gen)); +} + +Tensor& normal_meta_(Tensor& self, double mean, double std, std::optional gen) { + return at::native::templates::normal_impl_(self, mean, std, std::move(gen)); +} + +// out tensor float +Tensor& normal_out(const Tensor& mean, double std, std::optional gen, Tensor& output) { + return at::native::templates::normal_out_impl(output, mean, std, std::move(gen)); +} + +Tensor& normal_out_meta(const Tensor& mean, double std, std::optional gen, Tensor& output) { + return at::native::templates::normal_out_impl(output, mean, std, std::move(gen)); +} + +// out float tensor +Tensor& normal_out(double mean, const Tensor& std, std::optional gen, Tensor& output) { + return at::native::templates::normal_out_impl(output, mean, std, std::move(gen)); +} + +Tensor& normal_out_meta(double mean, const Tensor& std, std::optional gen, Tensor& output) { + return at::native::templates::normal_out_impl(output, mean, std, std::move(gen)); + +} + +// out tensor tensor +Tensor& normal_out(const Tensor& mean, const Tensor& std, std::optional gen, Tensor& output) { + return at::native::templates::normal_out_impl(output, mean, std, std::move(gen)); +} + +Tensor& normal_out_meta(const Tensor& mean, const Tensor& std, std::optional gen, Tensor& output) { + return at::native::templates::normal_out_impl(output, mean, std, std::move(gen)); +} + +// functional tensor float +Tensor normal(const Tensor& mean, double std, std::optional gen) { + return at::native::templates::normal_impl(mean, std, std::move(gen)); +} + +Tensor normal_meta(const Tensor& mean, double std, std::optional gen) { + return at::native::templates::normal_impl(mean, std, std::move(gen)); +} + +// functional float tensor +Tensor normal(double mean, const Tensor& std, std::optional gen) { + return at::native::templates::normal_impl(mean, std, std::move(gen)); +} + +Tensor normal_meta(double mean, const Tensor& std, std::optional gen) { + return at::native::templates::normal_impl(mean, std, std::move(gen)); +} + +// functional tensor tensor +Tensor normal(const Tensor& mean, const Tensor& std, std::optional gen) { + return at::native::templates::normal_impl(mean, std, std::move(gen)); +} + +Tensor normal_meta(const Tensor& mean, const Tensor& std, std::optional gen) { + return at::native::templates::normal_impl(mean, std, std::move(gen)); +} + +// functional variant, only used by the functionalization pass. +Tensor normal_functional(const Tensor& self, double mean, double std, std::optional generator) { + return self.clone().normal_(mean, std, std::move(generator)); +} + +// ==================================================== Random ======================================================== + +template +struct RandomStub { + void operator()(TensorIteratorBase& iter, std::optional gen) { + random_stub(iter.device_type(), iter, gen); + } +}; + +Tensor& random_(Tensor& self, std::optional gen) { + return at::native::templates::random_impl(self, std::move(gen)); +} + +template +struct RandomFromToStub { + void operator()(TensorIteratorBase& iter, uint64_t range, int64_t from, std::optional gen) { + random_from_to_stub(iter.device_type(), iter, range, from, gen); + } + void operator()(TensorIteratorBase& iter, std::optional gen) { + random_full_64_bits_range_stub(iter.device_type(), iter, gen); + } +}; + +Tensor& random_(Tensor& self, int64_t from, std::optional to, std::optional gen) { + return at::native::templates::random_from_to_impl(self, from, to, std::move(gen)); +} + +Tensor& random_(Tensor& self, int64_t to, std::optional gen) { + return random_(self, 0, to, std::move(gen)); +} + +Tensor& random_meta_(Tensor& self, std::optional gen) { + // No error checking yay + return self; +} + +Tensor& random_meta_(Tensor& self, int64_t from, std::optional to, std::optional gen) { + // No error checking yay + return self; +} + +Tensor& random_meta_(Tensor& self, int64_t to, std::optional gen) { + // No error checking yay + return self; +} + +// ==================================================================================================================== + +Tensor _standard_gamma_grad_cpu(const Tensor& self, const Tensor& output) { + Tensor ret = at::empty(self.sizes(), self.options()); + auto iter = TensorIteratorConfig() + .add_output(ret) + .add_input(self) + .add_input(output) + .build(); + AT_DISPATCH_FLOATING_TYPES(self.scalar_type(), "_standard_gamma_grad_cpu", [&] { + cpu_serial_kernel(iter, [](scalar_t self_val, scalar_t output_val) -> scalar_t{ + return standard_gamma_grad_one(self_val, output_val); + }); + }); + return ret; +} + +Tensor _dirichlet_grad_cpu(const Tensor& x, const Tensor& alpha, const Tensor& total) { + Tensor ret = at::empty(x.sizes(), x.options()); + auto iter = TensorIteratorConfig() + .add_output(ret) + .add_input(x) + .add_input(alpha) + .add_input(total) + .build(); + AT_DISPATCH_FLOATING_TYPES(x.scalar_type(), "_dirichlet_grad_cpu", [&] { + cpu_serial_kernel(iter, [](scalar_t x_val, scalar_t alpha_val, scalar_t total_val) -> scalar_t{ + return dirichlet_grad_one(x_val, alpha_val, total_val); + }); + }); + return ret; +} + +/* + * This section is a counterpart to Distributions.cu + */ + +Tensor _s_binomial_cpu(const Tensor& count, const Tensor& prob, std::optional gen) { + TORCH_CHECK_VALUE( + at::isFloatingType(count.scalar_type()), + "binomial only supports floating-point dtypes for count, got: ", + count.scalar_type()); + TORCH_CHECK_VALUE( + at::isFloatingType(prob.scalar_type()), + "binomial only supports floating-point dtypes for prob, got: ", + prob.scalar_type()); + Tensor ret = at::zeros(count.sizes(), count.options()); + auto iter = TensorIteratorConfig() + .add_output(ret) + .add_input(count) + .add_input(prob) + .build(); + AT_DISPATCH_FLOATING_TYPES(ret.scalar_type(), "binomial_cpu", [&] { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + cpu_serial_kernel(iter, [generator](scalar_t count_val, scalar_t prob_val) -> scalar_t{ + auto uniform_lambda = [generator] () { + at::uniform_real_distribution standard_uniform(0.0, 1.0); + return standard_uniform(generator); + }; + BaseSampler standard_uniform(uniform_lambda); + + auto sample = sample_binomial(count_val, prob_val, standard_uniform); + return static_cast(sample); + }); + }); + return ret; +} + +Tensor _s_poisson_cpu(const Tensor& lambda, std::optional gen) { + Tensor ret = at::zeros(lambda.sizes(), lambda.options()); + auto iter = TensorIteratorConfig() + .add_output(ret) + .add_input(lambda) + .build(); + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, ret.scalar_type(), "poisson_cpu", [&] { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + cpu_serial_kernel(iter, [generator](scalar_t lambda_val) -> scalar_t{ + return static_cast(sample_poisson(static_cast(lambda_val), generator)); + }); + }); + return ret; +} + +Tensor _s_gamma_cpu(const Tensor& alpha, std::optional gen) { + Tensor ret = at::zeros(alpha.sizes(), alpha.options()); + auto iter = TensorIteratorConfig() + .add_output(ret) + .add_input(alpha) + .build(); + AT_DISPATCH_FLOATING_TYPES(ret.scalar_type(), "gamma_cpu", [&] { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + cpu_serial_kernel(iter, [generator](scalar_t alpha_val) -> scalar_t{ + auto uniform_lambda = [generator] () { + at::uniform_real_distribution standard_uniform(0.0, 1.0); + return standard_uniform(generator); + }; + BaseSampler standard_uniform(uniform_lambda); + + auto normal_lambda = [generator] () { + at::normal_distribution normal(0.0, 1.0); + return normal(generator); + }; + BaseSampler standard_normal(normal_lambda); + auto sample = sample_gamma(alpha_val, standard_uniform, standard_normal); + return std::max(std::numeric_limits::min(), (scalar_t) sample); + }); + }); + + return ret; +} + +Tensor _s_dirichlet_cpu(const Tensor& alpha, std::optional gen) { + Tensor ret = at::zeros(alpha.sizes(), alpha.options()); + AT_DISPATCH_FLOATING_TYPES(ret.scalar_type(), "dirichlet", [&] { + Tensor gamma = at::zeros(alpha.sizes(), alpha.options().dtype(ScalarType::Double)); + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + /* Generate gamma sample by casting alpha to double to prevent underflow. */ + auto iter1 = TensorIteratorConfig() + .add_output(gamma) + .add_input(alpha) + .check_all_same_dtype(false) + .build(); + cpu_serial_kernel(iter1, [generator](scalar_t alpha_val) -> double{ + auto uniform_lambda = [generator] () { + at::uniform_real_distribution standard_uniform(0.0, 1.0); + return standard_uniform(generator); + }; + BaseSampler standard_uniform(uniform_lambda); + + auto normal_lambda = [generator] () { + at::normal_distribution normal(0.0, 1.0); + return normal(generator); + }; + BaseSampler standard_normal(normal_lambda); + auto sample = sample_gamma + (alpha_val, standard_uniform, standard_normal); + return std::max(std::numeric_limits::min(), sample); + }); + /* Normalize and cast back to scalar_t. */ + Tensor gamma_sum = gamma.sum(-1, true).expand(alpha.sizes()); + auto iter2 = TensorIteratorConfig() + .add_output(ret) + .add_input(gamma) + .add_input(gamma_sum) + .check_all_same_dtype(false) + .build(); + cpu_serial_kernel(iter2, [](double gamma_val, double gamma_sum_val) -> scalar_t{ + auto ret_val = gamma_val / gamma_sum_val; + auto min_val = std::numeric_limits::min(); + auto max_val = std::nexttoward(static_cast(1.0f), 0.0f); + return std::min(max_val, std::max(min_val, static_cast(ret_val))); + }); + }); + return ret; +} + +/* The largest consecutive integer representable in float32 (2^24) */ +constexpr int64_t FLOAT32_MAX_CONSECUTIVE_INT = 1 << (FLT_MANT_DIG); + +Tensor& multinomial_out(const Tensor& self, + int64_t n_sample, + bool with_replacement, + std::optional gen, + Tensor& result) { + TORCH_CHECK( + result.device() == self.device(), + "multinomial arguments must have the same device"); + TORCH_CHECK( + self.dim() > 0 && self.dim() <= 2, "prob_dist must be 1 or 2 dim"); + TORCH_CHECK( + at::isFloatingType(self.scalar_type()), + "multinomial only supports floating-point dtypes for input, got: ", + self.scalar_type()); + TORCH_CHECK(result.scalar_type() == ScalarType::Long, + "multinomial expects Long tensor out, got: ", result.scalar_type()); + TORCH_CHECK(n_sample > 0, "cannot sample n_sample <= 0 samples"); + int64_t n_categories = self.size(-1); + TORCH_CHECK(with_replacement || (n_sample <= n_categories), + "cannot sample n_sample > prob_dist.size(-1) samples without replacement"); + // Since the index tensor is float, numCategories cannot exceed max + // float integer precision + TORCH_CHECK( + n_categories <= FLOAT32_MAX_CONSECUTIVE_INT, + "number of categories cannot exceed 2^24"); + + if (self.dim() == 1) { + result.resize_({n_sample}); + } else { + const int64_t n_dist = self.size(0); + result.resize_({n_dist, n_sample}); + } + if (result.numel() == 0) { + return result; + } + + // Fast-path for no replacement or if only one sample is drawn. + // Reference: + // https://github.com/pytorch/pytorch/issues/11931#issuecomment-625882503 + if (!with_replacement || n_sample == 1) { + // Sanity checks on `self`. + auto [self_min, self_max] = self.aminmax(); + auto is_valid = ((self_max < INFINITY) & (self_min >= 0)); + at::_assert_async(is_valid, "probability tensor contains either `inf`, `nan` or element < 0"); + at::Tensor zero_prob_condition; + if (self.dim() == 1){ + zero_prob_condition = (self.sum() == 0); + } else { + zero_prob_condition = (self.sum(1) == 0).any(); + } + at::_assert_async(~zero_prob_condition, "invalid multinomial distribution (sum of probabilities <= 0)"); + + // The algorithm is from gumbel softmax. + // s = argmax( logp - log(-log(eps)) ) where eps ~ U(0, 1) + // Here we can apply exp to the formula which will not affect result of + // argmax or topk. Then we have + // s = argmax( p / (-log(eps)) ) where eps ~ U(0, 1). + // We can also simplify the formula above by + // s = argmax( p / q ) where q ~ Exp(1) + Tensor q = at::empty_like(self).exponential_(1, std::move(gen)); + // In theory the probability to generate 0 from exponential distribution is + // 0. However, on CUDA side there is a protection to avoid 0s, but on CPU + // side, there is a very low probability to generate 0 from + // exponential. The probability is about 2^(-DBL_MANT_DIG). We just + // ignore it here, but there may be some risk to get invalid output on CPU. + at::div_out(q, self, q); + if (n_sample == 1) { + at::argmax_out(result, q, /*dim=*/-1, /*keepdim=*/true); + } else { + Tensor vals = at::empty(result.sizes(), self.options()); + at::topk_out(vals, result, q, n_sample); + } + return result; + } + + multinomial_with_replacement_stub( + result.device().type(), result, self, n_sample, gen); + return result; +} + +Tensor multinomial( + const Tensor& self, + int64_t n_sample, + bool with_replacement, + std::optional gen) { + Tensor result = at::empty({0}, self.options().dtype(kLong)); + native::multinomial_out(self, n_sample, with_replacement, std::move(gen), result); + return result; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Distributions.h b/western_ai/usa/pytorch/aten/src/ATen/native/Distributions.h new file mode 100644 index 0000000000000000000000000000000000000000..a90781ba31e4426d40e88ad281b631d4bca71440 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Distributions.h @@ -0,0 +1,559 @@ +#pragma once + +#if defined(__METAL_VERSION__) +#include +#include +#include +#else +#include +#include +#include +#include +#endif + +// ROCm hip compiler doesn't work well with using std:: in kernel functions +#if defined(__CUDA_ARCH__) || defined(__HIPCC__) +#if defined(__CUDA_ARCH__) +#include +#elif defined(__HIPCC__) +#include +#endif +#define compat_exp c10::cuda::compat::exp +#define compat_ceil c10::cuda::compat::ceil +#define compat_floor c10::cuda::compat::floor +#define compat_log c10::cuda::compat::log +#define compat_pow c10::cuda::compat::pow +#define compat_sqrt c10::cuda::compat::sqrt +#define compat_tan c10::cuda::compat::tan +#define compat_abs c10::cuda::compat::abs +#define compat_log1p c10::cuda::compat::log1p +#elif defined(__METAL_VERSION__) +#define compat_log ::metal::precise::log +#define compat_exp ::metal::precise::exp +#define compat_pow ::metal::precise::pow +#define compat_sqrt ::metal::precise::sqrt +#define compat_ceil ::metal::ceil +#define compat_floor ::metal::floor +#define compat_abs ::metal::abs +#define compat_log1p ::c10::metal::log1p +#else +#define compat_exp std::exp +#define compat_ceil std::ceil +#define compat_floor std::floor +#define compat_log std::log +#define compat_pow std::pow +#define compat_sqrt std::sqrt +#define compat_tan std::tan +#define compat_abs std::abs +#define compat_log1p std::log1p +#endif + +#if defined(__METAL_VERSION__) +#define C10_HOST_DEVICE +#define C10_DEVICE +#define STATIC_IF_NOT_METAL +#define METAL_THREAD thread +#define std_size_compat(a) (sizeof(a) / sizeof(a[0])) +#else +#define STATIC_IF_NOT_METAL static +#define METAL_THREAD +#define std_size_compat std::size +#endif + +namespace { + +#if !defined(__CUDA_ARCH__) && !defined(__HIPCC__) && !defined(__METAL_VERSION__) +// we cannot use std::isnan directly due to some incompatibility of +// gcc constexpr'ing and nvcc +using std::isnan; +#endif + + +// Here sampler_t should be function type scalar_t(void). For gpu +// "sampler" is a device function, but since ROCM doesn't have +// equivalent to nvstd::function, we use a template type parameter to +// capture it. +template +struct BaseSampler { + sampler_t sampler; + C10_DEVICE BaseSampler(const METAL_THREAD sampler_t& sampler): sampler(sampler) {} + C10_DEVICE scalar_t sample() { + return sampler(); + } +}; + +#if !defined(__METAL_VERSION__) + +// The function `sample_gamma` is +// is adapted from Numpy's distributions.c implementation. +// It is MIT licensed, so here is the copyright: + +/* Copyright 2005 Robert Kern (robert.kern@gmail.com) + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +template +C10_DEVICE scalar_t sample_gamma(scalar_t alpha, BaseSampler& standard_uniform, BaseSampler& standard_normal) { + accscalar_t scale = 1.0f; + + // Boost alpha for higher acceptance probability. + if (alpha < 1.0f) { + if (alpha == 0.f) return 0.f; + scale *= compat_pow(1 - standard_uniform.sample(), 1.0f / alpha); + alpha += 1.0f; + } + + // This implements the acceptance-rejection method of Marsaglia and Tsang (2000) + // doi:10.1145/358407.358414 + const accscalar_t d = alpha - 1.0f / 3.0f; + const accscalar_t c = 1.0f / compat_sqrt(9.0f * d); + for (;;) { + accscalar_t x, y; + do { + x = standard_normal.sample(); + y = 1.0f + c * x; + } while (y <= 0); + const accscalar_t v = y * y * y; + const accscalar_t u = 1 - standard_uniform.sample(); + const accscalar_t xx = x * x; + if (u < 1.0f - 0.0331f * xx * xx) + return static_cast(scale * d * v); + if (compat_log(u) < 0.5f * xx + d * (1.0f - v + compat_log(v))) + return static_cast(scale * d * v); + } +} + +#endif // #if !defined(__METAL_VERSION__) + +/* the functions stirling_approx_tail, binomial_inversion, and btrs are adapted + * from TensorFlow's random_binomial_op.cc implementation. That code is under + * copyright: 2019 The TensorFlow Authors. + * + * It was released under the Apache License, Version 2.0 (the "License"), available at: + * http://www.apache.org/licenses/LICENSE-2.0 + */ + +template +C10_DEVICE scalar_t stirling_approx_tail(scalar_t k) { + constexpr STATIC_IF_NOT_METAL scalar_t kTailValues[] = { + 0.0810614667953272, + 0.0413406959554092, + 0.0276779256849983, + 0.02079067210376509, + 0.0166446911898211, + 0.0138761288230707, + 0.0118967099458917, + 0.0104112652619720, + 0.00925546218271273, + 0.00833056343336287 + }; + if (k < std_size_compat(kTailValues)) { + return kTailValues[static_cast(k)]; + } + scalar_t kp1sq = (k + 1) * (k + 1); + return (1.0 / 12 - (1.0 / 360 - 1.0 / 1260 / kp1sq) / kp1sq) / (k + 1); +} + +template +C10_DEVICE scalar_t binomial_inversion(scalar_t count, scalar_t prob, METAL_THREAD BaseSampler& standard_uniform) { + accscalar_t U; + accscalar_t geom_sum = 0; + scalar_t num_geom = 0; + + accscalar_t logprob = compat_log1p(-prob); + + while (true) { + U = standard_uniform.sample(); + accscalar_t geom = compat_ceil(compat_log(U) / logprob); + geom_sum += geom; + if (geom_sum > count) { + break; + } + num_geom = num_geom + 1; + } + return num_geom; +} + +template +C10_DEVICE scalar_t btrs(scalar_t count, scalar_t prob, METAL_THREAD BaseSampler& standard_uniform) { + scalar_t k; + accscalar_t U, V, us; + + // This is spq in the paper. + const accscalar_t stddev = compat_sqrt(count * prob * (1 - prob)); + + // Other coefficients for Transformed Rejection sampling. + const accscalar_t b = 1.15 + 2.53 * stddev; + const accscalar_t a = -0.0873 + 0.0248 * b + 0.01 * prob; + const accscalar_t c = count * prob + 0.5; + const accscalar_t v_r = 0.92 - 4.2 / b; + const accscalar_t r = prob / (1 - prob); + + const accscalar_t alpha = (2.83 + 5.1 / b) * stddev; + const accscalar_t m = compat_floor((count + 1) * prob); + + while (true) { + U = standard_uniform.sample() - 0.5; + V = standard_uniform.sample(); + + us = 0.5 - compat_abs(U); + k = static_cast(compat_floor((2 * a / us + b) * U + c)); + + // Reject non-sensical answers. + if (k < 0 || k > count) { + continue; + } + // Region for which the box is tight, and we can return our calculated value. + // This should happen 0.86 * v_r times. In the limit as n * p is large, + // the acceptance rate converges to ~79% (and in the lower regime it is ~24%). + if (us >= 0.07 && V <= v_r) { + return k; + } + + // This deviates from Hormann's BTRS algorithm, as there is a log missing. + // For all (u, v) pairs outside of the bounding box, this calculates the + // transformed-reject ratio. + V = compat_log(V * alpha / (a / (us * us) + b)); + accscalar_t upperbound = + ((m + 0.5) * compat_log((m + 1) / (r * (count - m + 1))) + + (count + 1) * compat_log((count - m + 1) / (count - k + 1)) + + (k + 0.5) * compat_log(r * (count - k + 1) / (k + 1)) + + stirling_approx_tail(m) + stirling_approx_tail(count - m) - + stirling_approx_tail(k) - stirling_approx_tail(count - k)); + + if (V <= upperbound) { + return k; + } + } +} + +template +C10_DEVICE scalar_t sample_binomial(scalar_t count, scalar_t prob, METAL_THREAD BaseSampler& standard_uniform) { + if (count <= 0.0 || prob <= 0.0) { + return 0; + } else if (prob >= 1.0) { + return count; + } else if (prob <= 0.5) { + if (count * prob >= 10.0) { + // btrs + return btrs(count, prob, standard_uniform); + } else { + // binomial inversion + return binomial_inversion(count, prob, standard_uniform); + } + } else if (prob > 0.5) { + scalar_t qprob = 1.0 - prob; + if (count * qprob >= 10.0) { + // btrs + return count - btrs(count, qprob, standard_uniform); + } else { + // count - binomial inversion + return count - binomial_inversion(count, qprob, standard_uniform); + } + } else { + // prob is nan? + return static_cast(NAN); + } +} + +#if !defined(__METAL_VERSION__) + +/* + * This function is derived from the implementation of the digamma function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library] in ATen/native/Math.h. + */ +template +C10_DEVICE inline scalar_t digamma_one(scalar_t x) { + constexpr accscalar_t PSI_10 = 2.25175258906672110764; + if (x == 0) { + return INFINITY; + } + accscalar_t additional_summand = 0; + int x_is_integer = x == compat_floor(x); + if (x < 0) { + if (x_is_integer) { + return INFINITY; + } + // it is more standard to write this as recursion, but + // nvcc does not like that + additional_summand = -c10::pi / + compat_tan(c10::pi * x); + x = 1 - x; + } + + // Push x to be >= 10 + accscalar_t result = 0; + while (x < 10) { + result -= 1 / x; + x += 1; + } + if (x == 10) { + return result + PSI_10 + additional_summand; + } + + // Compute asymptotic digamma + static const accscalar_t A[] = { + 8.33333333333333333333E-2, + -2.10927960927960927961E-2, + 7.57575757575757575758E-3, + -4.16666666666666666667E-3, + 3.96825396825396825397E-3, + -8.33333333333333333333E-3, + 8.33333333333333333333E-2, + }; + + accscalar_t y = 0; + if (x < 1.0e17f) { + accscalar_t z = 1.0 / (x * x); + y = z * polevl(z, A, 6); + } + return static_cast( + result + compat_log(x) - (0.5f / x) - y + additional_summand); +} + + +#endif // #if !defined(__METAL_VERSION__) + +#if defined(__METAL_VERSION__) +template +C10_DEVICE inline scalar_t digamma_one(scalar_t x) { + return c10::metal::digamma(x); +} +#endif // #if defined(__METAL_VERSION__) + +#if !defined(__METAL_VERSION__) + +// Computes the reparameterized gradient -(d/dalpha cdf(x;alpha)) / pdf(x;alpha) +// for random number x drawn from a standard Gamma distribution Gamma(alpha). +template +C10_HOST_DEVICE scalar_t standard_gamma_grad_one(scalar_t alpha_, scalar_t x_) { + // Use a Taylor series expansion for small x. + accscalar_t x = static_cast(x_); + accscalar_t alpha = static_cast(alpha_); + if (x < 0.8f) { + accscalar_t numer = 1; + accscalar_t denom = alpha; + auto series1 = numer / denom; + auto series2 = numer / (denom * denom); + for (int i = 1; i <= 5; ++i) { + numer *= -x / static_cast(i); + denom += 1; + series1 += numer / denom; + series2 += numer / (denom * denom); + } + const auto pow_x_alpha = compat_pow(x, alpha); + const auto gamma_pdf = compat_pow(x, alpha - 1) * compat_exp(-x); + const auto gamma_cdf = pow_x_alpha * series1; + const auto gamma_cdf_alpha = + (compat_log(x) - digamma_one(alpha)) * + gamma_cdf - + pow_x_alpha * series2; + const auto result = -gamma_cdf_alpha / gamma_pdf; + return isnan(result) ? static_cast( 0.f ) : static_cast(result); + } + + // Use a Rice saddle point expansion for large alpha. + if (alpha > 8.0f) { + if (0.9f * alpha <= x && x <= 1.1f * alpha) { + const auto numer_1 = 1 + 24 * alpha * (1 + 12 * alpha); + const auto numer_2 = 1440 * (alpha * alpha) + 6 * x * (53 - 120 * x) + - 65 * x * x / alpha + alpha * (107 + 3600 * x); + const auto denom = 1244160 * (alpha * alpha) * (alpha * alpha); + return static_cast(numer_1 * numer_2 / denom); + } + const auto denom = compat_sqrt(8 * alpha); + const auto term2 = denom / (alpha - x); + const auto term3 = compat_pow( + x - alpha - alpha * compat_log(x / alpha), + static_cast(-1.5)); + const auto term23 = (x < alpha) ? term2 - term3 : term2 + term3; + const auto term1 = compat_log(x / alpha) * term23 - + compat_sqrt(2 / alpha) * (alpha + x) / ((alpha - x) * (alpha - x)); + const auto stirling = 1 + 1 / (12 * alpha) * (1 + 1 / (24 * alpha)); + const auto numer = x * term1; + return static_cast(-stirling * numer / denom); + } + + // Use a bivariate rational approximation to the reparameterized gradient. + const auto u = compat_log(x / alpha); + const auto v = compat_log(alpha); + static const accscalar_t coef_uv[3][8] = { + {0.16009398, -0.094634809, 0.025146376, -0.0030648343, + 1, 0.32668115, 0.10406089, 0.0014179084}, + {0.53487893, 0.1298071, 0.065735949, -0.0015649758, + 0.16639465, 0.020070113, -0.0035938915, -0.00058392623}, + {0.040121004, -0.0065914022, -0.0026286047, -0.0013441777, + 0.017050642, -0.0021309326, 0.00085092367, -1.5247877e-07}, + }; + accscalar_t coef_v[8]; + for (int i = 0; i < 8; ++ i) { + coef_v[i] = coef_uv[0][i] + u * (coef_uv[1][i] + u * coef_uv[2][i]); + } + const auto p = coef_v[0] + v * (coef_v[1] + v * (coef_v[2] + v * coef_v[3])); + const auto q = coef_v[4] + v * (coef_v[5] + v * (coef_v[6] + v * coef_v[7])); + return static_cast(compat_exp(p / q)); +} + +#endif // #if !defined(__METAL_VERSION__) + +// Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha. +// Assumes x is close to zero and uses a Taylor expansion. +template +C10_DEVICE inline scalar_t _beta_grad_alpha_small(scalar_t x, scalar_t alpha, scalar_t beta) { + const scalar_t factor = digamma_one(alpha) + - digamma_one(alpha + beta) - compat_log(x); + scalar_t numer = 1; + scalar_t series = numer / alpha * (factor + 1 / alpha); + for (int i = 1; i <= 10; ++i) { + scalar_t casted_i = static_cast(i); + numer *= (casted_i - beta) * x / casted_i; + const scalar_t denom = alpha + casted_i; + series += numer / denom * (factor + 1 / denom); + } + const scalar_t result = x * compat_pow(1 - x, -beta) * series; + return isnan(result) ? static_cast( 0.f ) : result; +} + +// Approximate reparameterized gradient of Beta(x,alpha,beta) wrt beta. +// Assumes x is close to zero and uses a Taylor expansion. +template +C10_DEVICE inline scalar_t _beta_grad_beta_small(scalar_t x, scalar_t alpha, scalar_t beta) { + const scalar_t factor = digamma_one(alpha + beta) - digamma_one(beta); + scalar_t numer = 1, betas = 1, dbetas = 0, series = factor / alpha; + for (int i = 1; i <= 8; ++i) { + scalar_t casted_i = static_cast(i); + numer *= -x / casted_i; + dbetas = dbetas * (beta - casted_i) + betas; + betas = betas * (beta - casted_i); + series += numer / (alpha + casted_i) * (dbetas + factor * betas); + } + const scalar_t result = -compat_pow(1 - x, 1 - beta) * series; + return isnan(result) ? static_cast( 0.f ) : result; +} + +// Approximate reparameterized gradient of Beta(x,alpha,beta) wrt alpha. +// Assumes alpha and beta are both large and uses a Rice saddle point expansion. +// To ensure numerical stability, this computation is performed at higher precision. +template +C10_DEVICE inline scalar_t _beta_grad_alpha_mid(accscalar_t x, accscalar_t alpha, accscalar_t beta) { + const accscalar_t total = alpha + beta; + const accscalar_t mean = alpha / total; + const accscalar_t std = compat_sqrt(alpha * beta / (total + 1)) / total; + if (mean - 0.1 * std <= x && x <= mean + 0.1 * std) { + // Avoid the singularity at x = mean. + const accscalar_t poly = 47 * x * (beta * beta) * (beta * beta) + alpha * ( + (43 + 20 * (16 + 27 * beta) * x) * (beta * beta) * beta + alpha * ( + 3 * (59 + 180 * beta - 90 * x) * (beta * beta) + alpha * ( + (453 + 1620 * beta * (1 - x) - 455 * x) * beta + alpha * ( + 8 * (1 - x) * (135 * beta - 11))))); + const accscalar_t prefactor_num = (1 + 12 * alpha) * (1 + 12 * beta) / (total * total); + const accscalar_t prefactor_den = 12960 * alpha * alpha * alpha * beta * beta * (1 + 12 * total); + return prefactor_num / (1 - x) * poly / prefactor_den; + } + const accscalar_t prefactor = -x / compat_sqrt(2 * alpha * beta / total); + const accscalar_t stirling = (1 + 1 / (12 * alpha) + 1 / (288 * alpha * alpha)) + * (1 + 1 / (12 * beta) + 1 / (288 * beta * beta)) + / (1 + 1 / (12 * total) + 1 / (288 * total * total)); + const accscalar_t term1_num = 2 * (alpha * alpha) * (x - 1) + alpha * beta * (x - 1) - x * (beta * beta); + const accscalar_t axbx = alpha * (x - 1) + beta * x; + const accscalar_t term1_den = compat_sqrt(2 * alpha / beta) * compat_pow(total, static_cast(1.5f)) * axbx * axbx; + const accscalar_t term1 = term1_num / term1_den; + const accscalar_t term2 = 0.5f * compat_log(alpha / (total * x)); + const accscalar_t term3_num = compat_sqrt(8 * alpha * beta / total); + const accscalar_t term3_den = beta * x + alpha * (x - 1); + const accscalar_t term3 = term3_num / term3_den; + const accscalar_t term4_base = beta * compat_log(beta / (total * (1 - x))) + + alpha * compat_log(alpha / (total * x)); + const accscalar_t term4 = compat_pow(term4_base, static_cast(-1.5f)); + const accscalar_t term1234 = term1 + term2 * (term3 + (x < mean ? term4 : -term4)); + return static_cast(stirling * prefactor * term1234); +} + +// Computes a scaled reparameterized gradient +// -(d/dalpha cdf(x;alpha,beta)) / pdf(x;alpha,beta) / (1-x) +// for random number x drawn from a Beta distribution Beta(alpha,beta). +// This function inputs total=alpha+beta to make it easy to implement +// Dirichlet reparameterized gradients in terms of Betas. +template +C10_HOST_DEVICE inline scalar_t dirichlet_grad_one(scalar_t x, scalar_t alpha, scalar_t total) { + accscalar_t x_ = static_cast(x); + accscalar_t alpha_ = static_cast(alpha); + accscalar_t total_ = static_cast(total); + + const scalar_t beta = total - alpha; + const accscalar_t beta_ = total_ - alpha_; + const scalar_t boundary = total * x * (1 - x); + + // Use an asymptotic approximation for x close to 0. + if (x <= 0.5f && boundary < 2.5f) { + return _beta_grad_alpha_small(x, alpha, beta); + } + + // Use an asymptotic approximation for x close to 1. + if (x >= 0.5f && boundary < 0.75f) { + return -_beta_grad_beta_small(1 - x, beta, alpha); + } + + // Use an asymptotic approximation when alpha and (total - alpha) are both large. + if (alpha > 6 && beta > 6) { + return _beta_grad_alpha_mid(x_, alpha_, beta_); + } + + // Use a rational correction to an analytic approximation. + STATIC_IF_NOT_METAL const accscalar_t c[2][3][3][4] = { + {{{1.003668233, -0.01061107488, -0.0657888334, 0.01201642863}, + {0.6336835991, -0.3557432599, 0.05486251648, -0.001465281033}, + {-0.03276231906, 0.004474107445, 0.002429354597, -0.0001557569013}}, + {{0.221950385, -0.3187676331, 0.01799915743, 0.01074823814}, + {-0.2951249643, 0.06219954479, 0.01535556598, 0.001550077057}, + {0.02155310298, 0.004170831599, 0.001292462449, 6.976601077e-05}}, + {{-0.05980841433, 0.008441916499, 0.01085618172, 0.002319392565}, + {0.02911413504, 0.01400243777, -0.002721828457, 0.000751041181}, + {0.005900514878, -0.001936558688, -9.495446725e-06, 5.385558597e-05}}}, + {{{1, -0.02924021934, -0.04438342661, 0.007285809825}, + {0.6357567472, -0.3473456711, 0.05454656494, -0.002407477521}, + {-0.03301322327, 0.004845219414, 0.00231480583, -0.0002307248149}}, + {{0.5925320577, -0.1757678135, 0.01505928619, 0.000564515273}, + {0.1014815858, -0.06589186703, 0.01272886114, -0.0007316646956}, + {-0.007258481865, 0.001096195486, 0.0003934994223, -4.12701925e-05}}, + {{0.06469649321, -0.0236701437, 0.002902096474, -5.896963079e-05}, + {0.001925008108, -0.002869809258, 0.0008000589141, -6.063713228e-05}, + {-0.0003477407336, 6.959756487e-05, 1.097287507e-05, -1.650964693e-06}}}, + }; + const accscalar_t u = compat_log(x_); + const accscalar_t a = compat_log(alpha_) - u; + const accscalar_t b = compat_log(total_) - a; + const accscalar_t pow_u[3] = {1, u, u * u}; + const accscalar_t pow_a[3] = {1, a, a * a}; + accscalar_t p = 0.0; + accscalar_t q = 0.0; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + const accscalar_t ua = pow_u[i] * pow_a[j]; + p += ua * (c[0][i][j][0] + b * (c[0][i][j][1] + b * (c[0][i][j][2] + b * c[0][i][j][3]))); + q += ua * (c[1][i][j][0] + b * (c[1][i][j][1] + b * (c[1][i][j][2] + b * c[1][i][j][3]))); + } + } + const accscalar_t approx = x_ * (digamma_one(total_) - digamma_one(alpha_)) / beta_; + return static_cast(p / q * approx); +} + +} // namespace diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Dropout.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Dropout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ab95ec58ca037095526edf02d2b5e2ab98151e1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Dropout.cpp @@ -0,0 +1,172 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +template +using Ctype = typename std::conditional_t; + +Tensor make_feature_noise(const Tensor& input) { + auto input_sizes = input.sym_sizes(); + TORCH_CHECK(input.dim() >= 2, "Feature dropout requires at least 2 dimensions in the input"); + c10::SymDimVector sizes; + sizes.reserve(input.dim()); + sizes.push_back(input_sizes[0]); + sizes.push_back(input_sizes[1]); + for ([[maybe_unused]] const auto i : c10::irange(2, input.dim())) { + sizes.push_back(1); + } + return input.new_empty_symint(sizes); +} + +bool is_fused_kernel_acceptable(const Tensor& input, double p) { + return (input.is_cuda() || input.is_xpu() || input.is_lazy() || input.is_privateuseone()) && p > 0 && p < 1 && input.sym_numel() > 0; +} + +// NB: sure, we could have used different overloads here, but I would feel insecure +// knowing that this dispatch depends only on the constness of the references +template +Tensor& multiply(Tensor& input, const Tensor& noise) { + static_assert(inplace, "Wrong multiply overload triggered in Dropout.cpp"); + return input.mul_(noise); +} + +template +Tensor multiply(const Tensor& input, const Tensor& noise) { + static_assert(!inplace, "Wrong multiply overload triggered in Dropout.cpp"); + return input.mul(noise); +} + +template +Ctype _dropout_impl(T& input, double p, bool train) { + TORCH_CHECK(p >= 0 && p <= 1, "dropout probability has to be between 0 and 1, but got ", p); + if (p == 0 || !train || input.sym_numel() == 0) { + return input; + } + + if (p == 1) { + return multiply(input, at::zeros({}, input.options())); + } + + at::Tensor b; // used for alpha_dropout only + auto noise = feature_dropout ? make_feature_noise(input) : at::empty_like(input); + noise.bernoulli_(1 - p); + if (alpha_dropout) { + constexpr double alpha = 1.7580993408473766; + double a = 1. / std::sqrt((alpha * alpha * p + 1) * (1 - p)); + b = noise.add(-1).mul_(alpha * a).add_(alpha * a * p); + noise.mul_(a); + } else { + noise.div_(1 - p); + } + + if (!alpha_dropout) { + return multiply(input, noise); + } else { + return multiply(input, noise).add_(b); + } +} + +#define ALIAS_SPECIALIZATION(ALIAS_NAME, IS_FEATURE, IS_ALPHA) \ +template \ +Ctype ALIAS_NAME(Args&&... args) { \ + return _dropout_impl(std::forward(args)...); \ +} + +ALIAS_SPECIALIZATION(_dropout, false, false) +ALIAS_SPECIALIZATION(_feature_dropout, true, false) +ALIAS_SPECIALIZATION(_alpha_dropout, false, true ) +ALIAS_SPECIALIZATION(_feature_alpha_dropout, true, true ) + +} // anonymous namespace + +std::tuple +native_dropout_cpu(const Tensor& input, double p, std::optional train) { + if (input.numel() == 0) { + return std::make_tuple(input, at::empty_like(input, input.options())); + } + + Tensor mask; + Tensor output; + + if (!train.has_value() || *train) { + double p1m = 1. - p; + // Check for probability of zero to avoid divide by zero and NaN results + double scale = p1m == 0 ? 0. : 1. / p1m; + mask = at::empty_like(input, input.options().dtype(c10::CppTypeToScalarType::value)); + mask.bernoulli_(p1m); + output = input.mul(mask).mul_(scale); + } else { + mask = at::ones_like(input, input.options().dtype(c10::CppTypeToScalarType::value)); + output = input.clone(); + } + return std::make_tuple(std::move(output), std::move(mask)); +} + +Tensor native_dropout_backward(const Tensor& grad, const Tensor& mask, double scale) { + Tensor result = grad * mask * scale; + return result; +} + +Tensor dropout(const Tensor& input, double p, bool train) { + auto result = [&]() { + // TODO: we can remove this is_nested() code smell in the future + // if we find a way to support _dropout for nested tensor + // e.g. make it an op (at::_dropout) to use dispatcher? + if (input.is_nested() || (train && is_fused_kernel_acceptable(input, p))) { + return std::get<0>(at::native_dropout(input, p, train)); + } + return _dropout(input, p, train); + }(); + return result; +} + +Tensor& dropout_(Tensor& input, double p, bool train) { + return _dropout(input, p, train); +} + +Tensor feature_dropout(const Tensor& input, double p, bool train) { + return _feature_dropout(input, p, train); +} + +Tensor& feature_dropout_(Tensor& input, double p, bool train) { + return _feature_dropout(input, p, train); +} + +Tensor alpha_dropout(const Tensor& input, double p, bool train) { + return _alpha_dropout(input, p, train); +} + +Tensor& alpha_dropout_(Tensor& input, double p, bool train) { + return _alpha_dropout(input, p, train); +} + +Tensor feature_alpha_dropout(const Tensor& input, double p, bool train) { + return _feature_alpha_dropout(input, p, train); +} + +Tensor& feature_alpha_dropout_(Tensor& input, double p, bool train) { + return _feature_alpha_dropout(input, p, train); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Embedding.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Embedding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ebfbbff34da0eee0cc36b08bcf670e5bce598a1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Embedding.cpp @@ -0,0 +1,215 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include + +#include +#include +#include +#include + + +namespace at::native { + +Tensor embedding_symint(const Tensor & weight, const Tensor & indices, + c10::SymInt padding_idx, bool scale_grad_by_freq, bool sparse) { + TORCH_CHECK(weight.dim() == 2, "'weight' must be 2-D"); + auto indices_arg = TensorArg(indices, "indices", 1); + checkScalarTypes("embedding", indices_arg, {kLong, kInt}); + + // TODO: use tensor.index() after improving perf + if (indices.dim() == 1) { + return weight.index_select(0, indices); + } + + auto size = indices.sym_sizes().vec(); + for (const auto& d : weight.sym_sizes().slice(1)) { + size.push_back(d); + } + + return weight.index_select(0, indices.reshape(-1)).view_symint(size); +} + +Tensor embedding_backward_symint( + const Tensor & grad, const Tensor & indices, c10::SymInt num_weights, + c10::SymInt padding_idx, bool scale_grad_by_freq, bool sparse) { + if (sparse) { + // TODO: if we teach sparse tensor how to propagate symints, the guard + // here is not strictly necessary. However, we think it is fine as is + // because num weights is derived from a parameter and therefore + // typically not varying. + return at::embedding_sparse_backward( + grad, indices, + num_weights.guard_int(__FILE__, __LINE__), + padding_idx.guard_int(__FILE__, __LINE__), + scale_grad_by_freq); + } else { + return at::embedding_dense_backward_symint( + grad, indices, std::move(num_weights), padding_idx, scale_grad_by_freq); + } +} + +Tensor embedding_sparse_backward( + const Tensor & grad_, const Tensor & indices_, int64_t num_weights, + int64_t padding_idx, bool scale_grad_by_freq) { + + auto indices_arg = TensorArg(indices_, "indices", 2); + checkScalarTypes("embedding_backward", indices_arg, {kLong, kInt}); + + // TODO: implement scale_grad_by_freq + if (scale_grad_by_freq) { + TORCH_CHECK(false, + "embedding_backward: scale_grad_by_freq not supported with sparse gradients"); + } + + Tensor indices = indices_; + Tensor grad = grad_; + if (padding_idx != -1) { + c10::List> c({indices != padding_idx}); + indices = indices.index(c); + grad = grad.index(c); + } + + auto num_features = grad_.sym_size(-1); + auto weight_size = std::array{{ num_weights, num_features }}; + auto dense_options = grad.options(); + + // check if all our grad come from padding_idx + if (grad.sym_numel() == 0) { + return at::_sparse_coo_tensor_unsafe_symint(at::empty({1, 0}, indices_.options().dtype(kLong)), + at::empty_symint({c10::SymInt(0), std::move(num_features)}, dense_options), + weight_size); + } + + auto index = indices.reshape({1, -1}); + auto values = grad.reshape_symint({c10::SymInt(-1), std::move(num_features)}); + return at::_sparse_coo_tensor_unsafe_symint(index.to(kLong), values, weight_size); +} + +Tensor embedding_dense_backward_cpu( + const Tensor & grad_, const Tensor & indices, int64_t num_weights, + int64_t padding_idx, bool scale_grad_by_freq) { + + auto indices_arg = TensorArg(indices, "indices", 2); + checkScalarTypes("embedding_backward", indices_arg, {kLong, kInt}); + + auto grad_weight = at::zeros({num_weights, grad_.size(-1)}, grad_.options()); + auto indices_contig = indices.contiguous(); + int64_t numel = indices.numel(); + auto grad = grad_.contiguous().view({numel, grad_.size(-1)}); + + auto add_iter = TensorIteratorConfig() + .add_output(grad_weight) + .add_input(grad_weight) + .add_const_input(grad) + .resize_outputs(false) + .declare_static_shape(grad.sizes(), /*squash_dims=*/0) + .build(); + + const auto gW_data = reinterpret_cast(grad_weight.data_ptr()); + const auto gO_data = reinterpret_cast(grad.const_data_ptr()); + const auto gW_stride = grad_weight.strides()[0] * grad_weight.element_size(); + const auto gO_stride = grad.strides()[0] * grad.element_size(); + + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_dense_backward_cpu", [&] () { + auto indices_data = indices_contig.const_data_ptr(); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + std::unique_ptr counts; + if (scale_grad_by_freq) { + counts.reset(new index_t[num_weights]); + for (const auto i : c10::irange(numel)) { + counts[indices_data[i]] = 0; + } + for (const auto i : c10::irange(numel)) { + counts[indices_data[i]]++; + } + } + + auto parallel_section = [&](index_t start, index_t end) { + TensorIterator iter(add_iter); + for (const auto i : c10::irange(numel)) { + if (indices_data[i] != padding_idx) { + index_t k = indices_data[i]; + if (k >= start && k < end) { + double scale = 1.0; + if (scale_grad_by_freq) { + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scale /= counts[k]; + } + + // grad_weight[k].add_(grad[i], scale); + iter.unsafe_replace_operand(0, gW_data + k * gW_stride); + iter.unsafe_replace_operand(1, gW_data + k * gW_stride); + iter.unsafe_replace_operand(2, const_cast(gO_data + i * gO_stride)); + add_stub(kCPU, iter, scale); + } + } + } + }; + + at::parallel_for(0, num_weights, 1000, parallel_section); + + }); + + return grad_weight; +} + +Tensor & embedding_renorm_cpu_( + Tensor & self, const Tensor & indices, double max_norm, double norm_type) { + auto self_arg = TensorArg(self, "self", 1); + auto indices_arg = TensorArg(indices, "indices", 2); + checkDim("embedding_renorm_", self_arg, 2); + checkScalarTypes("embedding_renorm_", indices_arg, {kLong, kInt}); + + auto indices_contig = indices.contiguous(); + auto num_indices = indices.numel(); + + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_renorm_cpu_", [&]() { + auto data_ptr = indices_contig.const_data_ptr(); + auto sorted_indices = std::vector(data_ptr, data_ptr + num_indices); + std::sort(sorted_indices.begin(), sorted_indices.end()); + + // Note that we cannot use at::parallel_for here because we perform operations on + // Tensor inside the loop. See github.com/pytorch/pytorch/issues/28370 for more details. + for (const auto i : c10::irange(num_indices)) { + if (i > 0 && sorted_indices[i] == sorted_indices[i - 1]) { + continue; + } + auto row = self[sorted_indices[i]]; + auto norm = row.norm(norm_type).item(); + if (norm > max_norm) { + auto scale = max_norm / (norm + 1e-7); + row *= scale; + } + } + }); + + return self; +} + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/EmbeddingBag.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/EmbeddingBag.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2621c278bc8975f6e560b3c686d630549fcb374 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/EmbeddingBag.cpp @@ -0,0 +1,1779 @@ +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#ifdef USE_FBGEMM +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi") +#include +#include +C10_DIAGNOSTIC_POP() +#else +#include +#endif + +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +template +scalar_t dot_impl(int64_t n, const scalar_t *x, int64_t incx, const scalar_t *y, int64_t incy); + +static void make_offset2bag(const Tensor &offsets, Tensor& offset2bag) { + offset2bag.index_add_( + 0, offsets, at::ones_like(offsets, LEGACY_CONTIGUOUS_MEMORY_FORMAT)); // offset2bag = [1 0 1 0 1] + offset2bag[0] -= 1; // offset2bag = [0 0 1 0 1] + offset2bag = offset2bag.cumsum(0, offset2bag.scalar_type()); // offset2bag = [0 0 1 1 2] +} + +namespace { + +std::pair, c10::MaybeOwned> promoteIndicesAndOffsets( + const Tensor& indices, + const Tensor& offsets) { + const auto commonType = + promoteTypes(offsets.scalar_type(), indices.scalar_type()); + return { + indices.scalar_type() == commonType ? c10::MaybeOwned::borrowed(indices) + : c10::MaybeOwned::owned(indices.toType(commonType)), + offsets.scalar_type() == commonType ? c10::MaybeOwned::borrowed(offsets) + : c10::MaybeOwned::owned(offsets.toType(commonType))}; +} + +// Determines if we can use a fast implementation for index_select_add, which +// is only applicable if special conditions are met +template +bool is_fast_path_index_select(const Tensor& src, Tensor& output, index_t padding_idx) { + return (src.scalar_type() == kFloat || src.scalar_type() == kHalf || + src.scalar_type() == kBFloat16) && + src.strides()[1] == 1 && output.strides()[1] == 1 && + padding_idx < static_cast(0); +} + +// Determines if we can use a fast implementation for index_select_scale_add, +// which is only applicable if special conditions are met +template +bool is_fast_path_index_select_scale(const Tensor& src, const Tensor& scale, Tensor& output, index_t padding_idx) { + return (src.scalar_type() == kFloat || src.scalar_type() == kHalf || + src.scalar_type() == kBFloat16) && + src.strides()[1] == 1 && output.strides()[1] == 1 && + scale.strides()[0] == 1 && padding_idx < static_cast(0); +} + +template +bool is_fast_path(const Tensor& src, const std::optional& scale, Tensor& output, index_t padding_idx) { + return (scale.has_value() && scale.value().defined()) ? + is_fast_path_index_select_scale(src, scale.value(), output, padding_idx) : + is_fast_path_index_select(src, output, padding_idx); +} + +// This function combines index_select (using select_indices as the index) and +// index_add (using add_indices as the index), without creating an intermediary +// tensor to hold the selected embeddings +template +std::enable_if_t, void> +index_select_add( + const Tensor& select_indices, + const Tensor& add_indices, + const Tensor& src, + Tensor& output, + [[maybe_unused]] const Tensor& offsets, + [[maybe_unused]] bool include_last_offset, + Tensor& bag_size, + index_t padding_idx, + [[maybe_unused]] _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + TORCH_CHECK(select_indices.numel() == add_indices.numel()); + auto* add_indices_data = add_indices.const_data_ptr(); + auto* select_indices_data = select_indices.const_data_ptr(); + auto* src_data = src.const_data_ptr(); + auto* output_data = output.data_ptr(); + index_t* bag_size_data = nullptr; + if (bag_size.defined()) { + bag_size_data = bag_size.data_ptr(); + } + auto numel = add_indices.numel(); + int64_t ddim = src.size(1); + auto vocab_size = src.size(0); + auto src_stride0 = src.strides()[0]; + auto src_stride1 = src.strides()[1]; + auto output_stride0 = output.strides()[0]; + auto output_stride1 = output.strides()[1]; + + for (const auto i : c10::irange(numel)) { + // We can skip indices equal to padding_idx so they are not included in + // the reduction + auto idx = select_indices_data[i]; + TORCH_CHECK( + idx >= 0 && idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + idx); + if (idx != padding_idx) { + at::native::cpublas::axpy(ddim, 1, + src_data + src_stride0 * idx, src_stride1, + output_data + output_stride0 * add_indices_data[i], output_stride1); + } else if (bag_size_data) { + // Decrement bag_size to reflect that the index is padded + bag_size_data[add_indices_data[i]]--; + } + } +} + +namespace { +template +void fbgemm_spmdm_report_error_( + int64_t output_size, + int index_size, + int64_t N, + const index_t* offsets, + const index_t* indices) { + for (const auto m : c10::irange(output_size)) { + for (index_t i = offsets[m]; i < offsets[m + 1]; ++i) { + TORCH_CHECK(i < index_size); + index_t idx = indices[i]; + TORCH_CHECK( + 0 <= idx && idx < N, + "Index ", + i, + " of input takes value ", + idx, + " which is not in the valid range [0, ", + N, + ")"); + } + } + TORCH_CHECK( + offsets[output_size] == index_size, + "Your input appears to be incorrect: the last offset value should be " + "the size of the indices tensor, but it seems not to be the case."); +} +} // namespace + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> +index_select_add( + const Tensor& select_indices, + const Tensor& add_indices, + const Tensor& src, + Tensor& output, + const Tensor& offsets, + bool include_last_offset, + Tensor& bag_size, + index_t padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + int64_t ddim = src.size(1); + auto* select_indices_data = select_indices.const_data_ptr(); + auto* output_data = output.data_ptr(); + + if (is_fast_path_index_select(src, output, padding_idx)) { + auto src_contig = src.contiguous(); + auto* src_data = src_contig.const_data_ptr(); + int64_t output_size = offsets.numel() - 1; + auto* offsets_data = offsets.const_data_ptr(); + std::vector offsets_include_last; + + if (include_last_offset) { + output_size = offsets.numel() - 1; + } else { + output_size = offsets.numel(); + offsets_include_last.resize(offsets.numel() + 1); + if (offsets.numel() > 0) { + std::memcpy( + offsets_include_last.data(), + offsets.const_data_ptr(), + sizeof(index_t) * offsets.numel()); + } + offsets_include_last[offsets.numel()] = select_indices.numel(); + offsets_data = offsets_include_last.data(); + } +#if defined(USE_FBGEMM) + constexpr bool isbf16 = std::is_same_v ? false : true; + auto kernel_16bit_index_t = fbgemm_kernel_cache + ? fbgemm_kernel_cache + ->getCallback(ddim) + : fbgemm::GenerateEmbeddingSpMDM( + /* block_size */ ddim, + /* has_weight */ false, + /* normalize_by_lengths */ false, + /* prefetch */ 16, + /* is_weight_positional */ false, + /* use_offsets */ true, + /* is_bf16_out */ isbf16, + /* is_bf16_in */ isbf16); + at::parallel_for( + 0, output_size, 1, [&](index_t start_idx, index_t end_idx) { + bool success = kernel_16bit_index_t( + /* output_size */ end_idx - start_idx, + /* index_size */ offsets_data[end_idx] - offsets_data[start_idx], + /* data_size */ src.size(0), + /* input */ reinterpret_cast(src_data), + /* indices */ select_indices_data + offsets_data[start_idx], + /* offsets_or_lengths */ offsets_data + start_idx, + /* weights */ nullptr, + /* output */ + reinterpret_cast(output_data + start_idx * ddim)); + if (!success) { + fbgemm_spmdm_report_error_( + end_idx - start_idx, + offsets_data[end_idx] - offsets_data[start_idx], + src.size(0), + offsets_data + start_idx, + select_indices_data + offsets_data[start_idx]); + } + }); +#else + // Initialize the intermediate output buffer to be 0. + Tensor output_fp32 = at::zeros({output_size, ddim}, output.options().dtype(at::kFloat)); + auto* output_data_fp32 = output_fp32.data_ptr(); + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + at::parallel_for( + 0, output_size, 1, [&](index_t start_idx, index_t end_idx) { + caffe2::EmbeddingLookupIdx( + /*block_size=*/ddim, + /*output_size=*/end_idx - start_idx, + /*index_size=*/offsets_data[end_idx] - offsets_data[start_idx], + /*data_size=*/src.size(0), + /*input=*/src_data, + /*indices=*/select_indices_data + offsets_data[start_idx], + /*offsets=*/offsets_data + start_idx, + /*weights=*/nullptr, + /*scale_bias=*/nullptr, + /*normalize_by_lengths=*/false, + /*out=*/output_data_fp32 + start_idx * ddim); + for (int64_t i = start_idx; i < end_idx; i++) { + // Convert FP32 intermediate buffer result back to 16 bit for + // output dtype + if constexpr (std::is_same_v) { + // FP16 + for (const auto d : c10::irange(ddim)) { + (output_data + i * ddim)[d] = + static_cast((output_data_fp32 + ddim * i)[d]); + } + } else { + // BF16 + int64_t d = 0; + for (; d < ddim - (ddim % bVec::size()); d += bVec::size()) { + fVec temp_fp32_0 = fVec::loadu(output_data_fp32 + ddim * i + d); + fVec temp_fp32_1 = + fVec::loadu(output_data_fp32 + ddim * i + d + fVec::size()); + convert_float_bfloat16(temp_fp32_0, temp_fp32_1) + .store(output_data + i * ddim + d); + } + for (; d < ddim; d++) { + (output_data + i * ddim)[d] = + static_cast((output_data_fp32 + ddim * i)[d]); + } + } + } + }); +#endif + } else { + TORCH_CHECK(select_indices.numel() == add_indices.numel()); + auto* src_data = src.const_data_ptr(); + auto* add_indices_data = add_indices.const_data_ptr(); + index_t* bag_size_data = nullptr; + if (bag_size.defined()) { + bag_size_data = bag_size.data_ptr(); + } + auto vocab_size = src.size(0); + auto src_stride0 = src.strides()[0]; + auto src_stride1 = src.strides()[1]; + auto output_stride0 = output.strides()[0]; + auto output_stride1 = output.strides()[1]; + auto numel = add_indices.numel(); + + Tensor src_fp32 = at::empty({ddim}, src.options().dtype(at::kFloat)); + auto* src_data_fp32 = src_fp32.mutable_data_ptr(); + + // Initialize the intermediate output buffer to be 0. + Tensor output_fp32 = + at::zeros({output.size(0), ddim}, output.options().dtype(at::kFloat)); + auto* output_data_fp32 = output_fp32.data_ptr(); + + for (const auto i : c10::irange(numel)) { + // We can skip indices equal to padding_idx so they are not included in + // the reduction + auto idx = select_indices_data[i]; + TORCH_CHECK( + idx >= 0 && idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + idx); + if (idx != padding_idx) { + // Copy src_data + src_stride0 * idx to src_data_fp32 + for (const auto d : c10::irange(ddim)) { + src_data_fp32[d] = static_cast( + (src_data + src_stride0 * idx)[d * src_stride1]); + } + at::native::cpublas::axpy( + ddim, + 1, + src_data_fp32, + 1, + output_data_fp32 + ddim * add_indices_data[i], + 1); + + } else if (bag_size_data) { + // Decrement bag_size to reflect that the index is padded + bag_size_data[add_indices_data[i]]--; + } + } + for (const auto i : c10::irange(output.size(0))) { + // Convert FP32 intermediate buffer result back to 16 bit for output + // dtype + for (const auto d : c10::irange(ddim)) { + (output_data + output_stride0 * i)[d * output_stride1] = + static_cast((output_data_fp32 + ddim * i)[d]); + } + } + } +} +template +std::enable_if_t, void> +index_select_add(const Tensor &select_indices, + const Tensor &add_indices, + const Tensor &src, + Tensor &output, + const Tensor& offsets, + bool include_last_offset, + Tensor &bag_size, + index_t padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + int64_t ddim = src.size(1); + auto* select_indices_data = select_indices.const_data_ptr(); + auto* output_data = output.data_ptr(); + + if (is_fast_path_index_select(src, output, padding_idx)) { + auto src_contig = src.contiguous(); + auto* src_data = src_contig.const_data_ptr(); + int64_t output_size = offsets.numel() - 1; + auto* offsets_data = offsets.const_data_ptr(); + std::vector offsets_include_last; + + if (include_last_offset) { + output_size = offsets.numel() - 1; + } else { + output_size = offsets.numel(); + offsets_include_last.resize(offsets.numel() + 1); + if (offsets.numel() > 0) { + std::memcpy( + offsets_include_last.data(), + offsets.const_data_ptr(), + sizeof(index_t) * offsets.numel()); + } + offsets_include_last[offsets.numel()] = select_indices.numel(); + offsets_data = offsets_include_last.data(); + } + +#ifdef USE_FBGEMM + auto kernel_fp32_index_t = + fbgemm_kernel_cache ? + fbgemm_kernel_cache->getCallback(ddim) : + fbgemm::GenerateEmbeddingSpMDM( + /* block_size */ddim, + /* has_weight */false, + /* normalize_by_lengths */false, + /* prefetch */16, + /* is_weight_positional */false, + /* use_offsets */true + ); +#endif + at::parallel_for( + 0, output_size, 1, [&](index_t start_idx, index_t end_idx) { +#ifdef USE_FBGEMM + bool success = kernel_fp32_index_t( + /* output_size */end_idx - start_idx, + /* index_size */offsets_data[end_idx] - offsets_data[start_idx], + /* data_size */src.size(0), + /* input */src_data, + /* indices */select_indices_data + offsets_data[start_idx], + /* offsets_or_lengths */offsets_data + start_idx, + /* weights */nullptr, + /* output */output_data + start_idx * ddim); + if (!success) { + fbgemm_spmdm_report_error_( + end_idx - start_idx, + offsets_data[end_idx] - offsets_data[start_idx], + src.size(0), + offsets_data + start_idx, + select_indices_data + offsets_data[start_idx]); + } +#else + caffe2::EmbeddingLookupIdx( + /*block_size=*/ddim, + /*output_size=*/end_idx - start_idx, + /*index_size=*/offsets_data[end_idx] - offsets_data[start_idx], + /*data_size=*/src.size(0), + /*input=*/src_data, + /*indices=*/select_indices_data + offsets_data[start_idx], + /*offsets=*/offsets_data + start_idx, + /*weights=*/nullptr, + /*scale_bias=*/nullptr, + /*normalize_by_lengths=*/false, + /*out=*/output_data + start_idx * ddim); +#endif + }); + } else { + AT_ASSERT(select_indices.numel() == add_indices.numel()); + auto* src_data = src.const_data_ptr(); + auto* add_indices_data = add_indices.const_data_ptr(); + index_t* bag_size_data = nullptr; + if (bag_size.defined()) { + bag_size_data = bag_size.data_ptr(); + } + auto vocab_size = src.size(0); + auto src_stride0 = src.strides()[0]; + auto src_stride1 = src.strides()[1]; + auto output_stride0 = output.strides()[0]; + auto output_stride1 = output.strides()[1]; + auto numel = add_indices.numel(); + for (const auto i : c10::irange(numel)) { + // We can skip indices equal to padding_idx so they are not included in + // the reduction + auto idx = select_indices_data[i]; + TORCH_CHECK( + idx >= 0 && idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + idx); + if (idx != padding_idx) { + at::native::cpublas::axpy( + ddim, + 1, + src_data + src_stride0 * idx, + src_stride1, + output_data + output_stride0 * add_indices_data[i], + output_stride1); + } else if (bag_size_data) { + // Decrement bag_size to reflect that the index is padded + bag_size_data[add_indices_data[i]]--; + } + } + } +} + +// This function fuses the following three fns: +// index_select (using select_indices as the index) +// mul (scaling by per_sample_weights) +// index_add (using add_indices as the index) +template +std::enable_if_t, void> +index_select_scale_add( + const Tensor& select_indices, + const Tensor& add_indices, + const Tensor& scale, + const Tensor& src, + Tensor& output, + [[maybe_unused]] const Tensor& offsets, + [[maybe_unused]] bool include_last_offset, + Tensor& bag_size, + index_t padding_idx, + [[maybe_unused]] _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + AT_ASSERT(select_indices.numel() == add_indices.numel()); + auto* add_indices_data = add_indices.const_data_ptr(); + auto* select_indices_data = select_indices.const_data_ptr(); + auto* src_data = src.const_data_ptr(); + auto* output_data = output.data_ptr(); + index_t* bag_size_data = nullptr; + if (bag_size.defined()) { + bag_size_data = bag_size.data_ptr(); + } + auto numel = add_indices.numel(); + int64_t ddim = src.size(1); + auto vocab_size = src.size(0); + auto src_stride0 = src.strides()[0]; + auto src_stride1 = src.strides()[1]; + auto output_stride0 = output.strides()[0]; + auto output_stride1 = output.strides()[1]; + + auto* scale_data = scale.const_data_ptr(); + auto scale_stride = scale.strides()[0]; + + for (const auto i : c10::irange(numel)) { + // We can skip indices equal to padding_idx so they are not included in + // the reduction + auto idx = select_indices_data[i]; + TORCH_CHECK( + idx >= 0 && idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + idx); + if (idx != padding_idx) { + auto* src_base = src_data + src_stride0 * idx; + auto* output_base = output_data + output_stride0 * add_indices_data[i]; + auto element_scale = scale_data[i * scale_stride]; + for (const auto j : c10::irange(ddim)) { + output_base[j * output_stride1] += src_base[j * src_stride1] * element_scale; + } + } else if (bag_size_data) { + // Decrement bag_size to reflect that the index is padded + bag_size_data[add_indices_data[i]]--; + } + } +} + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> +index_select_scale_add( + const Tensor& select_indices, + const Tensor& add_indices, + const Tensor& scale, + const Tensor& src, + Tensor& output, + const Tensor& offsets, + bool include_last_offset, + Tensor& bag_size, + index_t padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + int64_t ddim = src.size(1); + auto* scale_data = scale.const_data_ptr(); + auto* select_indices_data = select_indices.const_data_ptr(); + auto* output_data = output.data_ptr(); + + if (is_fast_path_index_select_scale(src, scale, output, padding_idx)) { + auto src_contig = src.contiguous(); + auto* src_data = src_contig.const_data_ptr(); + int64_t output_size = offsets.numel() - 1; + auto* offsets_data = offsets.const_data_ptr(); + std::vector offsets_include_last; + + if (include_last_offset) { + output_size = offsets.numel() - 1; + } else { + output_size = offsets.numel(); + offsets_include_last.resize(offsets.numel() + 1); + std::memcpy( + offsets_include_last.data(), + offsets.const_data_ptr(), + sizeof(index_t) * offsets.numel()); + offsets_include_last[offsets.numel()] = select_indices.numel(); + offsets_data = offsets_include_last.data(); + } + + Tensor scale_fp32 = at::empty(scale.sizes(), scale.options().dtype(at::kFloat)); + auto* scale_data_fp32 = scale_fp32.mutable_data_ptr(); + +#if defined(USE_FBGEMM) + constexpr bool isbf16 = std::is_same_v ? false : true; + if constexpr (isbf16) { + fbgemm::Bfloat16ToFloat_simd( + reinterpret_cast(scale_data), + scale_data_fp32, + scale_fp32.numel()); + } else { + fbgemm::Float16ToFloat_simd( + reinterpret_cast(scale_data), + scale_data_fp32, + scale_fp32.numel()); + } + auto kernel_16bit_index_t = fbgemm_kernel_cache + ? fbgemm_kernel_cache + ->getCallback(ddim) + : fbgemm::GenerateEmbeddingSpMDM( + /* block_size */ ddim, + /* has_weight */ true, + /* normalize_by_lengths */ false, + /* prefetch */ 16, + /* is_weight_positional */ false, + /* use_offsets */ true, + /* is_bf16_out */ isbf16, + /* is_bf16_in */ isbf16); + at::parallel_for( + 0, output_size, 1, [&](index_t start_idx, index_t end_idx) { + bool success = kernel_16bit_index_t( + /* output_size */ end_idx - start_idx, + /* index_size */ offsets_data[end_idx] - offsets_data[start_idx], + /* data_size */ src.size(0), + /* input */ reinterpret_cast(src_data), + /* indices */ select_indices_data + offsets_data[start_idx], + /* offsets_or_lengths */ offsets_data + start_idx, + /* weights */ scale_data_fp32 + offsets_data[start_idx], + /* output */ + reinterpret_cast(output_data + start_idx * ddim)); + if (!success) { + fbgemm_spmdm_report_error_( + end_idx - start_idx, + offsets_data[end_idx] - offsets_data[start_idx], + src.size(0), + offsets_data + start_idx, + select_indices_data + offsets_data[start_idx]); + } + }); +#else + // Initialize the intermediate output buffer to be 0. + Tensor output_fp32 = + at::zeros({output_size, ddim}, output.options().dtype(at::kFloat)); + auto* output_data_fp32 = output_fp32.data_ptr(); + for (const auto i : c10::irange(scale.numel())) { + scale_data_fp32[i] = static_cast(scale_data[i]); + } + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + at::parallel_for( + 0, output_size, 1, [&](index_t start_idx, index_t end_idx) { + caffe2::EmbeddingLookupIdx( + /*block_size=*/ddim, + /*output_size=*/end_idx - start_idx, + /*index_size=*/offsets_data[end_idx] - offsets_data[start_idx], + /*data_size=*/src.size(0), + /*input=*/src_data, + /*indices=*/select_indices_data + offsets_data[start_idx], + /*offsets=*/offsets_data + start_idx, + /*weights=*/scale_data_fp32 + offsets_data[start_idx], + /*scale_bias=*/nullptr, + /*normalize_by_lengths=*/false, + /*out=*/output_data_fp32 + start_idx * ddim); + for (int64_t i = start_idx; i < end_idx; i++) { + // Convert FP32 intermediate buffer result back to 16 bit for + // output dtype + if constexpr (std::is_same_v) { + // FP16 + for (const auto d : c10::irange(ddim)) { + (output_data + i * ddim)[d] = + static_cast((output_data_fp32 + ddim * i)[d]); + } + } else { + // BF16 + int64_t d = 0; + for (; d < ddim - (ddim % bVec::size()); d += bVec::size()) { + fVec temp_fp32_0 = fVec::loadu(output_data_fp32 + ddim * i + d); + fVec temp_fp32_1 = + fVec::loadu(output_data_fp32 + ddim * i + d + fVec::size()); + convert_float_bfloat16(temp_fp32_0, temp_fp32_1) + .store(output_data + i * ddim + d); + } + for (; d < ddim; d++) { + (output_data + i * ddim)[d] = + static_cast((output_data_fp32 + ddim * i)[d]); + } + } + } + }); +#endif + } else { + AT_ASSERT(select_indices.numel() == add_indices.numel()); + auto* src_data = src.const_data_ptr(); + auto* add_indices_data = add_indices.const_data_ptr(); + index_t* bag_size_data = nullptr; + if (bag_size.defined()) { + bag_size_data = bag_size.data_ptr(); + } + auto vocab_size = src.size(0); + auto src_stride0 = src.strides()[0]; + auto src_stride1 = src.strides()[1]; + auto output_stride0 = output.strides()[0]; + auto output_stride1 = output.strides()[1]; + auto scale_stride = scale.strides()[0]; + auto numel = add_indices.numel(); + + // Initialize the intermediate output buffer to be 0. + Tensor output_fp32 = + at::zeros({output.size(0), ddim}, output.options().dtype(at::kFloat)); + auto* output_data_fp32 = output_fp32.data_ptr(); + + for (const auto i : c10::irange(numel)) { + // We can skip indices equal to padding_idx so they are not included in + // the reduction + auto idx = select_indices_data[i]; + TORCH_CHECK( + idx >= 0 && idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + idx); + if (idx != padding_idx) { + auto* src_base = src_data + src_stride0 * idx; + auto* output_base_fp32 = output_data_fp32 + ddim * add_indices_data[i]; + auto element_scale = scale_data[i * scale_stride]; + for (const auto j : c10::irange(ddim)) { + output_base_fp32[j] += static_cast(src_base[j * src_stride1]) * + static_cast(element_scale); + } + } else if (bag_size_data) { + // Decrement bag_size to reflect that the index is padded + bag_size_data[add_indices_data[i]]--; + } + } + for (const auto i : c10::irange(output.size(0))) { + // Convert FP32 intermediate buffer result back to 16 bit for output + // dtype + for (const auto d : c10::irange(ddim)) { + (output_data + output_stride0 * i)[d * output_stride1] = + static_cast((output_data_fp32 + ddim * i)[d]); + } + } + } +} +template +std::enable_if_t, void> +index_select_scale_add(const Tensor &select_indices, + const Tensor &add_indices, + const Tensor &scale, + const Tensor &src, + Tensor &output, + const Tensor& offsets, + bool include_last_offset, + Tensor &bag_size, + index_t padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + int64_t ddim = src.size(1); + auto* scale_data = scale.const_data_ptr(); + auto* select_indices_data = select_indices.const_data_ptr(); + auto* output_data = output.data_ptr(); + + if (is_fast_path_index_select_scale(src, scale, output, padding_idx)) { + auto src_contig = src.contiguous(); + auto* src_data = src_contig.const_data_ptr(); + int64_t output_size = offsets.numel() - 1; + auto* offsets_data = offsets.const_data_ptr(); + std::vector offsets_include_last; + + if (include_last_offset) { + output_size = offsets.numel() - 1; + } else { + output_size = offsets.numel(); + offsets_include_last.resize(offsets.numel() + 1); + std::memcpy( + offsets_include_last.data(), + offsets.const_data_ptr(), + sizeof(index_t) * offsets.numel()); + offsets_include_last[offsets.numel()] = select_indices.numel(); + offsets_data = offsets_include_last.data(); + } + +#ifdef USE_FBGEMM + auto kernel_fp32_index_t = + fbgemm_kernel_cache ? + fbgemm_kernel_cache->getCallback(ddim) : + fbgemm::GenerateEmbeddingSpMDM( + /* block_size */ddim, + /* has_weight */true, + /* normalize_by_lengths */false, + /* prefetch */16, + /* is_weight_positional */false, + /* use_offsets */true + ); +#endif + at::parallel_for( + 0, output_size, 1, [&](index_t start_idx, index_t end_idx) { +#ifdef USE_FBGEMM + bool success = kernel_fp32_index_t( + /* output_size */end_idx - start_idx, + /* index_size */offsets_data[end_idx] - offsets_data[start_idx], + /* data_size */src.size(0), + /* input */src_data, + /* indices */select_indices_data + offsets_data[start_idx], + /* offsets_or_lengths */offsets_data + start_idx, + /* weights */scale_data + offsets_data[start_idx], + /* output */output_data + start_idx * ddim); + if (!success) { + fbgemm_spmdm_report_error_( + end_idx - start_idx, + offsets_data[end_idx] - offsets_data[start_idx], + src.size(0), + offsets_data + start_idx, + select_indices_data + offsets_data[start_idx]); + } +#else + caffe2::EmbeddingLookupIdx( + /*block_size=*/ddim, + /*output_size=*/end_idx - start_idx, + /*index_size=*/offsets_data[end_idx] - offsets_data[start_idx], + /*data_size=*/src.size(0), + /*input=*/src_data, + /*indices=*/select_indices_data + offsets_data[start_idx], + /*offsets=*/offsets_data + start_idx, + /*weights=*/scale_data + offsets_data[start_idx], + /*scale_bias=*/nullptr, + /*normalize_by_lengths=*/false, + /*out=*/output_data + start_idx * ddim); +#endif + }); + } else { + AT_ASSERT(select_indices.numel() == add_indices.numel()); + auto* src_data = src.const_data_ptr(); + auto* add_indices_data = add_indices.const_data_ptr(); + index_t* bag_size_data = nullptr; + if (bag_size.defined()) { + bag_size_data = bag_size.data_ptr(); + } + auto vocab_size = src.size(0); + auto src_stride0 = src.strides()[0]; + auto src_stride1 = src.strides()[1]; + auto output_stride0 = output.strides()[0]; + auto output_stride1 = output.strides()[1]; + auto scale_stride = scale.strides()[0]; + auto numel = add_indices.numel(); + + + for (const auto i : c10::irange(numel)) { + // We can skip indices equal to padding_idx so they are not included in + // the reduction + auto idx = select_indices_data[i]; + TORCH_CHECK( + idx >= 0 && idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + idx); + if (idx != padding_idx) { + auto* src_base = src_data + src_stride0 * idx; + auto* output_base = output_data + output_stride0 * add_indices_data[i]; + auto element_scale = scale_data[i * scale_stride]; + for (const auto j : c10::irange(ddim)) { + output_base[j * output_stride1] += src_base[j * src_stride1] * element_scale; + } + } else if (bag_size_data) { + // Decrement bag_size to reflect that the index is padded + bag_size_data[add_indices_data[i]]--; + } + } + } +} + +} // namespace + +void check_arguments( + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const std::optional& per_sample_weights, + bool include_last_offset) { + auto indices_arg = TensorArg(indices, "indices", 1); + checkScalarTypes("embedding_bag", indices_arg, {kLong, kInt}); + auto offsets_arg = TensorArg(offsets, "offsets", 1); + checkScalarTypes("embedding_bag", offsets_arg, {kLong, kInt}); + checkSameType("embedding_bag", indices_arg, offsets_arg); + auto weight_arg = TensorArg(weight, "weight", 1); + checkScalarTypes( + "embedding_bag", weight_arg, {kHalf, kBFloat16, kFloat, kDouble}); + + AT_DISPATCH_INDEX_TYPES(offsets.scalar_type(), "_embedding_bag_cpu_impl", [&]() { + if (offsets.size(0) > 0) { + index_t offset_0 = offsets.const_data_ptr()[0]; + index_t offset_n = offsets.const_data_ptr()[offsets.size(0)-1]; + TORCH_CHECK(offset_0 == 0, "offsets[0] has to be 0, i.e., the first sequence " + "in the mini-batch has to start from position 0. " + "However, got ", offsets[0]); + TORCH_CHECK(offset_n <= indices.size(0), "offsets[-1] can not " + "be greater than input's length ", indices.size(0), " but got offsets[-1] of ", + offset_n); + } + }); + + if (per_sample_weights.has_value() && per_sample_weights.value().defined()) { + TORCH_CHECK( + mode == EmbeddingBagMode::SUM, + "embedding_bag: per_sample_weights only supported with mode='sum'"); + auto per_input_weights_arg = TensorArg( + per_sample_weights.value(),"per_sample_weights", 1); + checkSameType("embedding_bag", weight_arg, per_input_weights_arg); + TORCH_CHECK(per_sample_weights.value().dim() == 1); + TORCH_CHECK(per_sample_weights.value().numel() == indices.numel()); + } + + if (include_last_offset) { + TORCH_CHECK( + offsets.size(0) >= 1, + "include_last_offset: number of offset should be at least 1"); + } +} + +void make_bag_size_out( + Tensor& bag_size_out, + const Tensor& offsets, + const Tensor& indices, + const int64_t mode, + const bool include_last_offset, + const bool requires_grad) { + if (requires_grad || mode == EmbeddingBagMode::MEAN || + mode == EmbeddingBagMode::MAX) { + auto num_bags = offsets.size(0) - (include_last_offset ? 1 : 0); + at::native::resize_(bag_size_out, {num_bags}, std::nullopt); + // Compute this for EmbeddingBagMode::MEAN and EmbeddingBagMode::MAX (latter + // needed for backwards) + if (num_bags != 1) { + bag_size_out.slice(0, 0, bag_size_out.size(0) - 1, 1) = + offsets.slice(0, 1, num_bags, 1) - + offsets.slice(0, 0, num_bags - 1, 1); + } + if (num_bags > 0) { + bag_size_out[-1] = indices.size(0) - offsets[num_bags - 1]; + } + } else { + at::native::resize_(bag_size_out, offsets.sizes(), std::nullopt); + } +} + +void make_max_indices_out( + Tensor& max_indices_out, + const Tensor& weight, + [[maybe_unused]] const Tensor& indices, + const Tensor& offsets, + const Tensor& bag_size, + const int64_t mode, + bool include_last_offset) { + int64_t numBags = offsets.size(0); + if (mode == EmbeddingBagMode::MAX) { + if (include_last_offset) { + TORCH_CHECK( + numBags >= 1, "include_last_offset: numBags should be at least 1"); + numBags -= 1; + } + at::native::resize_(max_indices_out, {numBags, weight.sizes()[1]}, std::nullopt); + at::native::zero_(max_indices_out); + } else { + at::native::resize_(max_indices_out, bag_size.sizes(), std::nullopt); + } +} + +void make_offset2bag_out( + Tensor& offset2bag, + Tensor& output, + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const std::optional& per_sample_weights, + const int64_t padding_idx) { + // To save compute, if we are going to go down the fast path case for the 'sum' + // mode, we skip calculating offset2bag, since it is not going to be used. + bool fast_path_sum = is_fast_path(weight, per_sample_weights, output, padding_idx); + + if (mode == EmbeddingBagMode::MEAN || mode == EmbeddingBagMode::MAX || + !fast_path_sum) { + at::native::resize_(offset2bag, {indices.size(0) + 1}, std::nullopt); + at::native::zero_(offset2bag); + + int64_t offsets_size = offsets.size(0); + bool include_last_offset = (output.size(0) == offsets_size - 1); + // when include_last_offset is true, ignore the last index in offset. + // fix segfault when include_last_offset is true and offsets[-1] != indices.size(0) + // see https://github.com/pytorch/pytorch/issues/89677 for more details. + Tensor _offsets = offsets; + if (include_last_offset) { + _offsets = offsets.narrow(0, 0, offsets_size - 1); + } + make_offset2bag(_offsets, offset2bag); + at::native::resize_(offset2bag, {indices.size(0)}, std::nullopt); + // only initialize output in slow path + at::native::zero_(output); + } +} + +static Tensor make_bag_size( + const Tensor& offsets, + const Tensor& indices, + const int64_t mode, + const bool include_last_offset, + const bool requires_grad) { + Tensor bag_size = at::empty(offsets.sizes(), offsets.options()); + make_bag_size_out(bag_size, offsets, indices, mode, include_last_offset, requires_grad); + return bag_size; +} + +static Tensor make_max_indices( + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const Tensor& bag_size, + const int64_t mode, + bool include_last_offset) { + Tensor max_indices = at::empty(bag_size.sizes(), offsets.options()); + make_max_indices_out(max_indices, weight, indices, offsets, bag_size, mode, include_last_offset); + return max_indices; +} + +static Tensor make_offset2bag( + Tensor& output, + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const std::optional& per_sample_weights, + const int64_t padding_idx) { + Tensor offset2bag = at::empty({0}, offsets.options()); + make_offset2bag_out(offset2bag, output, weight, indices, offsets, mode, per_sample_weights, padding_idx); + return offset2bag; +} + +static Tensor apply_bag_size( + const int64_t mode, + Tensor &output, + const Tensor &bag_size) { + if (mode == EmbeddingBagMode::MEAN) { + auto bag_size_ = at::max(bag_size, at::ones_like(bag_size, LEGACY_CONTIGUOUS_MEMORY_FORMAT)) + .to(output.options()) + .unsqueeze(1) + .expand_as(output); + output /= bag_size_; + } + return output; +} + +static Tensor apply_bag_size_backward( + const int64_t mode, + Tensor &output, + const Tensor &offset2bag, + const Tensor &bag_size) { + if (mode == EmbeddingBagMode::MEAN) { + auto inv_bag_size_ = (1 / bag_size.to(output.options())) + .unsqueeze(1) + .index_select(0, offset2bag); + output *= inv_bag_size_; + } + return output; +} + +template +static void embedding_bag_cpu_max_out( + Tensor* max_indices, + const Tensor& weight, + const Tensor& indices, + const Tensor& offset2bag, + const Tensor& output, + [[maybe_unused]] bool include_last_offset, + Tensor& bag_size, + int64_t padding_idx) { + int64_t numIndices = indices.numel(); + int64_t featureSize = weight.size(1); + int64_t vocab_size = weight.size(0); + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_bag_cpu_max_out", [&] { + auto* indices_data = indices.const_data_ptr(); + auto* offset2bag_data = offset2bag.data_ptr(); + + index_t* max_indices_data = nullptr; + int64_t max_indices_stride = 0; + if (max_indices) { + max_indices_data = max_indices->data_ptr(); + max_indices_stride = max_indices->strides()[0]; + } + + auto* weight_data = weight.const_data_ptr(); + auto* output_data = output.data_ptr(); + auto* bag_size_data = bag_size.data_ptr(); + auto weight_stride0 = weight.strides()[0]; + auto weight_stride1 = weight.strides()[1]; + auto output_stride = output.strides()[0]; + int64_t numBags = bag_size.size(0); + std::vector bag_empty(numBags, true); + + for (const auto i : c10::irange(numIndices)) { + auto bag = offset2bag_data[i]; + auto word_idx = indices_data[i]; + TORCH_CHECK( + word_idx >= 0 && word_idx < vocab_size, + "embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ", + word_idx); + if (word_idx != static_cast(padding_idx)) { + bool is_first_for_bag = bag_empty[bag]; + for (const auto dim : c10::irange(featureSize)) { + auto& current_item = output_data[output_stride * bag + dim]; + auto weight_item = + weight_data[weight_stride0 * word_idx + dim * weight_stride1]; + + if (is_first_for_bag || (weight_item > current_item)) { + current_item = weight_item; + if (max_indices_data) { + max_indices_data[max_indices_stride * bag + dim] = word_idx; + } + } + } + if (is_first_for_bag) { + bag_empty[bag] = false; + } + } else { + // Decrement bag_size to reflect that the index is padded + bag_size_data[bag]--; + } + } + }); +} + +void _embedding_bag_cpu_impl_out(Tensor& output, Tensor& offset2bag, + Tensor& bag_size, Tensor* max_indices, + const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const int64_t mode, + const std::optional& per_sample_weights, + bool include_last_offset, int64_t padding_idx, _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + if (mode == EmbeddingBagMode::MEAN || mode == EmbeddingBagMode::SUM) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, weight.scalar_type(), "embedding_bag_no_grad_cpu_out", + [&indices, &offset2bag, &per_sample_weights, &weight, &output, &offsets, &include_last_offset, &mode, &bag_size, &padding_idx, &fbgemm_kernel_cache]() { + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_bag_no_grad_cpu_out", + [&indices, &offset2bag, &per_sample_weights, &weight, &output, &offsets, &include_last_offset, &mode, &bag_size, &padding_idx, &fbgemm_kernel_cache]() { + if (per_sample_weights.has_value() && per_sample_weights.value().defined()) { + TORCH_INTERNAL_ASSERT(mode == EmbeddingBagMode::SUM); + index_select_scale_add( + indices, offset2bag, per_sample_weights.value(), weight, output, offsets, include_last_offset, bag_size, padding_idx, fbgemm_kernel_cache); + } else { + index_select_add(indices, offset2bag, weight, output, offsets, include_last_offset, bag_size, padding_idx, fbgemm_kernel_cache); + } + }); + }); + apply_bag_size(mode, output, bag_size); + if (mode == EmbeddingBagMode::SUM) { + // make bag_size output deterministic + at::native::zero_(bag_size); + } + if (max_indices) { + max_indices->copy_(bag_size); + } + } else { + TORCH_CHECK(mode == EmbeddingBagMode::MAX, "`mode` must be sum, mean, or max.") + + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + weight.scalar_type(), + "embedding_bag_cpu_max_out", + [&]() { + embedding_bag_cpu_max_out( + max_indices, + weight, + indices, + offset2bag, + output, + include_last_offset, + bag_size, + padding_idx); + }); + } +} + +// Assumes all input tensors except for `weight` are contiguous. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +static std::tuple _embedding_bag_cpu_impl( + const Tensor& weight, + const Tensor& indices_, + const Tensor& offsets_, + const int64_t mode, + const Tensor& per_sample_weights, + bool include_last_offset, + int64_t padding_idx, + bool requires_grad) { + TORCH_CHECK(indices_.dim() == 1 || indices_.dim() == 2, + "input has to be a 1D or 2D Tensor, but got Tensor of dimension ", + indices_.dim()); + if (indices_.dim() == 1) { + TORCH_CHECK(offsets_.dim() == 1, + "offsets has to be a 1D Tensor, but got Tensor of dimension ", + offsets_.dim()); + } + TORCH_CHECK(weight.dim() == 2, + "weight has to be a 2D Tensor, but got Tensor of dimension ", + weight.dim()); + auto [indicesMaybeOwned, offsetsMaybeOwned] = promoteIndicesAndOffsets(indices_, offsets_); + const auto& indices = *indicesMaybeOwned; + const auto& offsets = *offsetsMaybeOwned; + check_arguments(weight, indices, offsets, mode, per_sample_weights, include_last_offset); + + Tensor output = at::empty( + {include_last_offset ? offsets.size(0) - 1 : offsets.size(0), + weight.sizes()[1]}, + weight.options()); + + Tensor offset2bag = make_offset2bag(output, weight, indices, offsets, mode, per_sample_weights, padding_idx); + + Tensor bag_size = make_bag_size(offsets, indices, mode, include_last_offset, requires_grad); + + Tensor max_indices = make_max_indices(weight, indices, offsets, bag_size, mode, include_last_offset); + + _embedding_bag_cpu_impl_out(output, offset2bag, + bag_size, &max_indices, + weight, indices, offsets, + mode, per_sample_weights, + include_last_offset, padding_idx); + + return std::make_tuple(std::move(output), std::move(offset2bag), std::move(bag_size), std::move(max_indices)); +} + +// embedding_bag wrapper to enforce contiguity in tensors other than `weight`. +// This is created to save extra `.contiguous()` call in backward. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +std::tuple +embedding_bag(const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const bool scale_grad_by_freq, + const int64_t mode, bool sparse, const std::optional& per_sample_weights_opt, + bool include_last_offset, std::optional padding_idx_opt) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + int64_t padding_idx = -1; + + if (padding_idx_opt.has_value()) { + auto num_embeddings = weight.size(0); + padding_idx = padding_idx_opt.value(); + TORCH_CHECK( + (padding_idx >= -num_embeddings) && (padding_idx < num_embeddings), + "padding_idx must be within the number of embeddings, -", num_embeddings, + " through ", num_embeddings - 1, ", but got ", padding_idx); + padding_idx = maybe_wrap_dim(padding_idx, weight.size(0)); + } + std::tuple out; + bool needs_grad_path = weight.requires_grad() || + weight._fw_grad(/*level=*/0).defined() || + (per_sample_weights_opt.has_value() && + per_sample_weights_opt.value().defined() && + per_sample_weights_opt.value().requires_grad()); + + if (!needs_grad_path) { + out = at::_embedding_bag_forward_only( + weight, indices.contiguous(), offsets.contiguous(), scale_grad_by_freq, + mode, sparse, per_sample_weights, include_last_offset, padding_idx); + } else { + out = at::_embedding_bag( + weight, indices.contiguous(), offsets.contiguous(), scale_grad_by_freq, + mode, sparse, per_sample_weights, include_last_offset, padding_idx); + } + return out; +} + +std::tuple +embedding_bag(const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const bool scale_grad_by_freq, + const int64_t mode, bool sparse, const std::optional& per_sample_weights_opt, + bool include_last_offset) { + return at::native::embedding_bag(weight, indices, offsets, scale_grad_by_freq, + mode, sparse, per_sample_weights_opt, include_last_offset, std::nullopt); +} + +// Assumes all input tensors except for `weight` are contiguous. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +std::tuple +_embedding_bag_forward_only_cpu(const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const bool scale_grad_by_freq, + const int64_t mode, bool sparse, const std::optional& per_sample_weights_opt, bool include_last_offset, + int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + std::ignore = scale_grad_by_freq; + std::ignore = sparse; + return _embedding_bag_cpu_impl( + weight, + indices, + offsets, + mode, + per_sample_weights, + include_last_offset, + padding_idx, + /*requires_grad=*/false); +} + +// Assumes all input tensors except for `weight` are contiguous. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +std::tuple +_embedding_bag_cpu(const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const bool scale_grad_by_freq, + const int64_t mode, bool sparse, const std::optional& per_sample_weights_opt, bool include_last_offset, + int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + + std::ignore = scale_grad_by_freq; + std::ignore = sparse; + return _embedding_bag_cpu_impl( + weight, + indices, + offsets, + mode, + per_sample_weights, + include_last_offset, + padding_idx, + /*requires_grad=*/true); +} + +void _embedding_bag_cpu_out( + at::Tensor& output, + at::Tensor& offset2bag, + at::Tensor& bag_size, + at::Tensor* p_max_indices, + const at::Tensor& weight, + const at::Tensor& indices_, + const at::Tensor& offsets_, + [[maybe_unused]] const bool scale_grad_by_freq, + const int64_t mode, + [[maybe_unused]] const bool sparse, + const std::optional& per_sample_weights, + const bool include_last_offset, + const std::optional& padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache) { + auto [indicesMaybeOwned, offsetsMaybeOwned] = promoteIndicesAndOffsets(indices_, offsets_); + const auto& indices = *indicesMaybeOwned; + const auto& offsets = *offsetsMaybeOwned; + at::native::check_arguments( + weight, indices, offsets, mode, per_sample_weights, include_last_offset); + + at::native::make_offset2bag_out( + offset2bag, + output, + weight, + indices, + offsets, + mode, + per_sample_weights, + padding_idx.value_or(-1)); + + at::native::make_bag_size_out( + bag_size, offsets, indices, mode, include_last_offset, false); + + if (p_max_indices) { + at::native::make_max_indices_out( + *p_max_indices, + weight, + indices, + offsets, + bag_size, + mode, + include_last_offset); + } + + at::native::_embedding_bag_cpu_impl_out( + output, + offset2bag, + bag_size, + p_max_indices, + weight, + indices, + offsets, + mode, + per_sample_weights, + include_last_offset, + padding_idx.value_or(-1), + fbgemm_kernel_cache); +} + +Tensor _embedding_bag_backward(const Tensor &grad, const Tensor &indices_, + const Tensor &offsets_, + const Tensor &offset2bag, + const Tensor &bag_size_, + const Tensor &max_indices_, + int64_t num_weights, + bool scale_grad_by_freq, int64_t mode, + bool sparse, const std::optional& per_sample_weights_opt, + int64_t padding_idx) { + return at::native::_embedding_bag_backward_symint( + grad, indices_, offsets_, offset2bag, bag_size_, max_indices_, num_weights, scale_grad_by_freq, mode, sparse, per_sample_weights_opt, padding_idx); +} + +// Assumes all input tensors are contiguous. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +Tensor _embedding_bag_backward_symint(const Tensor &grad, const Tensor &indices_, + const Tensor &offsets_, + const Tensor &offset2bag, + const Tensor &bag_size_, + const Tensor &max_indices_, + c10::SymInt num_weights, + bool scale_grad_by_freq, int64_t mode, + bool sparse, const std::optional& per_sample_weights_opt, + int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + + auto [indicesMaybeOwned, offsetsMaybeOwned] = promoteIndicesAndOffsets(indices_, offsets_); + const auto& indices = *indicesMaybeOwned; + const auto& offsets = *offsetsMaybeOwned; + auto indices_arg = TensorArg(indices, "indices", 1); + checkScalarTypes("embedding_bag", indices_arg, {kLong, kInt}); + checkContiguous("embedding_bag", indices_arg); + auto offsets_arg = TensorArg(offsets, "offsets", 1); + checkScalarTypes("embedding_bag", offsets_arg, {kLong, kInt}); + checkSameType("embedding_bag", indices_arg, offsets_arg); + checkContiguous("embedding_bag", offsets_arg); + + Tensor offset2bag_; + if (indices.sym_numel() != 0 && offset2bag.sym_numel() == 0) { + offset2bag_ = offsets.new_zeros( + {indices.size(0) + 1}, offsets.options()); // offset2bag = [0 0 0 0 0] + + make_offset2bag(offsets, offset2bag_); + // For Composite Compliance, if `offset2bag_` is CCT + // then we can't call `resize_`. Instead we call `narrow` + // to slice the tensor. + if (isTensorSubclassLike(offset2bag_)) { + offset2bag_ = offset2bag_.narrow(0, 0, indices.size(0)); + } else { + offset2bag_.resize_({indices.size(0)}); + } + } else { + auto offset2bag_arg = TensorArg(offset2bag, "offset2bag", 1); + checkScalarTypes("embedding_bag", offset2bag_arg, {kLong, kInt}); + checkContiguous("embedding_bag", offset2bag_arg); + offset2bag_ = offset2bag; + } + + if (sparse) { + return at::_embedding_bag_sparse_backward_symint( + grad, indices, offsets, offset2bag_, bag_size_, std::move(num_weights), + scale_grad_by_freq, mode, per_sample_weights, padding_idx); + } else { + return at::_embedding_bag_dense_backward_symint( + grad, indices, offset2bag_, bag_size_, max_indices_, std::move(num_weights), + scale_grad_by_freq, mode, per_sample_weights, padding_idx); + } +} + +static Tensor _embedding_bag_dense_backward_cpu_max( + const Tensor& grad, + const Tensor& bag_size, + const Tensor& max_indices, + int64_t num_weights) { + AT_ASSERT(max_indices.defined()); + auto index_grad_weight = + at::zeros({num_weights, grad.sizes()[1]}, grad.options()); + auto nonempty_max_indices = max_indices.index_select(0, bag_size.nonzero().view(-1)); + auto nonempty_grad = grad.index_select(0, bag_size.nonzero().view(-1)); + + for (const auto dim : c10::irange(grad.sizes()[1])) { + index_grad_weight.select(1, dim).index_add_( + 0, nonempty_max_indices.select(1, dim), nonempty_grad.select(1, dim)); + } + return index_grad_weight; +} + +template +static std::vector compute_counts( + int64_t num_weights, + const index_t* indices_data, + int64_t indices_length) { + std::vector counts(num_weights, 0); + for (const auto i : c10::irange(indices_length)) { + counts[indices_data[i]]++; + } + return counts; +} + +// counts_uniq stores the index of the NEXT unique element +// of the (sorted) indices vector. +// +// For example: +// indices: [0, 0, 0, 1, 3, 3, 4] +// counts: [3, 1, 0, 2, 1, 0] +// counts_uniq: [3, 4, 6, 7] +// +// The unique indices can be found at index 0, 3, 4, 6. +template +static std::vector compute_counts_uniq( + int64_t num_weights, + const index_t* indices_data, + int64_t indices_length, + const std::vector& counts) { + std::vector counts_uniq; + counts_uniq.reserve(num_weights); + int64_t o = 0; + for (int64_t i = 0; i < indices_length; i += counts[indices_data[i]]) { + counts_uniq.push_back(counts[indices_data[i]]); + if (o > 0) { + counts_uniq[o] += counts_uniq[o - 1]; + } + o++; + } + return counts_uniq; +} + +template +static void _embedding_bag_dense_backward_cpu_sum_mean( + const Tensor& grad, + const Tensor& indices_, + const Tensor& offset2bag_, + const Tensor& bag_size_, + int64_t num_weights, + bool scale_grad_by_freq, + int64_t mode, + const Tensor& per_sample_weights_, + Tensor& index_grad_weight, + int64_t padding_idx) { + + auto ind_sort_ = indices_.sort(); + auto const& indices = std::get<0>(ind_sort_); + auto const& ind_sort = std::get<1>(ind_sort_); + auto offset2bag = offset2bag_.index_select(0, ind_sort); + + std::optional per_sample_weights; + const scalar_t* per_sample_weights_data = nullptr; + std::optional per_sample_weights_stride; + if (per_sample_weights_.defined()) { + per_sample_weights = per_sample_weights_.index_select(0, ind_sort); + per_sample_weights_data = per_sample_weights->const_data_ptr(); + per_sample_weights_stride = per_sample_weights->strides()[0]; + } + + int64_t numel = indices.numel(); + + // explicitly capture all required variables to work around windows build + // TODO: fix this when windows can correctly capture variables in nested lambda + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "_embedding_bag_dense_backward_cpu_sum_mean", + [&indices, &offset2bag, &bag_size_, &num_weights, &numel, &per_sample_weights, + &per_sample_weights_data, &per_sample_weights_stride, &mode, &scale_grad_by_freq, + &grad, &index_grad_weight, &padding_idx] { + auto* indices_data = indices.const_data_ptr(); + auto* offset2bag_data = offset2bag.const_data_ptr(); + auto* bag_size_data = bag_size_.const_data_ptr(); + + auto counts = compute_counts(num_weights, indices_data, numel); + auto next_unique_index_idx = + compute_counts_uniq(num_weights, indices_data, numel, counts); + + auto loop = + [&next_unique_index_idx, &indices_data, &offset2bag_data, &bag_size_data, &per_sample_weights, + &mode, &per_sample_weights_data, &per_sample_weights_stride, &scale_grad_by_freq, + &counts, &grad, &index_grad_weight, &padding_idx + ](index_t start, index_t end) { + for (index_t i = start; i < end; i++) { + index_t indices_start = i == 0 ? 0 : next_unique_index_idx[i - 1]; + index_t index = indices_data[indices_start]; + + if (index != static_cast(padding_idx)) { + for (index_t j = indices_start; j < next_unique_index_idx[i]; j++) { + index_t source = offset2bag_data[j]; + double scale = 1.0; + if (per_sample_weights) { + AT_ASSERT(mode == EmbeddingBagMode::SUM); + scale = per_sample_weights_data[*per_sample_weights_stride * j]; + } + if (scale_grad_by_freq) { + scale /= counts[indices_data[i]]; + } + if (mode == EmbeddingBagMode::MEAN) { + auto bag_size = bag_size_data[source]; + if (bag_size != 0) { + scale /= bag_size; + } + } + int64_t ddim = grad.size(1); + auto igwd = index_grad_weight.data_ptr(); + auto gd = grad.const_data_ptr(); + at::native::cpublas::axpy(ddim, (scalar_t)scale, gd + ddim * source, 1, + igwd + ddim * index, 1); + } + } + } + }; + + if (numel > 1000) { + at::parallel_for(0, (int64_t)next_unique_index_idx.size(), 0, loop); + } else { + loop(0, (int64_t)next_unique_index_idx.size()); + } + }); +} + +Tensor _embedding_bag_dense_backward_cpu(const Tensor &grad_, const Tensor &indices_, + const Tensor &offset2bag__, + const Tensor &bag_size_, + const Tensor& max_indices_, int64_t num_weights, + bool scale_grad_by_freq, int64_t mode, const std::optional& per_sample_weights__opt, + int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights__maybe_owned = at::borrow_from_optional_tensor(per_sample_weights__opt); + const Tensor& per_sample_weights_ = *per_sample_weights__maybe_owned; + + // indices_, offsets_ and offset2bag__ are assumed having correct dtypes and + // contiguous here due to the checks in _embedding_bag_backward above. + // Also see NOTE [ embedding_bag Native Functions ] in native_functions.yaml + // for more details. + auto grad = grad_.contiguous(); + auto grad_arg = TensorArg(grad, "grad_", 1); + checkScalarTypes( + "embedding_bag", grad_arg, {kHalf, kBFloat16, kFloat, kDouble}); + + if (mode == EmbeddingBagMode::MAX) { + return _embedding_bag_dense_backward_cpu_max( + grad_, bag_size_, max_indices_, num_weights); + } + AT_ASSERT(mode == EmbeddingBagMode::MEAN || mode == EmbeddingBagMode::SUM); + + auto index_grad_weight = + at::zeros({num_weights, grad.sizes()[1]}, grad.options()); + + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + grad.scalar_type(), + "embedding_bag_backward", + [&] { + _embedding_bag_dense_backward_cpu_sum_mean( + grad, + indices_, + offset2bag__, + bag_size_, + num_weights, + scale_grad_by_freq, + mode, + per_sample_weights_, + index_grad_weight, + padding_idx); + }); + return index_grad_weight; +} + +template +static Tensor _embedding_bag_per_sample_weights_backward_cpu_template( + const Tensor& grad, + const Tensor& weight, // NB: embedding table, not per_sample_weights + const Tensor& indices_, + const Tensor& offsets_, + const Tensor& offset2bag, + int64_t mode, + int64_t padding_idx) { + TORCH_CHECK( + mode == EmbeddingBagMode::SUM, + "embedding_bag_backward: per_sample_weights only supported for mode='sum'"); + + AT_ASSERT(grad.dim() == 2); + auto embedding_features = grad.sizes()[1]; + + auto [indicesMaybeOwned, offsetsMaybeOwned] = promoteIndicesAndOffsets(indices_, offsets_); + const auto& indices = *indicesMaybeOwned; + const auto& offsets = *offsetsMaybeOwned; + + AT_ASSERT(indices.dim() == 1); + auto num_samples = indices.size(0); + + AT_ASSERT(weight.dim() == 2); + AT_ASSERT(weight.sizes()[1] == embedding_features); + + auto output = at::zeros({num_samples}, grad.options()); + + auto indices_arg = TensorArg(indices, "indices", 1); + checkScalarTypes("embedding_bag", indices_arg, {kLong, kInt}); + checkContiguous("embedding_bag", indices_arg); + + Tensor offset2bag_; + if (indices.numel() != 0 && offset2bag.numel() == 0) { + offset2bag_ = at::zeros( + {indices.size(0) + 1}, offset2bag.options()); // offset2bag = [0 0 0 0 0] + + make_offset2bag(offsets, offset2bag_); + + at::native::resize_(offset2bag_, {indices.size(0)}, std::nullopt); + } else { + auto offset2bag_arg = TensorArg(offset2bag, "offset2bag", 1); + checkScalarTypes("embedding_bag", offset2bag_arg, {kLong, kInt}); + checkContiguous("embedding_bag", offset2bag_arg); + offset2bag_ = offset2bag; + } + + auto* grad_data = grad.const_data_ptr(); + auto grad_stride0 = grad.strides()[0]; + auto grad_stride1 = grad.strides()[1]; + + auto* weight_data = weight.const_data_ptr(); + auto weight_stride0 = weight.strides()[0]; + auto weight_stride1 = weight.strides()[1]; + + // explicitly capture all required variables to work around windows build + // TODO: fix this when windows can correctly capture variables in nested lambda + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "_embedding_bag_per_sample_weights_backward_cpu_template", + [&indices, &output, &offset2bag_, &num_samples, &embedding_features, + &grad_data, &grad_stride0, &grad_stride1, &weight_data, &weight_stride0, &weight_stride1, + &padding_idx] () { + auto* indices_data = indices.const_data_ptr(); + + // The following are contiguous + auto* output_data = output.data_ptr(); + auto* offset2bag_data = offset2bag_.const_data_ptr(); + + // XXX: 64 was arbitrarily chosen. There is probably a sweet spot for this number. + parallel_for(0, num_samples, 64, + [&embedding_features, &grad_data, &grad_stride0, &grad_stride1, &weight_data, &weight_stride0, + &weight_stride1, &offset2bag_data, &indices_data, &output_data, &padding_idx](index_t begin, index_t end) { + for (index_t sample_idx = begin; sample_idx < end; sample_idx++) { + auto bag_idx = offset2bag_data[sample_idx]; + auto embedding_idx = indices_data[sample_idx]; + + if (embedding_idx != static_cast(padding_idx)) { + output_data[sample_idx] = dot_impl( + embedding_features, grad_data + grad_stride0 * bag_idx, grad_stride1, + weight_data + weight_stride0 * embedding_idx, weight_stride1); + } + } + }); + }); + return output; +} + +Tensor _embedding_bag_per_sample_weights_backward_cpu( + const Tensor& grad, + const Tensor& weight, // NB: embedding table, not per_sample_weights + const Tensor& indices, + const Tensor& offsets, + const Tensor& offset2bag, + int64_t mode, + int64_t padding_idx) { + return AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + grad.scalar_type(), + "_embedding_bag_per_sample_weights_backward_cpu", + [&]() { + return _embedding_bag_per_sample_weights_backward_cpu_template< + scalar_t>( + grad, weight, indices, offsets, offset2bag, mode, padding_idx); + }); +} + +Tensor _embedding_bag_sparse_backward_symint( + const Tensor &grad_, const Tensor &indices, [[maybe_unused]] const Tensor &offsets, + const Tensor &offset2bag, const Tensor &bag_size_, SymInt num_weights, + bool scale_grad_by_freq, int64_t mode, const std::optional& per_sample_weights_opt, + int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + + // indices, offsets and offset2bag are assumed having correct dtypes and + // contiguous here due to the checks in _embedding_bag_backward above. + // Also see NOTE [ embedding_bag Native Functions ] in native_functions.yaml + // for more details. + + Tensor index_grad = grad_.index_select(0, offset2bag); + + index_grad = apply_bag_size_backward(mode, index_grad, offset2bag, bag_size_); + + if (per_sample_weights.defined()) { + AT_ASSERT(mode == EmbeddingBagMode::SUM); + index_grad.mul_(per_sample_weights.unsqueeze(1)); + } + return native::embedding_backward_symint(index_grad, indices, std::move(num_weights), padding_idx, + scale_grad_by_freq, true); +} +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/EmbeddingBag.h b/western_ai/usa/pytorch/aten/src/ATen/native/EmbeddingBag.h new file mode 100644 index 0000000000000000000000000000000000000000..ba3e42753db86ea5ac557e828ea5876ce3d79492 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/EmbeddingBag.h @@ -0,0 +1,154 @@ +#pragma once +#include +#include +#include + +#ifdef USE_FBGEMM +#include +#endif + +namespace at::native { + +enum class EmbeddingBagMode { + SUM = 0, + MEAN = 1, + MAX = 2, +}; + +[[maybe_unused]] static bool operator==(int64_t op1, EmbeddingBagMode op2) { + return op1 == static_cast(op2); +} + +[[maybe_unused]] static bool operator!=(int64_t op1, EmbeddingBagMode op2) { + return !(op1 == op2); +} + +void check_arguments( + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const std::optional& per_sample_weights, + bool include_last_offset); + +void make_bag_size_out( + Tensor& bag_size_out, + const Tensor& offsets, + const Tensor& indices, + const int64_t mode, + const bool include_last_offset, + const bool requires_grad); + +void make_max_indices_out( + Tensor& max_indices_out, + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const Tensor& bag_size, + const int64_t mode, + bool include_last_offset); + +void make_offset2bag_out( + Tensor& offset2bag, + Tensor& output, + const Tensor& weight, + const Tensor& indices, + const Tensor& offsets, + const int64_t mode, + const std::optional& per_sample_weights, + const int64_t padding_idx = -1); + +#ifdef USE_FBGEMM + +template +struct _CallbackAndBlockSize { + using TCallback = typename fbgemm::EmbeddingSpMDMKernelSignature::Type; + + int64_t blockSize = -1; + TCallback callback = nullptr; + + static TCallback generateCallback(int64_t block_size) { + return fbgemm::GenerateEmbeddingSpMDM( + block_size, + has_weight, + /* normalize_by_lengths */false, + /* prefetch */16, + /* is_weight_positional */false, + /* use_offsets */true); + } + + _CallbackAndBlockSize() = default; + + explicit _CallbackAndBlockSize(std::optional maybe_block_size) + : blockSize(maybe_block_size.value_or(-1)) + , callback(maybe_block_size.has_value() ? generateCallback(maybe_block_size.value()) : nullptr) + {} +}; + +template +struct _EmbeddingBagKernelCacheImpl : private StorageMixins... { + + _EmbeddingBagKernelCacheImpl() = default; + // use each of the mixins to store corresponding kernel and block size + explicit _EmbeddingBagKernelCacheImpl(std::optional maybe_block_size) + : StorageMixins(maybe_block_size)... + {} + + // this method is thread safe (call sites may call from different threads) + template + typename _CallbackAndBlockSize::TCallback + getCallback(int64_t block_size) const { + // if the cache doesn't store the kernel for the incoming block size + // (so it is different from the one stored in corresponding mixin) + // regenerate the kernel (not writing it into the cache so we avoid locks) + if (block_size != _CallbackAndBlockSize::blockSize) { + return _CallbackAndBlockSize::generateCallback(block_size); + } + // else retrieve the cached kernel from the corresponding mixin + return _CallbackAndBlockSize::callback; + } +}; + +// instantiate the cache with the list of storage mixins +// for each of the 8 _EmbeddingBagKernelCache* usages in the EmbeddingBag.cpp impl file +using _EmbeddingBagKernelCache = _EmbeddingBagKernelCacheImpl< + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize, + _CallbackAndBlockSize>; +#else +struct _EmbeddingBagKernelCache { + explicit _EmbeddingBagKernelCache(std::optional /* maybe_block_size */) {} +}; +#endif + +void _embedding_bag_cpu_impl_out(Tensor& output, Tensor& offset2bag, + Tensor& bag_size, Tensor* max_indices, + const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const int64_t mode = 0, + const std::optional& per_sample_weights = std::nullopt, + bool include_last_offset = false, + int64_t padding_idx = -1, + _EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr); + +void _embedding_bag_cpu_out( + at::Tensor& output, + at::Tensor& offset2bag, + at::Tensor& bag_size, + at::Tensor* p_max_indices, + const at::Tensor& weight, + const at::Tensor& indices, + const at::Tensor& offsets, + const bool scale_grad_by_freq, + const int64_t mode, + const bool sparse, + const std::optional& per_sample_weights, + const bool include_last_offset, + const std::optional& padding_idx, + _EmbeddingBagKernelCache* fbgemm_kernel_cache = nullptr); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Fill.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Fill.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ea529bf6f342cc50aedc55e974be5df293d61dc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Fill.cpp @@ -0,0 +1,164 @@ +// Functions that fill Tensors with constants. +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ fill ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Tensor& fill_out(Tensor& self, const Scalar& value) { + if (self.device() == at::kCPU && self.numel() == 1) { + return at::detail::scalar_fill(self, value); + } + auto iter = TensorIteratorConfig() + .set_check_mem_overlap(false) // Fill is idempotent, so overlap is okay + .check_all_same_dtype(false) + .add_output(self) + .resize_outputs(false) + .build(); + fill_stub(iter.device_type(), iter, value); + return self; +} + +static Tensor& fill_out_quantized(Tensor& self, const Scalar& value) { + at::Tensor out = at::ones(self.sizes()).to(kFloat) * value; + out = out.to(self.device()).to(self.suggest_memory_format()); + // Trust the `copy_` to handle the quantization and the boundary checks. + self.copy_(out); + return self; +} + +Tensor& fill_(Tensor& self, const Scalar& value) { + return fill_out(self, value); +} + +Tensor& fill_quantized_(Tensor& self, const Scalar& value) { + return fill_out_quantized(self, value); +} + +Tensor& fill_(Tensor& self, const Tensor& value) { + TORCH_CHECK(value.dim() == 0, "fill_ only supports 0-dimension value tensor but got tensor with ", value.dim(), " dimensions."); + if (self.device() != value.device()){ + return fill_out(self, value.item()); + } + // Check if value is a view of self and if it is we clone + // it to avoid overwriting self prematurely + if(self.is_alias_of(value)) { + self.copy_(value.clone()); + } else{ + self.copy_(value); + } + return self; +} + +Tensor& fill_quantized_(Tensor& self, const Tensor& value) { + TORCH_CHECK(value.dim() == 0, "fill_ only supports 0-dimension value tensor but got tensor with ", value.dim(), " dimensions."); + return fill_out_quantized(self, value.item()); +} + +Tensor& fill_meta_(Tensor& self, const Scalar& value) { + return self; +} + +Tensor& fill_meta_(Tensor& self, const Tensor& value) { + TORCH_CHECK(value.dim() == 0, "fill_ only supports 0-dimension value tensor but got tensor with ", value.dim(), " dimensions."); + return self; +} + +Tensor fill(const Tensor& self, const Scalar& value) { + return at::empty_like(self).fill_(value); +} + +Tensor fill(const Tensor& self, const Tensor& value) { + return at::empty_like(self).fill_(value); +} + +DEFINE_DISPATCH(fill_stub); + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ fill_diagonal ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tensor& fill_diagonal_(Tensor& self, const Scalar& fill_value, bool wrap) { + int64_t nDims = self.dim(); + TORCH_CHECK(nDims >= 2, "dimensions must larger than 1"); + + auto height = self.sym_size(0); + auto width = self.sym_size(1); + + if (nDims > 2) { + for (const auto i : c10::irange(1, nDims)) { + if (self.sym_size(i) != height) { + TORCH_CHECK(false, "all dimensions of input must be of equal length"); + } + } + } + + auto storage_offset = self.sym_storage_offset(); + auto size = std::min(height, width); + + int64_t stride = 0; + for (const auto i : c10::irange(nDims)) { + stride += self.stride(i); + } + std::vector strides{stride}; + std::vector sizes{size}; + + auto main_diag = self.as_strided_symint(sizes, strides, storage_offset); + main_diag.fill_(fill_value); + + if (wrap && nDims == 2 && height > width + 1) { + auto step = width + 1; + auto wrap_size = ((self.numel() + step - 1) / step) - size; + std::vector wrap_sizes{wrap_size}; + + auto offset = self.stride(0) * (width + 1); + + auto wrap_diag = self.as_strided_symint(wrap_sizes, strides, storage_offset + offset); + wrap_diag.fill_(fill_value); + } + + return self; +} + +static Tensor& zero_cpu_(Tensor &self, int64_t nelements) { + void* ptr = self.data_ptr(); + if (nullptr == ptr) { + return self.fill_(0); + } + auto size_bytes = nelements * self.dtype().itemsize(); + if (size_bytes > 0) { + std::memset(ptr, 0, size_bytes); + } + return self; +} + +Tensor& zero_(Tensor &self) { + int64_t nelements = c10::multiply_integers(self.sizes()); + if (self.device() == at::kCPU && + self.is_non_overlapping_and_dense() && + nelements < internal::GRAIN_SIZE) { + return zero_cpu_(self, nelements); + } + return self.fill_(0); +} + +Tensor& zero_meta_(Tensor& self) { + return self; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Fill.h b/western_ai/usa/pytorch/aten/src/ATen/native/Fill.h new file mode 100644 index 0000000000000000000000000000000000000000..26a67717b6383c24ca47ea49396ba04c98530beb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Fill.h @@ -0,0 +1,21 @@ +// Functions that fill Tensors with constants. Implementations are in Fill.cpp. + +#pragma once + +#include + +namespace c10 { +class Scalar; +} + +namespace at { +class Tensor; +struct TensorIterator; + +namespace native { + +DECLARE_DISPATCH(void(*)(TensorIterator&, const c10::Scalar&), fill_stub) + +Tensor& fill_out(Tensor& self, const Scalar& value); + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ForeachOpsKernels.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ForeachOpsKernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..23552617306871b251e8175fc13c16d3116f1e77 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ForeachOpsKernels.cpp @@ -0,0 +1,575 @@ +#include +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +#define FOREACH_BINARY_OP_TENSOR(OP) \ + void foreach_tensor_##OP##_tensor_kernel_slow_( \ + TensorList tensors, const Tensor& scalar) { \ + TORCH_CHECK( \ + scalar.dim() == 0 && scalar.numel() == 1, \ + "scalar tensor expected to be 0 dim but it has ", \ + scalar.dim(), \ + " dimensions and ", \ + scalar.numel(), \ + " elements."); \ + check_foreach_api_restrictions(tensors); \ + \ + for (auto& t : tensors) { \ + t.OP##_(scalar); \ + } \ + } \ + \ + std::vector foreach_tensor_##OP##_tensor_kernel_slow( \ + TensorList tensors, const Tensor& scalar) { \ + TORCH_CHECK( \ + scalar.dim() == 0 && scalar.numel() == 1, \ + "scalar tensor expected to be 0 dim but it has ", \ + scalar.dim(), \ + " dimensions and ", \ + scalar.numel(), \ + " elements."); \ + check_foreach_api_restrictions(tensors); \ + \ + std::vector result; \ + result.reserve(tensors.size()); \ + for (const auto& t : tensors) { \ + result.emplace_back(t.OP(scalar)); \ + } \ + \ + return result; \ + } + +#define FOREACH_BINARY_OP_TENSOR_ALPHA(OP) \ + void foreach_tensor_##OP##_tensor_kernel_slow_( \ + TensorList tensors, const Tensor& scalar, const Scalar& alpha) { \ + TORCH_CHECK( \ + scalar.dim() == 0 && scalar.numel() == 1, \ + "scalar tensor expected to be 0 dim but it has ", \ + scalar.dim(), \ + " dimensions and ", \ + scalar.numel(), \ + " elements."); \ + check_foreach_api_restrictions(tensors); \ + \ + for (auto& t : tensors) { \ + t.OP##_(scalar, alpha); \ + } \ + } \ + \ + std::vector foreach_tensor_##OP##_tensor_kernel_slow( \ + TensorList tensors, const Tensor& scalar, const Scalar& alpha) { \ + TORCH_CHECK( \ + scalar.dim() == 0 && scalar.numel() == 1, \ + "scalar tensor expected to be 0 dim but it has ", \ + scalar.dim(), \ + " dimensions and ", \ + scalar.numel(), \ + " elements."); \ + check_foreach_api_restrictions(tensors); \ + \ + std::vector result; \ + result.reserve(tensors.size()); \ + for (const auto& t : tensors) { \ + result.emplace_back(t.OP(scalar, alpha)); \ + } \ + \ + return result; \ + } + +#define FOREACH_BINARY_OP_SCALAR(OP) \ + void foreach_tensor_##OP##_scalar_kernel_slow_( \ + TensorList tensors, const Scalar& scalar) { \ + check_foreach_api_restrictions(tensors); \ + \ + for (auto& t : tensors) { \ + t.OP##_(scalar); \ + } \ + } \ + \ + std::vector foreach_tensor_##OP##_scalar_kernel_slow( \ + TensorList tensors, const Scalar& scalar) { \ + check_foreach_api_restrictions(tensors); \ + \ + std::vector result; \ + result.reserve(tensors.size()); \ + for (const auto& t : tensors) { \ + result.emplace_back(t.OP(scalar)); \ + } \ + \ + return result; \ + } + +#define FOREACH_BINARY_OP_SCALARLIST(OP) \ + void foreach_tensor_##OP##_scalarlist_kernel_slow_( \ + TensorList tensors, at::ArrayRef scalars) { \ + check_foreach_api_restrictions(tensors, scalars); \ + \ + for (const auto i : c10::irange(tensors.size())) { \ + tensors[i].OP##_(scalars[i]); \ + } \ + } \ + \ + std::vector foreach_tensor_##OP##_scalarlist_kernel_slow( \ + TensorList tensors, at::ArrayRef scalars) { \ + check_foreach_api_restrictions(tensors, scalars); \ + std::vector result; \ + result.reserve(tensors.size()); \ + for (const auto i : c10::irange(tensors.size())) { \ + result.emplace_back(tensors[i].OP(scalars[i])); \ + } \ + \ + return result; \ + } + +#define FOREACH_BINARY_OP_LIST(OP) \ + std::vector foreach_tensor_##OP##_list_kernel_slow( \ + TensorList tensors1, TensorList tensors2) { \ + check_foreach_api_restrictions(tensors1, tensors2); \ + \ + std::vector result; \ + result.reserve(tensors1.size()); \ + for (const auto i : c10::irange(tensors1.size())) { \ + result.emplace_back(tensors1[i].OP(tensors2[i])); \ + } \ + \ + return result; \ + } \ + \ + void foreach_tensor_##OP##_list_kernel_slow_( \ + TensorList tensors1, TensorList tensors2) { \ + check_foreach_api_restrictions(tensors1, tensors2); \ + \ + for (const auto i : c10::irange(tensors1.size())) { \ + tensors1[i].OP##_(tensors2[i]); \ + } \ + } + +#define FOREACH_BINARY_OP_LIST_ALPHA(OP) \ + std::vector foreach_tensor_##OP##_list_kernel_slow( \ + TensorList tensors1, TensorList tensors2, const Scalar& alpha) { \ + check_foreach_api_restrictions(tensors1, tensors2); \ + \ + std::vector result; \ + result.reserve(tensors1.size()); \ + for (const auto i : c10::irange(tensors1.size())) { \ + result.emplace_back(tensors1[i].OP(tensors2[i], alpha)); \ + } \ + \ + return result; \ + } \ + \ + void foreach_tensor_##OP##_list_kernel_slow_( \ + TensorList tensors1, TensorList tensors2, const Scalar& alpha) { \ + check_foreach_api_restrictions(tensors1, tensors2); \ + \ + for (const auto i : c10::irange(tensors1.size())) { \ + tensors1[i].OP##_(tensors2[i], alpha); \ + } \ + } + +#define FOREACH_UNARY_OP(OP) \ + std::vector foreach_tensor_##OP##_slow(TensorList tensors) { \ + check_foreach_api_restrictions(tensors); \ + \ + std::vector result; \ + result.reserve(tensors.size()); \ + for (const auto& t : tensors) { \ + result.emplace_back(t.OP()); \ + } \ + \ + return result; \ + } \ + \ + void foreach_tensor_##OP##_slow_(TensorList tensors) { \ + check_foreach_api_restrictions(tensors); \ + \ + for (auto& t : tensors) { \ + t.OP##_(); \ + } \ + } + +#define FOREACH_POINTWISE_OP_SCALAR(OP) \ + std::vector foreach_tensor_##OP##_scalar_slow( \ + TensorList input, \ + TensorList tensors1, \ + TensorList tensors2, \ + const Scalar& scalar) { \ + check_foreach_api_restrictions(input, tensors1, tensors2); \ + \ + std::vector result; \ + result.reserve(input.size()); \ + for (const auto i : c10::irange(input.size())) { \ + result.emplace_back(input[i].OP(tensors1[i], tensors2[i], scalar)); \ + } \ + \ + return result; \ + } \ + \ + void foreach_tensor_##OP##_scalar_slow_( \ + TensorList input, \ + TensorList tensors1, \ + TensorList tensors2, \ + const Scalar& scalar) { \ + check_foreach_api_restrictions(input, tensors1, tensors2); \ + \ + for (const auto i : c10::irange(input.size())) { \ + input[i].OP##_(tensors1[i], tensors2[i], scalar); \ + } \ + } + +#define FOREACH_POINTWISE_OP_SCALARLIST(OP) \ + std::vector foreach_tensor_##OP##_scalarlist_slow( \ + TensorList input, \ + TensorList tensors1, \ + TensorList tensors2, \ + at::ArrayRef scalars) { \ + check_foreach_api_restrictions(input, tensors1, tensors2, scalars); \ + \ + std::vector result; \ + result.reserve(input.size()); \ + for (const auto i : c10::irange(input.size())) { \ + result.emplace_back(input[i].OP(tensors1[i], tensors2[i], scalars[i])); \ + } \ + \ + return result; \ + } \ + \ + void foreach_tensor_##OP##_scalarlist_slow_( \ + TensorList input, \ + TensorList tensors1, \ + TensorList tensors2, \ + at::ArrayRef scalars) { \ + check_foreach_api_restrictions(input, tensors1, tensors2, scalars); \ + \ + for (const auto i : c10::irange(input.size())) { \ + input[i].OP##_(tensors1[i], tensors2[i], scalars[i]); \ + } \ + } + +#define FOREACH_POINTWISE_OP_TENSOR(OP) \ + std::vector foreach_tensor_##OP##_tensor_slow( \ + TensorList input, \ + TensorList tensors1, \ + TensorList tensors2, \ + const Tensor& scalars_) { \ + auto scalars = convert_tensor_to_scalar_list(scalars_, input.size()); \ + check_foreach_api_restrictions(input, tensors1, tensors2, scalars); \ + return foreach_tensor_##OP##_scalarlist_slow( \ + input, tensors1, tensors2, scalars); \ + } \ + \ + void foreach_tensor_##OP##_tensor_slow_( \ + TensorList input, \ + TensorList tensors1, \ + TensorList tensors2, \ + const Tensor& scalars_) { \ + auto scalars = convert_tensor_to_scalar_list(scalars_, input.size()); \ + check_foreach_api_restrictions(input, tensors1, tensors2, scalars); \ + foreach_tensor_##OP##_scalarlist_slow_( \ + input, tensors1, tensors2, scalars); \ + } + +FOREACH_BINARY_OP_LIST_ALPHA(add) +FOREACH_BINARY_OP_LIST_ALPHA(sub) +FOREACH_BINARY_OP_LIST_ALPHA(lerp) + +FOREACH_BINARY_OP_TENSOR_ALPHA(add) +FOREACH_BINARY_OP_TENSOR(mul) +FOREACH_BINARY_OP_TENSOR(div) + +FOREACH_BINARY_OP_SCALAR(add) +FOREACH_BINARY_OP_SCALAR(sub) +FOREACH_BINARY_OP_SCALAR(mul) +FOREACH_BINARY_OP_SCALAR(div) +FOREACH_BINARY_OP_SCALAR(clamp_min) +FOREACH_BINARY_OP_SCALAR(clamp_max) +FOREACH_BINARY_OP_SCALAR(pow) + +FOREACH_BINARY_OP_SCALARLIST(add) +FOREACH_BINARY_OP_SCALARLIST(sub) +FOREACH_BINARY_OP_SCALARLIST(mul) +FOREACH_BINARY_OP_SCALARLIST(div) +FOREACH_BINARY_OP_SCALARLIST(clamp_min) +FOREACH_BINARY_OP_SCALARLIST(clamp_max) +FOREACH_BINARY_OP_SCALARLIST(pow) + +FOREACH_BINARY_OP_LIST(mul) +FOREACH_BINARY_OP_LIST(div) +FOREACH_BINARY_OP_LIST(clamp_min) +FOREACH_BINARY_OP_LIST(clamp_max) +FOREACH_BINARY_OP_LIST(pow) + +// _foreach_clone +std::vector foreach_tensor_clone_slow( + TensorList self, + std::optional memory_format) { + check_foreach_api_restrictions(self); + + std::vector ret{}; + ret.reserve(self.size()); + for (const auto& t : self) { + ret.emplace_back(t.clone(memory_format)); + } + return ret; +} + +// _foreach_copy_ +void foreach_tensor_copy_list_kernel_slow_( + TensorList self, + TensorList src, + const bool non_blocking) { + check_foreach_api_restrictions(self, src); + + for (const auto i : c10::irange(self.size())) { + self[i].copy_(src[i], non_blocking); + } +} + +FOREACH_UNARY_OP(sqrt) +FOREACH_UNARY_OP(exp) +FOREACH_UNARY_OP(abs) +FOREACH_UNARY_OP(acos) +FOREACH_UNARY_OP(asin) +FOREACH_UNARY_OP(atan) +FOREACH_UNARY_OP(ceil) +FOREACH_UNARY_OP(cos) +FOREACH_UNARY_OP(cosh) +FOREACH_UNARY_OP(erf) +FOREACH_UNARY_OP(erfc) +FOREACH_UNARY_OP(expm1) +FOREACH_UNARY_OP(floor) +FOREACH_UNARY_OP(log) +FOREACH_UNARY_OP(log10) +FOREACH_UNARY_OP(log1p) +FOREACH_UNARY_OP(log2) +FOREACH_UNARY_OP(neg) +FOREACH_UNARY_OP(tan) +FOREACH_UNARY_OP(tanh) +FOREACH_UNARY_OP(sin) +FOREACH_UNARY_OP(sinh) +FOREACH_UNARY_OP(round) +FOREACH_UNARY_OP(rsqrt) +FOREACH_UNARY_OP(lgamma) +FOREACH_UNARY_OP(frac) +FOREACH_UNARY_OP(trunc) +FOREACH_UNARY_OP(reciprocal) +FOREACH_UNARY_OP(sigmoid) +FOREACH_UNARY_OP(sign) + +FOREACH_POINTWISE_OP_SCALAR(addcdiv) +FOREACH_POINTWISE_OP_SCALAR(addcmul) + +FOREACH_POINTWISE_OP_SCALARLIST(addcdiv) +FOREACH_POINTWISE_OP_SCALARLIST(addcmul) + +FOREACH_POINTWISE_OP_TENSOR(addcdiv) +FOREACH_POINTWISE_OP_TENSOR(addcmul) + +std::vector foreach_tensor_ternary_lerp_slow( + TensorList tensors1, + TensorList tensors2, + TensorList tensors3) { + check_foreach_api_restrictions(tensors1, tensors2, tensors3); + std::vector result; + result.reserve(tensors1.size()); + for (const auto i : c10::irange(tensors1.size())) { + result.emplace_back(tensors1[i].lerp(tensors2[i], tensors3[i])); + } + return result; +} + +void foreach_tensor_ternary_lerp_slow_( + TensorList tensors1, + TensorList tensors2, + TensorList tensors3) { + check_foreach_api_restrictions(tensors1, tensors2, tensors3); + for (const auto i : c10::irange(tensors1.size())) { + tensors1[i].lerp_(tensors2[i], tensors3[i]); + } +} + +std::vector foreach_tensor_lerp_scalarlist_kernel_slow( + TensorList tensors1, + TensorList tensors2, + at::ArrayRef scalars) { + check_foreach_api_restrictions(tensors1, tensors2, scalars); + std::vector result; + result.reserve(tensors1.size()); + for (const auto i : c10::irange(tensors1.size())) { + result.emplace_back(tensors1[i].lerp(tensors2[i], scalars[i])); + } + return result; +} + +void foreach_tensor_lerp_scalarlist_kernel_slow_( + TensorList tensors1, + TensorList tensors2, + at::ArrayRef scalars) { + check_foreach_api_restrictions(tensors1, tensors2, scalars); + for (const auto i : c10::irange(tensors1.size())) { + tensors1[i].lerp_(tensors2[i], scalars[i]); + } +} + +void foreach_tensor_zero_slow_(TensorList tensors) { + check_foreach_api_restrictions(tensors); + + for (auto& t : tensors) { + t.zero_(); + } +} + +std::vector foreach_tensor_norm_slow( + TensorList tensors, + const Scalar& ord, + std::optional dtype) { + check_foreach_api_restrictions(tensors); + + // Extract ord value to check for infinity + const auto p = [&]() -> double { + if (ord.isIntegral(false)) { + return ord.to(); + } else if (ord.isFloatingPoint()) { + return ord.to(); + } else { + TORCH_CHECK( + false, "foreach_tensor_norm_slow expects ord to be integer or float"); + } + }(); + + std::vector result; + result.reserve(tensors.size()); + for (const auto& t : tensors) { + // If the tensor is empty and norm == infinity, we cannot compute the norm + // because the operation does not have an identity + if (p == std::numeric_limits::infinity()) { + TORCH_SYM_CHECK( + t.sym_numel().sym_gt(0), + "_foreach_norm cannot compute the infinity norm on an empty tensor because the operation does not have an identity"); + } + result.emplace_back(at::linalg_vector_norm(t, ord, {}, false, dtype)); + } + return result; +} + +std::vector foreach_tensor_powsum_slow( + TensorList tensors, + const Scalar& ord, + std::optional dtype) { + check_foreach_api_restrictions(tensors); + std::vector result; + result.reserve(tensors.size()); + for (const auto& t : tensors) { + result.emplace_back(at::linalg__powsum(t, ord, {}, false, dtype)); + } + return result; +} + +std::vector foreach_tensor_max_slow(TensorList tensors) { + check_foreach_api_restrictions(tensors); + std::vector result; + result.reserve(tensors.size()); + for (const auto& t : tensors) { + TORCH_CHECK( + t.numel() > 0, + "_foreach_max cannot compute the maximum of an empty tensor; max over zero elements is undefined."); + result.emplace_back(at::max(t)); + } + return result; +} + +std::vector foreach_scalar_pow_list_kernel_slow( + const Scalar& self, + TensorList exponent) { + check_foreach_api_restrictions(exponent); + std::vector result; + result.reserve(exponent.size()); + for (const auto& t : exponent) { + result.emplace_back(at::pow(self, t)); + } + return result; +} + +std::vector _foreach_mm(TensorList self, TensorList mat2) { + TORCH_CHECK(self.size() > 0, "_foreach_mm requires non-empty tensor lists"); + TORCH_CHECK( + self.size() == mat2.size(), + "_foreach_mm: self and mat2 must have the same number of tensors"); + std::vector result; + result.reserve(self.size()); + for (const auto i : c10::irange(self.size())) { + result.emplace_back(at::mm(self[i], mat2[i])); + } + return result; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ForeachUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/ForeachUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..5cdbe2effca9babc49b1b37896f7e5bfe4fd4f90 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ForeachUtils.h @@ -0,0 +1,390 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include +#include + +namespace at::native { +namespace { +// Check if tensor list has either a boolean tensor or a integer tensor +inline bool has_integral_tensor(TensorList tensors, const bool includeBool) { + return std::any_of( + tensors.begin(), tensors.end(), [includeBool](const auto& t) { + return at::isIntegralType(t.scalar_type(), includeBool); + }); +} +// check if tensor list has bool tensors +inline bool has_bool_tensor(TensorList tensors) { + return std::any_of(tensors.begin(), tensors.end(), [](const auto& t) -> bool { + return t.scalar_type() == ScalarType::Bool; + }); +} + +// Check foreach API restrictions +// - Tensor lists must be non-empty. +// - All TensorLists and ScalarLists must have the same number of elements. +// - Corresponding tensors must have the same size. +inline void check_foreach_api_restrictions(TensorList tensors) { + TORCH_CHECK(!tensors.empty(), "Tensor list must have at least one tensor."); +} + +inline void check_foreach_api_restrictions( + TensorList tensors, + ArrayRef scalars) { + check_foreach_api_restrictions(tensors); + TORCH_CHECK( + tensors.size() == scalars.size(), + "Tensor list must have same number of elements as scalar list."); +} + +inline void check_foreach_api_restrictions( + TensorList tensors1, + TensorList tensors2) { + check_foreach_api_restrictions(tensors1); + check_foreach_api_restrictions(tensors2); + TORCH_CHECK( + tensors1.size() == tensors2.size(), + "Tensor lists must have the same number of tensors, got ", + tensors1.size(), + " and ", + tensors2.size()); +} + +inline void check_foreach_api_restrictions( + TensorList tensors1, + TensorList tensors2, + TensorList tensors3) { + check_foreach_api_restrictions(tensors1, tensors2); + check_foreach_api_restrictions(tensors1, tensors3); +} + +inline void check_foreach_api_restrictions( + TensorList tensors1, + TensorList tensors2, + TensorList tensors3, + ArrayRef scalars) { + check_foreach_api_restrictions(tensors1, tensors2, tensors3); + check_foreach_api_restrictions(tensors1, scalars); +} + +inline void check_foreach_api_restrictions( + TensorList tensors1, + TensorList tensors2, + ArrayRef scalars) { + check_foreach_api_restrictions(tensors1, tensors2); + check_foreach_api_restrictions(tensors1, scalars); +} + +// Helper function called in check_fast_path_restrictions to check whether all +// corresponding tensors (aligning in index across the tensorLists) share the +// same device and dtype. +inline bool _check_tensors_share_device_and_dtype( + ArrayRef tensorLists, + const bool skip_cross_list_dtype_check = false) { + const auto expected_dtype = tensorLists[0][0].dtype(); + const auto expected_device = tensorLists[0][0].device(); + + return std::all_of( + tensorLists.cbegin(), + tensorLists.cend(), + [&](const TensorList& tensorList) { + if (tensorList.empty()) { + return true; + } + const auto list_dtype = tensorList[0].dtype(); + return std::all_of( + tensorList.cbegin(), tensorList.cend(), [&](const Tensor& tensor) { + return tensor.device() == expected_device && + tensor.layout() == at::kStrided && + tensor.is_non_overlapping_and_dense() && + tensor.dtype() == list_dtype && + (skip_cross_list_dtype_check || + tensor.dtype() == expected_dtype); + }); + }); +} + +// Helper function called in check_fast_path_restrictions to check if +// corresponding tensors in tensor lists have the same sizes and strides. +inline bool _check_tensors_share_sizes_and_strides( + ArrayRef tensorLists) { + auto is_diff_stride = [](const IntArrayRef& size, + const IntArrayRef& left_stride, + const IntArrayRef& right_stride) -> bool { + const size_t size_size = size.size(); + for (const auto dim : c10::irange(size_size)) { + if (size[dim] == 1) + continue; + if (left_stride[dim] != right_stride[dim]) { + return true; + } + } + return false; + }; + for (const auto i : c10::irange(1, tensorLists.size())) { + for (const auto j : c10::irange(tensorLists[0].size())) { + if (tensorLists[0][j].sizes() != tensorLists[i][j].sizes() || + is_diff_stride( + tensorLists[0][j].sizes(), + tensorLists[0][j].strides(), + tensorLists[i][j].strides())) { + return false; + } + } + } + + return true; +} + +// Helper function called in check_fast_path_restrictions to check whether +// all tensors type promote properly with the scalars in scalarList. This +// function assumes that _check_tensors_share_device_and_dtype has already been +// called so that all corresponding tensors in tensorLists have the same dtype. +// Then, it is sufficient to check the type promotion with just one tensorList. +inline bool _check_tensors_do_type_promotion_with_scalars( + TensorList tensorList, + ArrayRef scalarList = {}, + bool does_op_promote_integer_inputs_to_float = false) { + for (const auto i : c10::irange(tensorList.size())) { + // For division, integer inputs will result in float. + if (does_op_promote_integer_inputs_to_float && + at::isIntegralType(tensorList[i].scalar_type(), /*includeBool*/ true)) { + return false; + } + if (!scalarList.empty()) { + const auto& scalar = + scalarList.size() == 1 ? scalarList[0] : scalarList[i]; + const auto& tensor = tensorList[i]; + // note(mkozuki): This check might be responsible for + // `_foreach_add(bool_tensors, bool_tensors)` being pushed to slow path. + if (tensor.scalar_type() != at::native::result_type(scalar, tensor)) { + return false; + } + } + } + + return true; +} + +// To go via 'fast' path, several conditions must be satisfied +// - All tensors in all lists must have the same dtype. +// - All tensors must be on the same device +// - All tensors must have strided layout +// - All tensors must be non-overlapping and dense +// - Resulting tensor must have the same dtype as the input one + +// [note: what's ``does_op_promote_integer_inputs_to_float=true``?] +// ``does_op_promote_integer_inputs_to_float=true`` means that the result of +// the op will be float even if inputs are integer or boolean, which +// currently fast path does not support. In short, this flag, when +// turned on, gatekeeps the op from going down the fastpath. + +// Please, make sure to call check_foreach_api_restrictions before calling this +// method. There is a set of preconditions that have to be satisfied. +inline bool check_fast_path_restrictions( + ArrayRef tensorLists, + ArrayRef scalarList = {}, + bool does_op_promote_integer_inputs_to_float = false, + bool skip_cross_list_dtype_check = false) { + return _check_tensors_share_device_and_dtype( + tensorLists, skip_cross_list_dtype_check) && + _check_tensors_share_sizes_and_strides(tensorLists) && + _check_tensors_do_type_promotion_with_scalars( + tensorLists[0], + scalarList, + does_op_promote_integer_inputs_to_float); +} + +inline std::vector convert_tensor_to_scalar_list( + const Tensor& scalarList_, + int64_t expect_length) { + std::vector scalarList; + TORCH_CHECK( + scalarList_.device() == c10::kCPU, + "Expected scalars to be on CPU, got ", + scalarList_.device(), + " instead."); + TORCH_CHECK( + scalarList_.is_contiguous(), "Expected scalars to be contiguous."); + TORCH_CHECK( + scalarList_.dim() == 1, + "Expected packed scalar Tensor to be of dimension 1. Got ", + scalarList_.dim(), + " instead."); + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5( + kComplexHalf, + kBComplex32, + kHalf, + kBool, + kBFloat16, + scalarList_.scalar_type(), + "convert_tensor_to_scalar_list", + [&]() { + const scalar_t* scalar_data = scalarList_.const_data_ptr(); + TORCH_CHECK( + (expect_length == scalarList_.size(0)), + "Expected length of scalars to match input of length ", + expect_length, + " but got ", + scalarList_.size(0), + " instead."); + scalarList.reserve(scalarList_.size(0)); + for (int64_t i = 0; i < scalarList_.size(0); i++) { + scalarList.emplace_back(scalar_data[i]); + } + }); + return scalarList; +} + +// see: [note: what's ``does_op_promote_integer_inputs_to_float=true``?] +inline bool can_use_fast_route( + ArrayRef tensorLists, + ArrayRef scalarList = {}, + bool does_op_promote_integer_inputs_to_float = false) { + return check_fast_path_restrictions( + tensorLists, scalarList, does_op_promote_integer_inputs_to_float); +} + +// see: [note: what's ``does_op_promote_integer_inputs_to_float=true``?] +inline bool can_use_fast_route( + TensorList tensors1, + TensorList tensors2, + bool does_op_promote_integer_inputs_to_float = false) { + return can_use_fast_route( + {tensors1, tensors2}, {}, does_op_promote_integer_inputs_to_float); +} + +using DeviceDtypeKey = std::pair; +using IndicesT = std::vector; +using nested_optional_tensorvec_t = + std::vector>>; +using TensorsAndIndicesT = std::pair; +using FlatMap = std::unordered_map< + DeviceDtypeKey, + TensorsAndIndicesT, + ParamsHash>; + +inline FlatMap _group_tensors_by_first_tensors_device_and_dtype( + const nested_optional_tensorvec_t& nested_tensorlist, + const bool with_indices) { + FlatMap grouped_tensors_with_indices; + + TORCH_CHECK(!nested_tensorlist.empty()); + TORCH_CHECK(!nested_tensorlist[0].empty()); + const auto num_lists = nested_tensorlist.size(); + const auto num_tensors = nested_tensorlist[0].size(); + + TORCH_CHECK(std::all_of( + nested_tensorlist.cbegin(), + nested_tensorlist.cend(), + [&](const auto& tensorlist) -> bool { + // note(crcrpar): Allow empty tensorlists following + // ref: + // https://github.com/pytorch/pytorch/blob/85885301fd3c6adb8b9dc3cf7afadf6945566684/torch/utils/_foreach_utils.py#L21-L24 + return tensorlist.size() == num_tensors || tensorlist.size() == 0; + })); + + for (const auto& tensor_index : c10::irange(num_tensors)) { + const auto key = [&]() -> DeviceDtypeKey { + const auto t = nested_tensorlist[0][tensor_index]; + TORCH_CHECK( + t.has_value(), + "Tensors of the first list of nested Tensor lists are supposed to be defined but ", + "the ", + tensor_index, + "-th Tensor is not."); + return {t->device(), t->scalar_type()}; + }(); + TORCH_CHECK( + std::all_of( + nested_tensorlist.cbegin(), + nested_tensorlist.cend(), + [&](const auto& tensorlist) -> bool { + if (tensorlist.size() == 0) { + return true; + } + const auto& tensor = tensorlist[tensor_index]; + // note(crcrpar): Currently the scope of this function is + // optimizers so there could be `state_steps` and other scalars + // whose elements are float tensors no matter what the parameter's + // dtype is. + if (!tensor.has_value()) { + return true; + } else { + const auto s = tensor->scalar_type(); + const auto d = tensor->device(); + // Note: `step` or `state_step` is float32 by default. + // BFloat16 is allowed here for mixed-precision optimizer + // states (e.g. fp32 params with bf16 exp_avg/exp_avg_sq). + // Currently only BFloat16 is permitted because it is the + // only low-precision state dtype validated end-to-end in + // large-scale training (e.g. DeepSeek-V3 671B). + // TBD: make the set of allowed extra dtypes configurable + // per optimizer so this function stays dtype-agnostic. + if (key.first == d) { + return key.second == s || s == at::ScalarType::Float || + s == at::ScalarType::Double || + s == at::ScalarType::BFloat16; + } else if (d.is_cpu()) { + // note(crcrpar): There are some test cases (e.g. + // TestOptim::test_adam) where state_steps are on CPU and the + // others are on CUDA. Currently a state_step Tensor has the + // dtype of float. + return s == at::ScalarType::Float || + s == at::ScalarType::Double; + } else { + return false; + } + } + }), + "Tensors of the same index must be on the same device and the same dtype " + "except `step` tensors that can be CPU and float32/64, and optimizer " + "states that can be bfloat16 for mixed-precision training"); + auto [it, inserted] = grouped_tensors_with_indices.try_emplace(key); + auto& tensors_and_indices = it->second; + if (inserted) { + auto& nested_tensorvec = tensors_and_indices.first; + nested_tensorvec.reserve(num_lists); + for (const auto& i : c10::irange(num_lists)) { + std::vector> tensors; + if (!nested_tensorlist[i].empty()) { + // NB: num_tensors is the max possible length for any of the inner + // lists of tensor references. Reserving the max trades memory for + // perf. This should not have significant impact. + tensors.reserve(num_tensors); + } + nested_tensorvec.emplace_back(std::move(tensors)); + } + if (with_indices) { + tensors_and_indices.second.reserve(num_tensors); + } + } + for (const auto& list_index : c10::irange(num_lists)) { + if (!nested_tensorlist[list_index].empty()) { + tensors_and_indices.first[list_index].emplace_back( + nested_tensorlist[list_index][tensor_index]); + } + } + if (with_indices) { + tensors_and_indices.second.emplace_back(tensor_index); + } + } + + return grouped_tensors_with_indices; +} + +} // namespace +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPool2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPool2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12e295cbdba0686ab64d36ecbacc7dc48f72c13d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPool2d.cpp @@ -0,0 +1,396 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at { + +namespace meta { +TORCH_META_FUNC(fractional_max_pool2d) ( + const at::Tensor& input, + IntArrayRef pool_size, + IntArrayRef output_size, + const at::Tensor& randomSamples +) { + TORCH_CHECK( + pool_size.size() == 2, + "fractional_max_pool2d: kernel_size must either be a single Int or tuple of Ints") + TORCH_CHECK( + output_size.size() == 2, + "fractional_max_pool2d: output_size must either be a single Int or tuple of Ints") + int64_t numBatch = 1; + int64_t planeDim = 0; + int64_t heightDim = 1; + int64_t widthDim = 2; + int64_t outputH = output_size[0]; + int64_t outputW = output_size[1]; + int64_t poolSizeH = pool_size[0]; + int64_t poolSizeW = pool_size[1]; + + int64_t ndims = input.ndimension(); + TORCH_CHECK(ndims == 3 || ndims == 4, + "fractional_max_pool2d(): Expected 3D or 4D tensor, but got: ", input.sizes()); + for (const auto i : c10::irange(1, ndims)) { + TORCH_CHECK(input.size(i) > 0, + "fractional_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, but got", + input.sizes(), " with dimension ", i, " being empty."); + } + + + if (ndims == 4) { + numBatch = input.size(0); + planeDim++; + heightDim++; + widthDim++; + } + + /* sizes */ + int64_t numPlanes = input.size(planeDim); + int64_t inputH = input.size(heightDim); + auto inputW = input.size(widthDim); + + TORCH_CHECK(outputH + poolSizeH - 1 <= inputH, + "fractional_max_pool2d(): pool height ", poolSizeH, + " too large relative to input height ", inputH); + TORCH_CHECK(outputW + poolSizeW - 1 <= inputW, + "fractional_max_pool2d(): pool width ", poolSizeW, + " too large relative to input width ", inputW); + + if (ndims == 3) { + set_output_raw_strided(0, {numPlanes, outputH, outputW}, {}, input.options()); + /* indices will contain the locations for each output point */ + set_output_raw_strided(1, {numPlanes, outputH, outputW}, {}, input.options().dtype(kLong)); + } else { + set_output_raw_strided(0, {numBatch, numPlanes, outputH, outputW}, {}, input.options()); + /* indices will contain the locations for each output point */ + set_output_raw_strided(1, {numBatch, numPlanes, outputH, outputW}, {}, input.options().dtype(kLong)); + } +} + +TORCH_META_FUNC(fractional_max_pool2d_backward)( + const at::Tensor& gradOutput_, + const at::Tensor& input, + IntArrayRef pool_size /* unused */, + IntArrayRef output_size, + const at::Tensor& indices) { + + int64_t numBatch = 1; + int planeDim = 0; + int heightDim = 1; + int widthDim = 2; + + auto outputH = output_size[0]; + auto outputW = output_size[1]; + + auto ndims = input.ndimension(); + if (ndims == 4) { + numBatch = input.size(0); + planeDim = 1; + heightDim++; + widthDim++; + } + + /* sizes */ + auto numPlanes = input.size(planeDim); + auto inputH = input.size(heightDim); + auto inputW = input.size(widthDim); + + /* get contiguous gradOutput */ + auto gradOutput = gradOutput_.contiguous(); + + auto expectedOutputShape = IntArrayRef(input.sizes().data(), ndims - 2).vec(); + expectedOutputShape.push_back(outputH); + expectedOutputShape.push_back(outputW); + TORCH_CHECK(gradOutput.sizes().equals(expectedOutputShape), + "fractional_max_pool2d_backward(): gradOutput sizes unexpected"); + TORCH_CHECK(indices.sizes().equals(expectedOutputShape), + "fractional_max_pool2d_backward(): indices sizes unexpected"); + + /* resize */ + if (ndims == 3) { + set_output_raw_strided(0, {numPlanes, inputH, inputW}, {}, input.options()); + } else { + set_output_raw_strided(0, {numBatch, numPlanes, inputH, inputW}, {}, input.options()); + } +} +} // namespace meta + +namespace native { +namespace { + +template +void fractional_max_pool2d_out_single_batch_frame( + const scalar_t* input, + scalar_t* output, + int64_t* indices, + const scalar_t* randomSamples, + int numPlanes, + int inputW, int inputH, + int outputW, int outputH, + int poolSizeW, int poolSizeH) { + at::parallel_for(0, numPlanes, 0, [&](int64_t start, int64_t end) { + for (const auto plane : c10::irange(start, end)) { + /* each plane contains 2 random samples, one for W and one for H */ + const scalar_t* randomSamplesForPlane = randomSamples + plane * 2; + + /* Generate interval sequence */ + auto sequenceW = generate_intervals( + randomSamplesForPlane[0], inputW, outputW, poolSizeW); + auto sequenceH = generate_intervals( + randomSamplesForPlane[1], inputH, outputH, poolSizeH); + + /* loop over output */ + const scalar_t* inputForPlane = input + plane * inputW * inputH; + scalar_t* outputForPlane = output + plane * outputW * outputH; + int64_t* indicesForPlane = indices + plane * outputW * outputH; + + for (int h = 0; h < outputH; ++h) { + int inputHStart = sequenceH[h]; + + for (int w = 0; w < outputW; ++w) { + int inputWStart = sequenceW[w]; + + int h2 = inputHStart, w2 = inputWStart; + scalar_t maxVal = -std::numeric_limits::infinity(); + int64_t maxIndex = h2 * inputW + w2; + + for (h2 = inputHStart; h2 < inputHStart + poolSizeH; ++h2) { + for (w2 = inputWStart; w2 < inputWStart + poolSizeW; ++w2) { + AT_ASSERT(h2 >= 0 && h2 < inputH); + AT_ASSERT(w2 >= 0 && w2 < inputW); + + int planeIndex = h2 * inputW + w2; + scalar_t val = inputForPlane[planeIndex]; + if (val > maxVal || std::isnan(val)) { + maxVal = val; + maxIndex = planeIndex; + } + } + } + + outputForPlane[h * outputW + w] = maxVal; + indicesForPlane[h * outputW + w] = maxIndex; + } + } + } + }); +} + +template +void fractional_max_pool2d_out_frame( + const scalar_t* input, + scalar_t* output, + int64_t* indices, + const scalar_t* randomSamples, + int numBatch, int numPlanes, + int inputW, int inputH, + int outputW, int outputH, + int poolSizeW, int poolSizeH) { + if(numBatch == 1) { + fractional_max_pool2d_out_single_batch_frame( + input, + output, + indices, + randomSamples, + numPlanes, inputW, inputH, outputW, outputH, poolSizeW, poolSizeH + ); + return; + } + at::parallel_for(0, numBatch, 0, [&](int64_t start, int64_t end) { + for (const auto batch : c10::irange(start, end)) { + fractional_max_pool2d_out_single_batch_frame( + input + batch * numPlanes * inputH * inputW, + output + batch * numPlanes * outputH * outputW, + indices + batch * numPlanes * outputH * outputW, + randomSamples + batch * numPlanes * 2, + numPlanes, inputW, inputH, outputW, outputH, poolSizeW, poolSizeH); + } + }); + } + +template +void fractional_max_pool2d_backward_out_single_batch_frame( + scalar_t* gradInput, + const scalar_t* gradOutput, + const int64_t* indices, + int numPlanes, + int inputW, int inputH, + int outputW, int outputH) { + at::parallel_for(0, numPlanes, 0, [&](int64_t start, int64_t end) { + for (const auto plane : c10::irange(start, end)) { + scalar_t* gradInputForPlane = gradInput + plane * inputW * inputH; + const scalar_t* gradOutputForPlane = gradOutput + plane * outputW * outputH; + const int64_t* indicesForPlane = indices + plane * outputW * outputH; + + for (int h = 0; h < outputH; ++h) { + for (int w = 0; w < outputW; ++w) { + int outputIndex = h * outputW + w; + int64_t index = indicesForPlane[outputIndex]; + AT_ASSERT(index >= 0 && index < static_cast(inputW) * inputH); + + gradInputForPlane[index] += gradOutputForPlane[outputIndex]; + } + } + } + }); +} + +template +void fractional_max_pool2d_backward_out_frame( + scalar_t* gradInput, + const scalar_t* gradOutput, + const int64_t* indices, + int numBatch, int numPlanes, + int inputW, int inputH, + int outputW, int outputH) { + if(numBatch == 1) { + fractional_max_pool2d_backward_out_single_batch_frame( + gradInput, gradOutput, indices, + numPlanes, + inputW, inputH, outputW, outputH + ); + return; + } + at::parallel_for(0, numBatch, 0, [&](int64_t start, int64_t end) { + for (const auto batch : c10::irange(start, end)) { + fractional_max_pool2d_backward_out_single_batch_frame( + gradInput + batch * numPlanes * inputH * inputW, + gradOutput + batch * numPlanes * outputH * outputW, + indices + batch * numPlanes * outputH * outputW, + numPlanes, inputW, inputH, outputW, outputH); + } + }); +} + +} // anonymous namespace + +TORCH_IMPL_FUNC(fractional_max_pool2d_out_cpu) ( + const at::Tensor& input_, + IntArrayRef pool_size, + IntArrayRef output_size, + const at::Tensor& randomSamples_, + const at::Tensor& output, + const at::Tensor& indices) { + + fractional_max_pool_check_shape(input_, randomSamples_); + + if (output.numel() == 0) { + return; + } + + int64_t numBatch = 1; + int64_t planeDim = 0; + int64_t heightDim = 1; + int64_t widthDim = 2; + int64_t outputH = output_size[0]; // output.size(heightDim) + int64_t outputW = output_size[1]; // output.size(widthDim) + int64_t poolSizeH = pool_size[0]; + int64_t poolSizeW = pool_size[1]; + + /* get contiguous input and samples */ + auto input = input_.contiguous(); + auto randomSamples = randomSamples_.contiguous(); + + int64_t ndims = input.ndimension(); + + if (ndims == 4) { + numBatch = input.size(0); + planeDim++; + heightDim++; + widthDim++; + } + + /* sizes */ + int64_t numPlanes = input.size(planeDim); + int64_t inputH = input.size(heightDim); + int64_t inputW = input.size(widthDim); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, + kHalf, + input.scalar_type(), + "fractional_max_pool2d_out_frame", [&] { + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + auto randomSamples_data = randomSamples.const_data_ptr(); + fractional_max_pool2d_out_frame( + input_data, + output_data, + indices_data, + randomSamples_data, + numBatch, numPlanes, + inputW, inputH, + outputW, outputH, + poolSizeW, poolSizeH); + } + ); +} + +TORCH_IMPL_FUNC(fractional_max_pool2d_backward_cpu) ( + const at::Tensor& gradOutput_, + const at::Tensor& input, + IntArrayRef pool_size, + IntArrayRef output_size, + const at::Tensor& indices, + const at::Tensor& gradInput) { + + gradInput.zero_(); + + int64_t numBatch = 1; + int planeDim = 0; + int heightDim = 1; + int widthDim = 2; + + auto outputH = output_size[0]; + auto outputW = output_size[1]; + + auto ndims = input.ndimension(); + if (ndims == 4) { + numBatch = input.size(0); + planeDim = 1; + heightDim++; + widthDim++; + } + + /* sizes */ + auto numPlanes = input.size(planeDim); + auto inputH = input.size(heightDim); + auto inputW = input.size(widthDim); + + /* get contiguous gradOutput */ + auto gradOutput = gradOutput_.contiguous(); + + /* backprop */ + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, + kHalf, + input.scalar_type(), "fractional_max_pool2d_backward_out_frame", [&] { + auto gradInput_data = gradInput.data_ptr(); + auto gradOutput_data = gradOutput.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + fractional_max_pool2d_backward_out_frame( + gradInput_data, + gradOutput_data, + indices_data, + numBatch, numPlanes, + inputW, inputH, + outputW, outputH + ); + } + ); +} + +} // at::native +} // at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPool3d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPool3d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..630191b88fab5236cfc1bd8be6ac1098c62bc44d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPool3d.cpp @@ -0,0 +1,424 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + + +namespace at::meta { +TORCH_PRECOMPUTE_META_FUNC(fractional_max_pool3d)( + const at::Tensor& input_, + IntArrayRef pool_size, + IntArrayRef output_size, + const at::Tensor& randomSamples +) { + TORCH_CHECK( + pool_size.size() == 3, + "fractional_max_pool3d: kernel_size must either be a single Int or tuple of three Ints") + TORCH_CHECK( + output_size.size() == 3, + "fractional_max_pool3d: output_size must either be a single Int or tuple of three Ints") + int64_t outputT = output_size[0]; + int64_t outputH = output_size[1]; + int64_t outputW = output_size[2]; + int64_t poolSizeT = pool_size[0]; + int64_t poolSizeH = pool_size[1]; + int64_t poolSizeW = pool_size[2]; + + int64_t numBatch = 1; + int64_t planeDim = 0; + int64_t timeDim = 1; + int64_t heightDim = 2; + int64_t widthDim = 3; + + int64_t ndims = input_.ndimension(); + TORCH_CHECK(ndims == 4 || ndims == 5, + "fractional_max_pool3d_out(): Expected 4D or 5D tensor, but got: ", + input_.sizes()); + for (const auto i : c10::irange(1, ndims)) { + TORCH_CHECK(input_.size(i) > 0, + "fractional_max_pool3d_out(): Expected input to have non-zero size for non-batch dimensions, but got", + input_.sizes(), " with dimension ", i, " being empty."); + } + + if (ndims == 5) { + numBatch = input_.size(0); + planeDim++; + timeDim++; + heightDim++; + widthDim++; + } + + /* sizes */ + int64_t numPlanes = input_.size(planeDim); + int64_t inputT = input_.size(timeDim); + int64_t inputH = input_.size(heightDim); + int64_t inputW = input_.size(widthDim); + + TORCH_CHECK((poolSizeT <= inputT) && (outputT + poolSizeT - 1 < inputT), + "fractional_max_pool3d_out(): pool time ", poolSizeT, + " too large relative to input time ", inputT); + TORCH_CHECK((poolSizeW <= inputW) && (outputW + poolSizeW - 1 < inputW), + "fractional_max_pool3d_out(): pool width ", poolSizeW, + " too large relative to input width ", inputW); + TORCH_CHECK((poolSizeH <= inputH) && (outputH + poolSizeH - 1 < inputH), + "fractional_max_pool3d_out(): pool height ", poolSizeH, + " too large relative to input height ", inputH); + + if (ndims == 4) { + /* resize output */ + set_output_raw_strided(0, {numPlanes, outputT, outputH, outputW}, {}, input_.options()); + /* indices will contain the locations for each output point */ + set_output_raw_strided(1, {numPlanes, outputT, outputH, outputW}, {}, input_.options().dtype(kLong)); + } else { + set_output_raw_strided(0, {numBatch, numPlanes, outputT, outputH, outputW}, {}, input_.options()); + /* indices will contain the locations for each output point */ + set_output_raw_strided(1, {numBatch, numPlanes, outputT, outputH, outputW}, {}, input_.options().dtype(kLong)); + } + + return TORCH_PRECOMPUTE_STRUCT(fractional_max_pool3d)().set_numBatch(numBatch).set_numPlanes(numPlanes).set_inputT(inputT).set_inputH(inputH).set_inputW(inputW) + .set_poolSizeT(poolSizeT).set_poolSizeH(poolSizeH).set_poolSizeW(poolSizeW) + .set_outputT(outputT).set_outputH(outputH).set_outputW(outputW); +} + +} // namespace at::meta + +namespace at::native { +namespace { + +template +void fractional_max_pool3d_out_single_batch_frame( + const scalar_t* input, + scalar_t* output, + int64_t* indices, + const scalar_t* randomSamples, + int64_t numPlanes, + int64_t inputT, int64_t inputH, int64_t inputW, + int64_t outputT, int64_t outputH, int64_t outputW, + int64_t poolSizeT, int64_t poolSizeH, int64_t poolSizeW) { + + at::parallel_for(0, numPlanes, 0, [&](int64_t start, int64_t end) { + for (const auto plane : c10::irange(start, end)) { + /* each plane contains 3 random samples, + one for T, one for W, and one for H */ + const scalar_t* randomSamplesForPlane = randomSamples + plane * 3; + + /* Generate interval sequence */ + auto sequenceT = generate_intervals( + randomSamplesForPlane[0], inputT, outputT, poolSizeT); + auto sequenceH = generate_intervals( + randomSamplesForPlane[1], inputH, outputH, poolSizeH); + auto sequenceW = generate_intervals( + randomSamplesForPlane[2], inputW, outputW, poolSizeW); + + /* loop over output */ + + const scalar_t* inputForPlane = input + plane * inputT * inputH * inputW; + scalar_t* outputForPlane = output + plane * outputT * outputH * outputW; + int64_t* indicesForPlane = indices + plane * outputT * outputH * outputW; + + for (int64_t t = 0; t < outputT; ++t) { + int64_t inputTStart = sequenceT[t]; + + for (int64_t h = 0; h < outputH; ++h) { + int64_t inputHStart = sequenceH[h]; + + for (int64_t w = 0; w < outputW; ++w) { + int64_t inputWStart = sequenceW[w]; + + int64_t t2 = inputTStart, h2 = inputHStart, w2 = inputWStart; + scalar_t maxVal = -std::numeric_limits::infinity(); + int64_t maxIndex = t2 * inputH * inputW + h2 * inputW + w2; + + for (t2 = inputTStart; t2 < inputTStart + poolSizeT; ++t2) { + for (h2 = inputHStart; h2 < inputHStart + poolSizeH; ++h2) { + for (w2 = inputWStart; w2 < inputWStart + poolSizeW; ++w2) { + AT_ASSERT(t2 >= 0 && t2 < inputT); + AT_ASSERT(h2 >= 0 && h2 < inputH); + AT_ASSERT(w2 >= 0 && w2 < inputW); + + int64_t planeIndex = t2 * inputH * inputW + h2 * inputW + w2; + scalar_t val = inputForPlane[planeIndex]; + if (val > maxVal || std::isnan(val)) { + maxVal = val; + maxIndex = planeIndex; + } + } + } + } + + outputForPlane[t * outputH * outputW + h * outputW + w] = maxVal; + indicesForPlane[t * outputH * outputW + h * outputW + w] = maxIndex; + } + } + } + } + }); +} + +template +void fractional_max_pool3d_out_frame( + const scalar_t* input, + scalar_t* output, + int64_t* indices, + const scalar_t* randomSamples, + int64_t numBatch, int64_t numPlanes, + int64_t inputT, int64_t inputH, int64_t inputW, + int64_t outputT, int64_t outputH, int64_t outputW, + int64_t poolSizeT, int64_t poolSizeH, int64_t poolSizeW) { + if(numBatch == 1) { + fractional_max_pool3d_out_single_batch_frame( + input, output, indices, randomSamples, + numPlanes, + inputT, inputH, inputW, + outputT, outputH, outputW, + poolSizeT, poolSizeH, poolSizeW + ); + return; + } + + at::parallel_for(0, numBatch, 0, [&](int64_t start, int64_t end) { + for (const auto batch : c10::irange(start, end)) { + fractional_max_pool3d_out_single_batch_frame( + input + batch * numPlanes * inputW * inputH * inputT, + output + batch * numPlanes * outputW * outputH * outputT, + indices + batch * numPlanes * outputW * outputH * outputT, + randomSamples + batch * numPlanes * 3, + numPlanes, + inputT, inputH, inputW, + outputT, outputH, outputW, + poolSizeT, poolSizeH, poolSizeW + ); + } + }); + } + +} // anonymous namespace + +TORCH_IMPL_FUNC(fractional_max_pool3d_out_cpu)( + const at::Tensor& input_, + int64_t poolSizeT, + int64_t poolSizeH, + int64_t poolSizeW, + int64_t outputT, + int64_t outputH, + int64_t outputW, + const at::Tensor& randomSamples_, + int64_t numBatch, + int64_t numPlanes, + int64_t inputT, + int64_t inputH, + int64_t inputW, + const at::Tensor& output, + const at::Tensor& indices) { + + fractional_max_pool_check_shape(input_, randomSamples_); + + if (output.numel() == 0) { + return; + } + + /* get contiguous input and samples */ + auto input = input_.contiguous(); + auto randomSamples = randomSamples_.contiguous(); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, + kHalf, + input.scalar_type(), + "fractional_max_pool3d_out_frame", + [&] { + fractional_max_pool3d_out_frame( + input.const_data_ptr(), + output.data_ptr(), + indices.data_ptr(), + randomSamples.const_data_ptr(), + numBatch, numPlanes, + inputT, inputH, inputW, + outputT, outputH, outputW, + poolSizeT, poolSizeH, poolSizeW + ); + } + ); +} + +namespace { + +template +void fractional_max_pool3d_backward_out_single_batch_frame( + scalar_t* gradInput, + const scalar_t* gradOutput, + const int64_t* indices, + int64_t numPlanes, + int64_t inputT, int64_t inputH, int64_t inputW, + int64_t outputT, int64_t outputH, int64_t outputW) { + + at::parallel_for(0, numPlanes, 0, [&](int64_t start, int64_t end) { + for (const auto plane : c10::irange(start, end)) { + scalar_t* gradInputForPlane = gradInput + plane * inputT * inputH * inputW; + const scalar_t* gradOutputForPlane = gradOutput + + plane * outputT * outputH * outputW; + const int64_t* indicesForPlane = indices + plane * outputT * outputH * outputW; + + for (int64_t t = 0; t < outputT; ++t) { + for (int64_t h = 0; h < outputH; ++h) { + for (int64_t w = 0; w < outputW; ++w) { + int64_t outputIndex = t * outputH * outputW + h * outputW + w; + int64_t index = indicesForPlane[outputIndex]; + AT_ASSERT(index >= 0 && index < inputT * inputH * inputW); + gradInputForPlane[index] += gradOutputForPlane[outputIndex]; + } + } + } + } + }); +} + +template +void fractional_max_pool3d_backward_out_frame( + scalar_t* gradInput, + const scalar_t* gradOutput, + const int64_t* indices, + int64_t numBatch, int64_t numPlanes, + int64_t inputT, int64_t inputH, int64_t inputW, + int64_t outputT, int64_t outputH, int64_t outputW) { + if(numBatch == 1) { + fractional_max_pool3d_backward_out_single_batch_frame( + gradInput, gradOutput, indices, + numPlanes, + inputT, inputH, inputW, + outputT, outputH, outputW + ); + return; + } + + at::parallel_for(0, numBatch, 0, [&](int64_t start, int64_t end) { + for (const auto batch : c10::irange(start, end)) { + fractional_max_pool3d_backward_out_single_batch_frame( + gradInput + batch * numPlanes * inputW * inputH * inputT, + gradOutput + batch * numPlanes * outputW * outputH * outputT, + indices + batch * numPlanes * outputW * outputH * outputT, + numPlanes, + inputT, inputH, inputW, + outputT, outputH, outputW + ); + } + }); + } + + +void fractional_max_pool3d_backward_out_cpu_template( + const Tensor& input, + const Tensor& gradOutput_, + Tensor& gradInput, + IntArrayRef output_size, + IntArrayRef pool_size /* unused */, + const Tensor& indices) { + + int64_t outputT = output_size[0]; + int64_t outputH = output_size[1]; + int64_t outputW = output_size[2]; + + int64_t numBatch = 1; + int64_t planeDim = 0; + int64_t timeDim = 1; + int64_t heightDim = 2; + int64_t widthDim = 3; + + int64_t ndims = input.ndimension(); + if (ndims == 5) { + numBatch = input.size(0); + planeDim = 1; + heightDim++; + widthDim++; + timeDim++; + } + + /* sizes */ + int64_t numPlanes = input.size(planeDim); + int64_t inputT = input.size(timeDim); + int64_t inputH = input.size(heightDim); + int64_t inputW = input.size(widthDim); + + TORCH_CHECK(outputT == gradOutput_.size(timeDim), + "fractional_max_pool3d_backward_out(): gradOutput time unexpected"); + TORCH_CHECK(outputH == gradOutput_.size(heightDim), + "fractional_max_pool3d_backward_out(): ", + "gradOutput height unexpected"); + TORCH_CHECK(outputW == gradOutput_.size(widthDim), + "fractional_max_pool3d_backward_out(): gradOutput width unexpected"); + + /* get contiguous gradOutput */ + auto gradOutput = gradOutput_.contiguous(); + + /* resize */ + gradInput.resize_as_(input); + gradInput.zero_(); + + /* backprop */ + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, + kHalf, + input.scalar_type(), + "fractional_max_pool3d_backward_out_frame", + [&]{ + fractional_max_pool3d_backward_out_frame( + gradInput.data_ptr(), + gradOutput.const_data_ptr(), + indices.const_data_ptr(), + numBatch, numPlanes, + inputT, inputH, inputW, + outputT, outputH, outputW + ); + } + ); +} + +}// anonymous namespace + +Tensor& fractional_max_pool3d_backward_out_cpu(const at::Tensor& gradOutput_, + const at::Tensor& input, + IntArrayRef pool_size, + IntArrayRef output_size, + const at::Tensor& indices, + at::Tensor& gradInput) { + fractional_max_pool3d_backward_out_cpu_template( + input, + gradOutput_, + gradInput, + output_size, + pool_size, + indices); + return gradInput; +} + +Tensor fractional_max_pool3d_backward_cpu( + const at::Tensor& gradOutput_, + const at::Tensor& input, + IntArrayRef pool_size, + IntArrayRef output_size, + const at::Tensor& indices) { + Tensor gradInput = at::empty({0}, input.options()); + fractional_max_pool3d_backward_out_cpu_template( + input, + gradOutput_, + gradInput, + output_size, + pool_size, + indices); + return gradInput; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPooling.h b/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPooling.h new file mode 100644 index 0000000000000000000000000000000000000000..1ad7a625ba3b9afa22f13aaff642220b2f71f34c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FractionalMaxPooling.h @@ -0,0 +1,80 @@ +#pragma once +#include +#include +#include + +namespace at::native { + +template +inline std::vector generate_intervals( + scalar_t sample, + int64_t inputSize, + int64_t outputSize, + int64_t poolSize) { + std::vector sequence(outputSize); + if (outputSize > 1) { + scalar_t alpha = static_cast(inputSize - poolSize) / + static_cast(outputSize - 1); + + for (const auto i : c10::irange(outputSize - 1)) { + sequence[i] = + static_cast((i + sample) * alpha) - static_cast(sample * alpha); + } + } + if (outputSize > 0) { + sequence[outputSize - 1] = inputSize - poolSize; + } + return sequence; +} + +template +inline void fractional_max_pool_check_shape( + const Tensor& input, + const Tensor& randomSamples) { + + TORCH_CHECK( + input.scalar_type() == randomSamples.scalar_type(), + "Expect _random_samples to have the same dtype as input"); + + int64_t ndimension = randomSamples.ndimension(); + TORCH_CHECK( + ndimension == 3, + "Expect _random_samples to have 3 dimensions, got ", ndimension); + + int64_t N = randomSamples.size(0); + int64_t C = randomSamples.size(1); + int64_t D = randomSamples.size(2); + + int64_t input_batch = 0, input_channel = 0; + if (ndim == 2) { + // fractional_max_pool2d + if (input.ndimension() == 3) { + input_batch = 1; + input_channel = input.size(0); + } else { + input_batch = input.size(0); + input_channel = input.size(1); + } + } else { + // factional_max_pool3d + if (input.ndimension() == 4) { + input_batch = 1; + input_channel = input.size(0); + } else { + input_batch = input.size(0); + input_channel = input.size(1); + } + } + + TORCH_CHECK( + N >= input_batch, + "Expect _random_samples.size(0) no less then input batch size."); + TORCH_CHECK( + C == input_channel, + "Expect _random_samples.size(1) equals to input channel size."); + TORCH_CHECK( + D == ndim, + "Expect _random_samples.size(2) equals to ", ndim, "; got ", D, "."); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FunctionOfAMatrixUtils.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/FunctionOfAMatrixUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d941209f80b8f42fd794d3bd61da4a9e9e1d78d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FunctionOfAMatrixUtils.cpp @@ -0,0 +1,118 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::native { + +DEFINE_DISPATCH(_compute_linear_combination_stub); + +// If `coefficients` is a [m, n] Tensor and +// `input` is a [n, ...] Tensor, then the output +// `output` is going to be a [m, ...] Tensor such that +// for i in range(m): +// for j in range(n): +// output[i, ...] += coefficients[i, j] * input[j, ...] +// +// Note: if input.dtype == scalar_t, then coefficients.dtype == T. +// This is relevant when scalar_t == complex. +Tensor _compute_linear_combination(const Tensor& input, const Tensor& coefficients) { + TORCH_CHECK(input.ndimension() > 0 && input.numel() > 0, "Empty tensor not supported"); + auto output_first_dim_size = coefficients.size(0); + + auto output_sizes = input.sizes().vec(); + output_sizes[0] = output_first_dim_size; + auto output = at::zeros( + output_sizes, + input.options().memory_format(at::MemoryFormat::Contiguous) + ); + + native::_compute_linear_combination_out(input, coefficients, output); + + return output; +} + +// Note: the function is implemented using the __restrict__ memory modifier, +// which means that if `output` actually is aliased by `input`, the result +// produced is undefined. +Tensor& _compute_linear_combination_out(const Tensor& input, const Tensor& coefficients, Tensor& output) { + auto output_first_dim_size = coefficients.size(0); + auto input_first_dim_size = coefficients.size(1); + + // Recall that `coefficients` is a [m, n] Tensor, + // `input` is a [n, ...] Tensor, `output` is a [m, ...] Tensor. + // We restride Tensors to the common dim == input.dim() + 1, so that + // coefficients.sizes() = [m, 1 (instead of n), 1 repeated (input.dim() - 1) times], + // input.sizes() = [1, 1 (instead of n), ...], + // output.sizes() = [m, 1 (instead of n), ...]. + // The second dimension in newly restrided Tensors is traversed inside the kernels. + // This is done to avoid synchronizations/atomic operations in the kernels + // and also guarantees determinism, required by the autograd. + + // restride output + auto output_to_broadcasted_dim = output.unsqueeze(1); + auto output_restrided_sizes = output_to_broadcasted_dim.sizes().vec(); + auto output_restrided_strides = output_to_broadcasted_dim.strides().vec(); + output_restrided_sizes[1] = 1; + output_restrided_strides[1] = 0; + auto output_restrided = output.as_strided( + output_restrided_sizes, + output_restrided_strides + ); + + // restride input + auto input_to_broadcasted_dim = input.unsqueeze(0); + auto input_restrided_sizes = input_to_broadcasted_dim.sizes().vec(); + auto input_restrided_strides = input_to_broadcasted_dim.strides().vec(); + input_restrided_sizes[1] = 1; + input_restrided_strides[1] = 0; + auto input_restrided = input.as_strided( + input_restrided_sizes, + input_restrided_strides + ); + + // restride coefficients + auto coefficients_restrided_sizes = std::vector(input.dim() + 1, 1); + coefficients_restrided_sizes[0] = output_first_dim_size; + coefficients_restrided_sizes[1] = 1; + auto coefficients_restrided_strides = std::vector(input.dim() + 1, 0); + coefficients_restrided_strides[0] = coefficients.stride(0); + coefficients_restrided_strides[1] = 0; + auto coefficients_restrided = coefficients.as_strided( + coefficients_restrided_sizes, + coefficients_restrided_strides + ); + + auto iter = TensorIteratorConfig() + .set_check_mem_overlap(false) // Output is intentionally 0 strided above + .check_all_same_dtype(false) + .resize_outputs(false) + .add_output(output_restrided) + .add_input(input_restrided) + .add_input(coefficients_restrided) + .build(); + + // The dimension of size n is traversed inside the kernels, + // it is the first dimension of `input` and the second of `coefficients` + auto input_stride = input.stride(0); + auto coeff_stride = coefficients.stride(1); + _compute_linear_combination_stub( + iter.device_type(), + iter, + input_stride, + coeff_stride, + input_first_dim_size + ); + return output; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FunctionOfAMatrixUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/FunctionOfAMatrixUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..db42959bd0309c8f0ccd5bb4da316f09f7bb1bca --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FunctionOfAMatrixUtils.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +namespace at { +struct TensorIterator; + +namespace native { + +using _compute_linear_combination_fn = void(*)( + TensorIterator& iter, + int64_t in_stride, + int64_t coeff_stride, + int64_t num_summations +); + +DECLARE_DISPATCH(_compute_linear_combination_fn, _compute_linear_combination_stub) + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdagrad.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdagrad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bef0c379dadbdc76ac5bbd81ab4eb87486fd1a43 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdagrad.cpp @@ -0,0 +1,83 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::native { + +void _fused_adagrad_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList state_sums, + at::TensorList state_steps, + const double lr, + const double lr_decay, + const double weight_decay, + const double eps, + const bool maximize, + const std::optional& grad_scale, + const std::optional& found_inf) { + const float* grad_scale_ptr = + grad_scale.has_value() ? grad_scale->data_ptr() : nullptr; + const float* found_inf_ptr = + found_inf.has_value() ? found_inf->data_ptr() : nullptr; + if (found_inf_ptr && *found_inf_ptr == 1.0) { + return; + } + size_t n_tensors = params.size(); + TORCH_CHECK(grads.size() == n_tensors); + TORCH_CHECK(state_sums.size() == n_tensors); + TORCH_CHECK(state_steps.size() == n_tensors); + for (size_t i = 0; i < n_tensors; i++) { + fused_adagrad_stub( + kCPU, + params[i], + grads[i], + state_sums[i], + state_steps[i], + lr, + lr_decay, + weight_decay, + eps, + maximize, + grad_scale_ptr); + } +} + +void _fused_adagrad_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList state_sums, + at::TensorList state_steps, + const at::Tensor& lr, + const double lr_decay, + const double weight_decay, + const double eps, + const bool maximize, + const std::optional& grad_scale, + const std::optional& found_inf) { + _fused_adagrad_kernel_cpu_( + params, + grads, + state_sums, + state_steps, + lr.item(), + lr_decay, + weight_decay, + eps, + maximize, + grad_scale, + found_inf); +} + +DEFINE_DISPATCH(fused_adagrad_stub); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdagrad.h b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdagrad.h new file mode 100644 index 0000000000000000000000000000000000000000..bf2540202c686789cc4e11f7fbcd1b3f858509c4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdagrad.h @@ -0,0 +1,20 @@ +#include +#include + +namespace at::native { + +using fused_adagrad_fn = void (*)( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& state_sum, + const at::Tensor& state_step, + const double lr, + const double lr_decay, + const double weight_decay, + const double eps, + const bool maximize, + const float* grad_scale_ptr); + +DECLARE_DISPATCH(fused_adagrad_fn, fused_adagrad_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdam.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdam.cpp new file mode 100644 index 0000000000000000000000000000000000000000..399c937b112162558b39559a838a97c026a89f02 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdam.cpp @@ -0,0 +1,174 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + + +namespace at::native { + +void _fused_adam_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList exp_avgs, + at::TensorList exp_avg_sqs, + at::TensorList max_exp_avg_sqs, + at::TensorList state_steps, + const double lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const std::optional& grad_scale, + const std::optional& found_inf) { + const float* grad_scale_ptr = + grad_scale.has_value() ? grad_scale->data_ptr() : nullptr; + const float* found_inf_ptr = + found_inf.has_value() ? found_inf->data_ptr() : nullptr; + if (found_inf_ptr && *found_inf_ptr == 1.0) { + return; + } + size_t n_tensors = params.size(); + TORCH_CHECK(grads.size() == n_tensors); + TORCH_CHECK(exp_avgs.size() == n_tensors); + TORCH_CHECK(exp_avg_sqs.size() == n_tensors); + if (amsgrad) { + TORCH_CHECK(max_exp_avg_sqs.size() == n_tensors); + } else { + TORCH_CHECK(max_exp_avg_sqs.empty()); + } + TORCH_CHECK(state_steps.size() == n_tensors); + at::Tensor max_exp_avg_sq = at::Tensor(); + for (size_t i = 0; i < n_tensors; i++){ + if (amsgrad) max_exp_avg_sq = max_exp_avg_sqs[i]; + fused_adam_stub( + kCPU, + params[i], + grads[i], + exp_avgs[i], + exp_avg_sqs[i], + max_exp_avg_sq, + state_steps[i], + lr, + beta1, + beta2, + weight_decay, + eps, + amsgrad, + maximize, + grad_scale_ptr, + ADAM_MODE::ORIGINAL); + } +} + +// The following overload simply has a Tensor lr +void _fused_adam_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList exp_avgs, + at::TensorList exp_avg_sqs, + at::TensorList max_exp_avg_sqs, + at::TensorList state_steps, + const at::Tensor& lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const std::optional& grad_scale, + const std::optional& found_inf) { + _fused_adam_kernel_cpu_(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr.item(), beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + +void _fused_adamw_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList exp_avgs, + at::TensorList exp_avg_sqs, + at::TensorList max_exp_avg_sqs, + at::TensorList state_steps, + const double lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const std::optional& grad_scale, + const std::optional& found_inf) { + const float* grad_scale_ptr = + grad_scale.has_value() ? grad_scale->data_ptr() : nullptr; + const float* found_inf_ptr = + found_inf.has_value() ? found_inf->data_ptr() : nullptr; + if (found_inf_ptr && *found_inf_ptr == 1.0) { + return; + } + size_t n_tensors = params.size(); + TORCH_CHECK(grads.size() == n_tensors); + TORCH_CHECK(exp_avgs.size() == n_tensors); + TORCH_CHECK(exp_avg_sqs.size() == n_tensors); + if (amsgrad) { + TORCH_CHECK(max_exp_avg_sqs.size() == n_tensors); + } else { + TORCH_CHECK(max_exp_avg_sqs.empty()); + } + TORCH_CHECK(state_steps.size() == n_tensors); + at::Tensor max_exp_avg_sq = at::Tensor(); + for (size_t i = 0; i < n_tensors; i++){ + if (amsgrad) max_exp_avg_sq = max_exp_avg_sqs[i]; + fused_adam_stub( + kCPU, + params[i], + grads[i], + exp_avgs[i], + exp_avg_sqs[i], + max_exp_avg_sq, + state_steps[i], + lr, + beta1, + beta2, + weight_decay, + eps, + amsgrad, + maximize, + grad_scale_ptr, + ADAM_MODE::ADAMW); + } +} + +// The following overload simply has a Tensor lr +void _fused_adamw_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList exp_avgs, + at::TensorList exp_avg_sqs, + at::TensorList max_exp_avg_sqs, + at::TensorList state_steps, + const at::Tensor& lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const std::optional& grad_scale, + const std::optional& found_inf) { + _fused_adamw_kernel_cpu_(params, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps, lr.item(), beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale, found_inf); +} + + +DEFINE_DISPATCH(fused_adam_stub); + +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdam.h b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdam.h new file mode 100644 index 0000000000000000000000000000000000000000..530424b5316890c174876a221da3f10631b7b370 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FusedAdam.h @@ -0,0 +1,27 @@ +#include +#include + +namespace at::native { + +enum class ADAM_MODE : uint8_t { ORIGINAL = 0, ADAMW = 1 }; + +using fused_adam_fn = void (*)( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& exp_avg, + const at::Tensor& exp_avg_sq, + const at::Tensor& max_exp_avg_sq, + const at::Tensor& state_step, + const double lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const float* grad_scale_ptr, + const ADAM_MODE); + +DECLARE_DISPATCH(fused_adam_fn, fused_adam_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FusedSGD.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/FusedSGD.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6909cd152baa3191f67c09ccc1c1ef7a0c85ed9f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FusedSGD.cpp @@ -0,0 +1,85 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + + +namespace at::native { + + +void _fused_sgd_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList momentum_buffer_list, + const double weight_decay, + const double momentum, + const double lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const std::optional& grad_scale, + const std::optional& found_inf) { + const float* grad_scale_ptr = + grad_scale.has_value() ? grad_scale->data_ptr() : nullptr; + const float* found_inf_ptr = + found_inf.has_value() ? found_inf->data_ptr() : nullptr; + if (found_inf_ptr && *found_inf_ptr == 1.0) { + return; + } + size_t n_tensors = params.size(); + TORCH_CHECK(grads.size() == n_tensors); + bool no_momentum_buffer = momentum == 0.0; + if (no_momentum_buffer) { + TORCH_CHECK(momentum_buffer_list.empty()); + } else { + TORCH_CHECK(momentum_buffer_list.size() == n_tensors); + } + for (size_t i = 0; i < n_tensors; i++){ + fused_sgd_stub( + kCPU, + params[i], + grads[i], + no_momentum_buffer ? Tensor() : momentum_buffer_list[i], + weight_decay, + momentum, + lr, + dampening, + nesterov, + maximize, + is_first_step, + grad_scale_ptr); + } +} + +void _fused_sgd_kernel_cpu_( + at::TensorList params, + at::TensorList grads, + at::TensorList momentum_buffer_list, + const double weight_decay, + const double momentum, + const at::Tensor& lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const std::optional& grad_scale, + const std::optional& found_inf) { + _fused_sgd_kernel_cpu_( + params, grads, momentum_buffer_list, weight_decay, + momentum, lr.item(), dampening, nesterov, + maximize, is_first_step, grad_scale, found_inf + ); +} + +DEFINE_DISPATCH(fused_sgd_stub); + +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/FusedSGD.h b/western_ai/usa/pytorch/aten/src/ATen/native/FusedSGD.h new file mode 100644 index 0000000000000000000000000000000000000000..283ccd1f3f2a2210cf510074bb8cee756d7904ef --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/FusedSGD.h @@ -0,0 +1,21 @@ +#include +#include + +namespace at::native { + +using fused_sgd_fn = void (*)( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& momentum_buffer, + const double weight_decay, + const double momentum, + const double lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const float* grad_scale_ptr); + +DECLARE_DISPATCH(fused_sgd_fn, fused_sgd_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/GatedLinearUnit.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/GatedLinearUnit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a2891ae77bd8eb02fc698d71eac9fcccfbc8c51 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/GatedLinearUnit.cpp @@ -0,0 +1,158 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::meta { + +TORCH_META_FUNC(glu) ( + const Tensor& self, int64_t dim +) { + // this can't pass anyway because a 0-dimensional tensor has "size" 1, which + // can't be evenly halved, but give a nicer error message here. + TORCH_CHECK(self.dim() > 0, "glu does not support 0-dimensional tensors"); + auto wrap_dim = maybe_wrap_dim(dim, self.dim()); + const int64_t nIn = self.size(wrap_dim); + TORCH_CHECK(nIn % 2 == 0, "Halving dimension must be even, but dimension ", + wrap_dim, " is size ", nIn); + + // size output to half of input + const int64_t selfSize = nIn / 2; + Tensor firstHalf = self.narrow(wrap_dim, 0, selfSize); + Tensor secondHalf = self.narrow(wrap_dim, selfSize, selfSize); + // Do not use build_borrowing_binary_op here, as self halves are stack allocated, + // but a structured op's iterator is reused in impl() after meta() func scope ends. + // Borrowing them would leave the iterator with dangling operands. + build_binary_op(maybe_get_output(), firstHalf, secondHalf); +} +} // namespace at::meta + +namespace at::native { + +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +DEFINE_DISPATCH(glu_stub); +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +DEFINE_DISPATCH(glu_backward_stub); +// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) +DEFINE_DISPATCH(glu_jvp_stub); + +TORCH_IMPL_FUNC(glu_out) (const Tensor& self, int64_t dim, const Tensor& out) { + glu_stub(device_type(), *this); +} + +Tensor& glu_backward_cpu_out(const Tensor& grad_output, const Tensor& input, + int64_t dim, Tensor& grad_input) { + TORCH_CHECK(input.dim() > 0, "glu does not support 0-dimensional tensors"); + auto wrap_dim = maybe_wrap_dim(dim, input.dim()); + const int64_t nIn = input.size(wrap_dim); + TORCH_CHECK(nIn % 2 == 0, "Halving dimension must be even, but dimension ", + wrap_dim, " is size ", nIn); + + grad_input.resize_as_(input); + const int64_t inputSize = nIn / 2; + // half tensor + Tensor firstHalf = input.narrow(wrap_dim, 0, inputSize); + Tensor secondHalf = input.narrow(wrap_dim, inputSize, inputSize); + Tensor gradInputfirstHalf = grad_input.narrow(wrap_dim, 0, inputSize); + Tensor gradInputsecondHalf = grad_input.narrow(wrap_dim, inputSize, inputSize); + + at::sigmoid_out(gradInputfirstHalf, secondHalf); + // for second gradinput half, can get a better performance by fusion + auto iter = at::TensorIteratorConfig() + .add_output(gradInputsecondHalf) + .add_const_input(gradInputfirstHalf) + .add_const_input(firstHalf) + .add_const_input(grad_output) + .build(); + glu_backward_stub(iter.device_type(), iter); + gradInputfirstHalf.mul_(grad_output); + return grad_input; +} + +Tensor glu_backward_cpu(const Tensor& grad_output, const Tensor& input, int64_t dim) { + auto grad_input = at::empty({0}, input.options()); + return glu_backward_cpu_out(grad_output, input, dim, grad_input); +} + +Tensor glu_jvp( + const Tensor& glu, + const Tensor& x, + const Tensor& dx, + int64_t dim +) { + dim = maybe_wrap_dim(dim, x.dim()); + const auto glu_size = glu.size(dim); + const auto b = x.narrow(dim, glu_size, glu_size); + const auto da = dx.narrow(dim, 0, glu_size); + const auto db = dx.narrow(dim, glu_size, glu_size); + auto dglu = at::empty_like(glu); + auto iter = at::TensorIteratorConfig() + .add_output(dglu) + .add_const_input(glu) + .add_const_input(b) + .add_const_input(da) + .add_const_input(db) + .build(); + glu_jvp_stub(iter.device_type(), iter); + return dglu; +} + +Tensor glu_backward_jvp( + const Tensor& grad_x, + const Tensor& grad_glu, + const Tensor& x, + const Tensor& dgrad_glu, + const Tensor& dx, + int64_t dim +) { + dim = maybe_wrap_dim(dim, x.dim()); + const auto glu_size = grad_glu.size(dim); + const auto a = x.narrow(dim, 0, glu_size); + const auto b = x.narrow(dim, glu_size, glu_size); + const auto da = dx.narrow(dim, 0, glu_size); + const auto db = dx.narrow(dim, glu_size, glu_size); + // grad_x_a = grad_glu * sigmoid(b) + const auto grad_x_a = grad_x.narrow(dim, 0, glu_size); + // grad_x_b = grad_x_a * a * (1 - sigmoid(b)) + const auto grad_x_b = grad_x.narrow(dim, glu_size, glu_size); + + const auto sig_b = at::sigmoid(b); + // TODO: use glu from forward. + // TODO: fuse kernels. + const auto glu = a * sig_b; + const auto db_neg_sig_b = db - db * sig_b; + + // dgrad_x_a = d(grad_glu * sigmoid(b)) + // = dgrad_glu * sigmoid(b) + grad_glu * sigmoid(b) * (1 - sigmoid(b)) * db + // = dgrad_glu * sig_b + grad_x_a * (db - db * sig_b) + // = dgrad_glu * sig_b + grad_x_a * db_neg_sig_b + const auto dgrad_x_a = dgrad_glu * sig_b + grad_x_a * db_neg_sig_b; + + // dgrad_x_b = d(grad_glu * sigmoid(b) * a * (1 - sigmoid(b)) + // = d(grad_glu * sigmoid(b)) * a * (1 - sigmoid(b)) + // + grad_glu * sigmoid(b) * da * (1 - sigmoid(b)) + // - grad_glu * sigmoid(b) * a * sigmoid(b) * (1 - sigmoid(b)) * db + // = dgrad_x_a * a * (1 - sigmoid(b)) + // + (grad_glu * sigmoid(b)) * (da * (1 - sigmoid(b)) - a * sigmoid(b) * (1 - sigmoid(b)) * db) + // = dgrad_x_a * (a - glu) + grad_x_a * (da - da * sig_b - glu * db_neg_sig_b + const auto dgrad_x_b = dgrad_x_a * (a - glu) + grad_x_a * (da - da * sig_b - glu * db_neg_sig_b); + + return at::cat({dgrad_x_a, dgrad_x_b}, dim); +} + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Gelu.h b/western_ai/usa/pytorch/aten/src/ATen/native/Gelu.h new file mode 100644 index 0000000000000000000000000000000000000000..111a729e1d764472b0975aac9da4ee92ed7cf694 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Gelu.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +namespace at::native { +// These constants control the approximation behavior of gelu function. +enum class GeluType { + None, // Baseline Gelu + Tanh, // Tanh Gelu Approximation + END +}; + +inline GeluType get_gelutype_enum(const std::string_view approximate) { + if (approximate == "none") { + return GeluType::None; + } else if (approximate == "tanh") { + return GeluType::Tanh; + } else { + TORCH_CHECK(false, "approximate argument must be either none or tanh."); + } +} + +inline std::string gelutype_to_string(const GeluType type) { + switch(type) { + case GeluType::None: return "none"; + case GeluType::Tanh: return "tanh"; + default: TORCH_CHECK(false, "unknown GELU type: ", static_cast(type)); + } +} + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/GridSampler.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/GridSampler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..056a4ffb10e73bc7ba78b01b4efb32ba81dfef93 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/GridSampler.cpp @@ -0,0 +1,1068 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace at::native { + +using at::native::detail::GridSamplerInterpolation; +using at::native::detail::GridSamplerPadding; + +namespace { + + template + Tensor grid_sampler_3d_cpu_impl(const Tensor& input, const Tensor& grid, + GridSamplerInterpolation interpolation_mode, + GridSamplerPadding padding_mode, + bool align_corners) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_3d( + input, grid, static_cast(interpolation_mode)); + + int64_t N = input.size(0); + int64_t C = input.size(1); + int64_t inp_D = input.size(2); + int64_t inp_H = input.size(3); + int64_t inp_W = input.size(4); + int64_t out_D = grid.size(1); + int64_t out_H = grid.size(2); + int64_t out_W = grid.size(3); + auto output = at::empty({N, C, out_D, out_H, out_W}, input.options()); + if (output.numel() == 0) { + return output; + } + int64_t inp_sN = input.stride(0); + int64_t inp_sC = input.stride(1); + int64_t inp_sD = input.stride(2); + int64_t inp_sH = input.stride(3); + int64_t inp_sW = input.stride(4); + int64_t grid_sN = grid.stride(0); + int64_t grid_sD = grid.stride(1); + int64_t grid_sH = grid.stride(2); + int64_t grid_sW = grid.stride(3); + int64_t grid_sCoor = grid.stride(4); + int64_t out_sN = output.stride(0); + int64_t out_sC = output.stride(1); + int64_t out_sD = output.stride(2); + int64_t out_sH = output.stride(3); + int64_t out_sW = output.stride(4); + const scalar_t *inp_ptr = input.const_data_ptr(); + scalar_t *out_ptr = output.data_ptr(); + const scalar_t *grid_ptr = grid.const_data_ptr(); + // loop over each output pixel + at::parallel_for(0, N, 0, [&](int64_t start, int64_t end) { + for (const auto n : c10::irange(start, end)) { + const scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; + const scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; + for (const auto d : c10::irange(out_D)) { + for (const auto h : c10::irange(out_H)) { + for (const auto w : c10::irange(out_W)) { + // get the corresponding input x, y, z coordinates from grid + const scalar_t *grid_ptr_NDHW = grid_ptr_N + d * grid_sD + h * grid_sH + w * grid_sW; + scalar_t ix = *grid_ptr_NDHW; + scalar_t iy = grid_ptr_NDHW[grid_sCoor]; + scalar_t iz = grid_ptr_NDHW[2 * grid_sCoor]; + + ix = grid_sampler_compute_source_index(ix, inp_W, padding_mode, align_corners); + iy = grid_sampler_compute_source_index(iy, inp_H, padding_mode, align_corners); + iz = grid_sampler_compute_source_index(iz, inp_D, padding_mode, align_corners); + + if (interpolation_mode == GridSamplerInterpolation::Bilinear) { + // get corner pixel values from (x, y, z) + // for 4d, we used north-east-south-west + // for 5d, we add top-bottom + int64_t ix_tnw = static_cast(std::floor(ix)); + int64_t iy_tnw = static_cast(std::floor(iy)); + int64_t iz_tnw = static_cast(std::floor(iz)); + + int64_t ix_tne = ix_tnw + 1; + int64_t iy_tne = iy_tnw; + int64_t iz_tne = iz_tnw; + + int64_t ix_tsw = ix_tnw; + int64_t iy_tsw = iy_tnw + 1; + int64_t iz_tsw = iz_tnw; + + int64_t ix_tse = ix_tnw + 1; + int64_t iy_tse = iy_tnw + 1; + int64_t iz_tse = iz_tnw; + + int64_t ix_bnw = ix_tnw; + int64_t iy_bnw = iy_tnw; + int64_t iz_bnw = iz_tnw + 1; + + int64_t ix_bne = ix_tnw + 1; + int64_t iy_bne = iy_tnw; + int64_t iz_bne = iz_tnw + 1; + + int64_t ix_bsw = ix_tnw; + int64_t iy_bsw = iy_tnw + 1; + int64_t iz_bsw = iz_tnw + 1; + + int64_t ix_bse = ix_tnw + 1; + int64_t iy_bse = iy_tnw + 1; + int64_t iz_bse = iz_tnw + 1; + + // get surfaces to each neighbor: + scalar_t tnw = (ix_bse - ix) * (iy_bse - iy) * (iz_bse - iz); + scalar_t tne = (ix - ix_bsw) * (iy_bsw - iy) * (iz_bsw - iz); + scalar_t tsw = (ix_bne - ix) * (iy - iy_bne) * (iz_bne - iz); + scalar_t tse = (ix - ix_bnw) * (iy - iy_bnw) * (iz_bnw - iz); + scalar_t bnw = (ix_tse - ix) * (iy_tse - iy) * (iz - iz_tse); + scalar_t bne = (ix - ix_tsw) * (iy_tsw - iy) * (iz - iz_tsw); + scalar_t bsw = (ix_tne - ix) * (iy - iy_tne) * (iz - iz_tne); + scalar_t bse = (ix - ix_tnw) * (iy - iy_tnw) * (iz - iz_tnw); + + // calculate bilinear weighted pixel value and set output pixel + scalar_t *out_ptr_NCDHW = out_ptr + n * out_sN + d * out_sD + h * out_sH + w * out_sW; + const scalar_t *inp_ptr_NC = inp_ptr_N; + for (int64_t c = 0; c < C; ++c, out_ptr_NCDHW += out_sC, inp_ptr_NC += inp_sC) { + // (c, iz_tnw, iy_tnw, ix_tnw) * tnw + (c, iz_tne, iy_tne, ix_tne) * tne + // + (c, iz_tsw, iy_tsw, ix_tsw) * tsw + (c, iz_tse, iy_tse, ix_tse) * tse + // + (c, iz_bnw, iy_bnw, ix_bnw) * bnw + (c, iz_bne, iy_bne, ix_bne) * bne + // + (c, iz_bsw, iy_bsw, ix_bsw) * bsw + (c, iz_bse, iy_bse, ix_bse) * bse + *out_ptr_NCDHW = static_cast(0); + if (within_bounds_3d(iz_tnw, iy_tnw, ix_tnw, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_tnw * inp_sD + iy_tnw * inp_sH + ix_tnw * inp_sW] * tnw; + } + if (within_bounds_3d(iz_tne, iy_tne, ix_tne, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_tne * inp_sD + iy_tne * inp_sH + ix_tne * inp_sW] * tne; + } + if (within_bounds_3d(iz_tsw, iy_tsw, ix_tsw, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_tsw * inp_sD + iy_tsw * inp_sH + ix_tsw * inp_sW] * tsw; + } + if (within_bounds_3d(iz_tse, iy_tse, ix_tse, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_tse * inp_sD + iy_tse * inp_sH + ix_tse * inp_sW] * tse; + } + if (within_bounds_3d(iz_bnw, iy_bnw, ix_bnw, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_bnw * inp_sD + iy_bnw * inp_sH + ix_bnw * inp_sW] * bnw; + } + if (within_bounds_3d(iz_bne, iy_bne, ix_bne, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_bne * inp_sD + iy_bne * inp_sH + ix_bne * inp_sW] * bne; + } + if (within_bounds_3d(iz_bsw, iy_bsw, ix_bsw, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_bsw * inp_sD + iy_bsw * inp_sH + ix_bsw * inp_sW] * bsw; + } + if (within_bounds_3d(iz_bse, iy_bse, ix_bse, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW += inp_ptr_NC[iz_bse * inp_sD + iy_bse * inp_sH + ix_bse * inp_sW] * bse; + } + } + } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { + int64_t ix_nearest = static_cast(std::nearbyint(ix)); + int64_t iy_nearest = static_cast(std::nearbyint(iy)); + int64_t iz_nearest = static_cast(std::nearbyint(iz)); + + // assign nearest neighbour pixel value to output pixel + scalar_t *out_ptr_NCDHW = out_ptr + n * out_sN + d * out_sD + h * out_sH + w * out_sW; + const scalar_t *inp_ptr_NC = inp_ptr_N; + for (int64_t c = 0; c < C; ++c, out_ptr_NCDHW += out_sC, inp_ptr_NC += inp_sC) { + if (within_bounds_3d(iz_nearest, iy_nearest, ix_nearest, inp_D, inp_H, inp_W)) { + *out_ptr_NCDHW = inp_ptr_NC[iz_nearest * inp_sD + iy_nearest * inp_sH + ix_nearest * inp_sW]; + } else { + *out_ptr_NCDHW = static_cast(0); + } + } + } + } + } + } + } + }); + return output; + } + + template + std::tuple + grid_sampler_3d_backward_cpu_impl(const Tensor& grad_output, + const Tensor& input, const Tensor& grid, + GridSamplerInterpolation interpolation_mode, + GridSamplerPadding padding_mode, + bool align_corners, std::array output_mask) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_3d( + input, grid, static_cast(interpolation_mode)); + + auto input_requires_grad = output_mask[0]; + Tensor grad_input = ([&]() { + if (input_requires_grad) { + return at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + } else { + return Tensor(); + } + })(); + auto grad_grid = at::empty_like(grid, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + if (grid.numel() == 0 || input.numel() == 0) { + grad_grid.zero_(); + return std::make_tuple(std::move(grad_input), std::move(grad_grid)); + } + // If interpolation mode is Nearest, then grad_grid is not filled in the + // loop below. + if (interpolation_mode == GridSamplerInterpolation::Nearest) { + grad_grid.zero_(); + } + int64_t N = input.size(0); + int64_t C = input.size(1); + int64_t inp_D = input.size(2); + int64_t inp_H = input.size(3); + int64_t inp_W = input.size(4); + int64_t out_D = grid.size(1); + int64_t out_H = grid.size(2); + int64_t out_W = grid.size(3); + int64_t inp_sN = input.stride(0); + int64_t inp_sC = input.stride(1); + int64_t inp_sD = input.stride(2); + int64_t inp_sH = input.stride(3); + int64_t inp_sW = input.stride(4); + int64_t grid_sN = grid.stride(0); + int64_t grid_sD = grid.stride(1); + int64_t grid_sH = grid.stride(2); + int64_t grid_sW = grid.stride(3); + int64_t grid_sCoor = grid.stride(4); + int64_t gOut_sN = grad_output.stride(0); + int64_t gOut_sC = grad_output.stride(1); + int64_t gOut_sD = grad_output.stride(2); + int64_t gOut_sH = grad_output.stride(3); + int64_t gOut_sW = grad_output.stride(4); + int64_t gInp_sN = 0; + int64_t gInp_sC = 0; + int64_t gInp_sD = 0; + int64_t gInp_sH = 0; + int64_t gInp_sW = 0; + if (input_requires_grad) { + gInp_sN = grad_input.stride(0); + gInp_sC = grad_input.stride(1); + gInp_sD = grad_input.stride(2); + gInp_sH = grad_input.stride(3); + gInp_sW = grad_input.stride(4); + } + int64_t gGrid_sN = grad_grid.stride(0); + int64_t gGrid_sW = grad_grid.stride(3); + const scalar_t *inp_ptr = input.const_data_ptr(); + const scalar_t *grid_ptr = grid.const_data_ptr(); + const scalar_t *gOut_ptr = grad_output.const_data_ptr(); + scalar_t *gInp_ptr = nullptr; + if (input_requires_grad) { + gInp_ptr = grad_input.mutable_data_ptr(); + } + scalar_t *gGrid_ptr = grad_grid.data_ptr(); + // loop over each output pixel + at::parallel_for(0, N, 0, [&](int64_t start, int64_t end) { + for (const auto n : c10::irange(start, end)) { + const scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; + const scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; + scalar_t *gGrid_ptr_NDHW = gGrid_ptr + n * gGrid_sN; + for (const auto d : c10::irange(out_D)) { + for (const auto h : c10::irange(out_H)) { + for (int64_t w = 0; w < out_W; ++w, gGrid_ptr_NDHW += gGrid_sW /* grad_grid is contiguous */ ) { + // get the corresponding input x, y, z coordinates from grid + const scalar_t *grid_ptr_NDHW = grid_ptr_N + d * grid_sD + h * grid_sH + w * grid_sW; + scalar_t ix = *grid_ptr_NDHW; + scalar_t iy = grid_ptr_NDHW[grid_sCoor]; + scalar_t iz = grid_ptr_NDHW[2 * grid_sCoor]; + + // multipliers for gradients on ix, iy, and iz + scalar_t gix_mult, giy_mult, giz_mult; + ix = grid_sampler_compute_source_index_set_grad(ix, inp_W, padding_mode, align_corners, &gix_mult); + iy = grid_sampler_compute_source_index_set_grad(iy, inp_H, padding_mode, align_corners, &giy_mult); + iz = grid_sampler_compute_source_index_set_grad(iz, inp_D, padding_mode, align_corners, &giz_mult); + + if (interpolation_mode == GridSamplerInterpolation::Bilinear) { + // get corner pixel values from (x, y, z) + // for 4d, we used north-east-south-west + // for 5d, we add top-bottom + int64_t ix_tnw = static_cast(std::floor(ix)); + int64_t iy_tnw = static_cast(std::floor(iy)); + int64_t iz_tnw = static_cast(std::floor(iz)); + + int64_t ix_tne = ix_tnw + 1; + int64_t iy_tne = iy_tnw; + int64_t iz_tne = iz_tnw; + + int64_t ix_tsw = ix_tnw; + int64_t iy_tsw = iy_tnw + 1; + int64_t iz_tsw = iz_tnw; + + int64_t ix_tse = ix_tnw + 1; + int64_t iy_tse = iy_tnw + 1; + int64_t iz_tse = iz_tnw; + + int64_t ix_bnw = ix_tnw; + int64_t iy_bnw = iy_tnw; + int64_t iz_bnw = iz_tnw + 1; + + int64_t ix_bne = ix_tnw + 1; + int64_t iy_bne = iy_tnw; + int64_t iz_bne = iz_tnw + 1; + + int64_t ix_bsw = ix_tnw; + int64_t iy_bsw = iy_tnw + 1; + int64_t iz_bsw = iz_tnw + 1; + + int64_t ix_bse = ix_tnw + 1; + int64_t iy_bse = iy_tnw + 1; + int64_t iz_bse = iz_tnw + 1; + + // get surfaces to each neighbor: + scalar_t tnw = (ix_bse - ix) * (iy_bse - iy) * (iz_bse - iz); + scalar_t tne = (ix - ix_bsw) * (iy_bsw - iy) * (iz_bsw - iz); + scalar_t tsw = (ix_bne - ix) * (iy - iy_bne) * (iz_bne - iz); + scalar_t tse = (ix - ix_bnw) * (iy - iy_bnw) * (iz_bnw - iz); + scalar_t bnw = (ix_tse - ix) * (iy_tse - iy) * (iz - iz_tse); + scalar_t bne = (ix - ix_tsw) * (iy_tsw - iy) * (iz - iz_tsw); + scalar_t bsw = (ix_tne - ix) * (iy - iy_tne) * (iz - iz_tne); + scalar_t bse = (ix - ix_tnw) * (iy - iy_tnw) * (iz - iz_tnw); + + scalar_t gix = static_cast(0), giy = static_cast(0), giz = static_cast(0); + const scalar_t *gOut_ptr_NCDHW = gOut_ptr + n * gOut_sN + d * gOut_sD + h * gOut_sH + w * gOut_sW; + const scalar_t *inp_ptr_NC = inp_ptr_N; + scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; + // calculate bilinear weighted pixel value and set output pixel + for (int64_t c = 0; c < C; ++c, gOut_ptr_NCDHW += gOut_sC, gInp_ptr_NC += gInp_sC, inp_ptr_NC += inp_sC) { + scalar_t gOut = *gOut_ptr_NCDHW; + + // calculate and set grad_input + if (input_requires_grad) { + safe_add_3d(gInp_ptr_NC, iz_tnw, iy_tnw, ix_tnw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tnw * gOut); + safe_add_3d(gInp_ptr_NC, iz_tne, iy_tne, ix_tne, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tne * gOut); + safe_add_3d(gInp_ptr_NC, iz_tsw, iy_tsw, ix_tsw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tsw * gOut); + safe_add_3d(gInp_ptr_NC, iz_tse, iy_tse, ix_tse, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tse * gOut); + safe_add_3d(gInp_ptr_NC, iz_bnw, iy_bnw, ix_bnw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bnw * gOut); + safe_add_3d(gInp_ptr_NC, iz_bne, iy_bne, ix_bne, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bne * gOut); + safe_add_3d(gInp_ptr_NC, iz_bsw, iy_bsw, ix_bsw, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bsw * gOut); + safe_add_3d(gInp_ptr_NC, iz_bse, iy_bse, ix_bse, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bse * gOut); + } + // calculate grad_grid + if (within_bounds_3d(iz_tnw, iy_tnw, ix_tnw, inp_D, inp_H, inp_W)) { + scalar_t tnw_val = inp_ptr_NC[iz_tnw * inp_sD + iy_tnw * inp_sH + ix_tnw * inp_sW]; + gix -= tnw_val * (iy_bse - iy) * (iz_bse - iz) * gOut; + giy -= tnw_val * (ix_bse - ix) * (iz_bse - iz) * gOut; + giz -= tnw_val * (ix_bse - ix) * (iy_bse - iy) * gOut; + } + if (within_bounds_3d(iz_tne, iy_tne, ix_tne, inp_D, inp_H, inp_W)) { + scalar_t tne_val = inp_ptr_NC[iz_tne * inp_sD + iy_tne * inp_sH + ix_tne * inp_sW]; + gix += tne_val * (iy_bsw - iy) * (iz_bsw - iz) * gOut; + giy -= tne_val * (ix - ix_bsw) * (iz_bsw - iz) * gOut; + giz -= tne_val * (ix - ix_bsw) * (iy_bsw - iy) * gOut; + } + if (within_bounds_3d(iz_tsw, iy_tsw, ix_tsw, inp_D, inp_H, inp_W)) { + scalar_t tsw_val = inp_ptr_NC[iz_tsw * inp_sD + iy_tsw * inp_sH + ix_tsw * inp_sW]; + gix -= tsw_val * (iy - iy_bne) * (iz_bne - iz) * gOut; + giy += tsw_val * (ix_bne - ix) * (iz_bne - iz) * gOut; + giz -= tsw_val * (ix_bne - ix) * (iy - iy_bne) * gOut; + } + if (within_bounds_3d(iz_tse, iy_tse, ix_tse, inp_D, inp_H, inp_W)) { + scalar_t tse_val = inp_ptr_NC[iz_tse * inp_sD + iy_tse * inp_sH + ix_tse * inp_sW]; + gix += tse_val * (iy - iy_bnw) * (iz_bnw - iz) * gOut; + giy += tse_val * (ix - ix_bnw) * (iz_bnw - iz) * gOut; + giz -= tse_val * (ix - ix_bnw) * (iy - iy_bnw) * gOut; + } + if (within_bounds_3d(iz_bnw, iy_bnw, ix_bnw, inp_D, inp_H, inp_W)) { + scalar_t bnw_val = inp_ptr_NC[iz_bnw * inp_sD + iy_bnw * inp_sH + ix_bnw * inp_sW]; + gix -= bnw_val * (iy_tse - iy) * (iz - iz_tse) * gOut; + giy -= bnw_val * (ix_tse - ix) * (iz - iz_tse) * gOut; + giz += bnw_val * (ix_tse - ix) * (iy_tse - iy) * gOut; + } + if (within_bounds_3d(iz_bne, iy_bne, ix_bne, inp_D, inp_H, inp_W)) { + scalar_t bne_val = inp_ptr_NC[iz_bne * inp_sD + iy_bne * inp_sH + ix_bne * inp_sW]; + gix += bne_val * (iy_tsw - iy) * (iz - iz_tsw) * gOut; + giy -= bne_val * (ix - ix_tsw) * (iz - iz_tsw) * gOut; + giz += bne_val * (ix - ix_tsw) * (iy_tsw - iy) * gOut; + } + if (within_bounds_3d(iz_bsw, iy_bsw, ix_bsw, inp_D, inp_H, inp_W)) { + scalar_t bsw_val = inp_ptr_NC[iz_bsw * inp_sD + iy_bsw * inp_sH + ix_bsw * inp_sW]; + gix -= bsw_val * (iy - iy_tne) * (iz - iz_tne) * gOut; + giy += bsw_val * (ix_tne - ix) * (iz - iz_tne) * gOut; + giz += bsw_val * (ix_tne - ix) * (iy - iy_tne) * gOut; + } + if (within_bounds_3d(iz_bse, iy_bse, ix_bse, inp_D, inp_H, inp_W)) { + scalar_t bse_val = inp_ptr_NC[iz_bse * inp_sD + iy_bse * inp_sH + ix_bse * inp_sW]; + gix += bse_val * (iy - iy_tnw) * (iz - iz_tnw) * gOut; + giy += bse_val * (ix - ix_tnw) * (iz - iz_tnw) * gOut; + giz += bse_val * (ix - ix_tnw) * (iy - iy_tnw) * gOut; + } + } + + // assuming grad_grid is contiguous + gGrid_ptr_NDHW[0] = gix_mult * gix; + gGrid_ptr_NDHW[1] = giy_mult * giy; + gGrid_ptr_NDHW[2] = giz_mult * giz; + } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { + int64_t ix_nearest = static_cast(std::nearbyint(ix)); + int64_t iy_nearest = static_cast(std::nearbyint(iy)); + int64_t iz_nearest = static_cast(std::nearbyint(iz)); + + // assign nearest neighbour pixel value to output pixel + const scalar_t *gOut_ptr_NCDHW = gOut_ptr + n * gOut_sN + d * gOut_sD + h * gOut_sH + w * gOut_sW; + if (input_requires_grad) { + scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; + for (int64_t c = 0; c < C; ++c, gOut_ptr_NCDHW += gOut_sC, gInp_ptr_NC += gInp_sC) { + // calculate and set grad_input + safe_add_3d(gInp_ptr_NC, iz_nearest, iy_nearest, ix_nearest, + gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, *gOut_ptr_NCDHW); + } + } + } + } + } + } + } + }); + return std::make_tuple(std::move(grad_input), std::move(grad_grid)); + } + +} // namespace + +static Tensor _grid_sampler_2d_cpu_quantized( + const Tensor& input, + const Tensor& grid, + int64_t interpolation_mode_, + int64_t padding_mode_, + bool align_corners) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_2d(input, grid); + + auto interpolation_mode = + static_cast(interpolation_mode_); + /* Bilinear interpolation is supported using the fact that we can perform + * linear interpolations on quantized values without rescaling. */ + TORCH_CHECK( + interpolation_mode == GridSamplerInterpolation::Bilinear, + "_grid_sampler_2d_cpu_quantized(): only bilinear interpolation supported") + auto padding_mode = static_cast(padding_mode_); + + int64_t N = input.size(0); + int64_t C = input.size(1); + int64_t inp_H = input.size(2); + int64_t inp_W = input.size(3); + int64_t out_H = grid.size(1); + int64_t out_W = grid.size(2); + uint8_t zero_point = input.q_zero_point(); + auto output = at::_empty_affine_quantized( + {N, C, out_H, out_W}, + at::device(c10::kCPU).dtype(c10::kQUInt8), + input.q_scale(), + zero_point); + int64_t inp_sN = input.stride(0); + int64_t inp_sC = input.stride(1); + int64_t inp_sH = input.stride(2); + int64_t inp_sW = input.stride(3); + int64_t grid_sN = grid.stride(0); + int64_t grid_sH = grid.stride(1); + int64_t grid_sW = grid.stride(2); + int64_t grid_sCoor = grid.stride(3); + int64_t out_sN = output.stride(0); + int64_t out_sC = output.stride(1); + int64_t out_sH = output.stride(2); + int64_t out_sW = output.stride(3); + const uint8_t* inp_ptr = input.const_data_ptr(); + uint8_t* out_ptr = output.data_ptr(); + const float* grid_ptr = grid.const_data_ptr(); + at::parallel_for(0, N, 0, [&](int64_t start, int64_t end) { + for (const auto n : c10::irange(start, end)) { + const float* grid_ptr_N = grid_ptr + n * grid_sN; + const uint8_t* inp_ptr_N = inp_ptr + n * inp_sN; + for (const auto h : c10::irange(out_H)) { + for (const auto w : c10::irange(out_W)) { + // get the corresponding input x, y, z coordinates from grid + const float* grid_ptr_NHW = grid_ptr_N + h * grid_sH + w * grid_sW; + float x = *grid_ptr_NHW; + float y = grid_ptr_NHW[grid_sCoor]; + + float ix = grid_sampler_compute_source_index( + x, inp_W, padding_mode, align_corners); + float iy = grid_sampler_compute_source_index( + y, inp_H, padding_mode, align_corners); + + // get corner pixel values from (x, y) + // for 4d, we use north-east-south-west + int64_t ix_nw = static_cast(std::floor(ix)); + int64_t iy_nw = static_cast(std::floor(iy)); + + int64_t ix_ne = ix_nw + 1; + int64_t iy_ne = iy_nw; + + int64_t ix_sw = ix_nw; + int64_t iy_sw = iy_nw + 1; + + int64_t ix_se = ix_nw + 1; + int64_t iy_se = iy_nw + 1; + + // get surfaces to each neighbor: + float nw = (ix_se - ix) * (iy_se - iy); + float ne = (ix - ix_sw) * (iy_sw - iy); + float sw = (ix_ne - ix) * (iy - iy_ne); + float se = (ix - ix_nw) * (iy - iy_nw); + + // calculate bilinear weighted pixel value and set output pixel + const uint8_t* inp_ptr_NC = inp_ptr_N; + uint8_t* out_ptr_NCHW = + out_ptr + n * out_sN + h * out_sH + w * out_sW; + for (int64_t c = 0; c < C; + ++c, out_ptr_NCHW += out_sC, inp_ptr_NC += inp_sC) { + float res = 0; + res += within_bounds_2d(iy_nw, ix_nw, inp_H, inp_W) + ? inp_ptr_NC[iy_nw * inp_sH + ix_nw * inp_sW] * nw + : zero_point * nw; + res += within_bounds_2d(iy_ne, ix_ne, inp_H, inp_W) + ? inp_ptr_NC[iy_ne * inp_sH + ix_ne * inp_sW] * ne + : zero_point * ne; + res += within_bounds_2d(iy_sw, ix_sw, inp_H, inp_W) + ? inp_ptr_NC[iy_sw * inp_sH + ix_sw * inp_sW] * sw + : zero_point * sw; + res += within_bounds_2d(iy_se, ix_se, inp_H, inp_W) + ? inp_ptr_NC[iy_se * inp_sH + ix_se * inp_sW] * se + : zero_point * se; + *out_ptr_NCHW = std::nearbyint(res); + } + } + } + } + }); + return output; +} + +Tensor _grid_sampler_2d_cpu_fallback(const Tensor& input, const Tensor& grid, + int64_t interpolation_mode_, + int64_t padding_mode_, + bool align_corners) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_2d(input, grid); + + auto interpolation_mode = static_cast(interpolation_mode_); + auto padding_mode = static_cast(padding_mode_); + using scalar_t = float; + + int64_t N = input.size(0); + int64_t C = input.size(1); + int64_t inp_H = input.size(2); + int64_t inp_W = input.size(3); + int64_t out_H = grid.size(1); + int64_t out_W = grid.size(2); + auto output = at::empty({N, C, out_H, out_W}, input.options()); + if (output.numel() == 0) { + return output; + } + int64_t inp_sN = input.stride(0); + int64_t inp_sC = input.stride(1); + int64_t inp_sH = input.stride(2); + int64_t inp_sW = input.stride(3); + int64_t grid_sN = grid.stride(0); + int64_t grid_sH = grid.stride(1); + int64_t grid_sW = grid.stride(2); + int64_t grid_sCoor = grid.stride(3); + int64_t out_sN = output.stride(0); + int64_t out_sC = output.stride(1); + int64_t out_sH = output.stride(2); + int64_t out_sW = output.stride(3); + const scalar_t *inp_ptr = input.const_data_ptr(); + scalar_t *out_ptr = output.data_ptr(); + const scalar_t *grid_ptr = grid.const_data_ptr(); + // loop over each output pixel + at::parallel_for(0, N, 0, [&](int64_t start, int64_t end) { + for (const auto n : c10::irange(start, end)) { + const scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; + const scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; + for (const auto h : c10::irange(out_H)) { + for (const auto w : c10::irange(out_W)) { + // get the corresponding input x, y, z coordinates from grid + const scalar_t *grid_ptr_NHW = grid_ptr_N + h * grid_sH + w * grid_sW; + scalar_t x = *grid_ptr_NHW; + scalar_t y = grid_ptr_NHW[grid_sCoor]; + + scalar_t ix = grid_sampler_compute_source_index(x, inp_W, padding_mode, align_corners); + scalar_t iy = grid_sampler_compute_source_index(y, inp_H, padding_mode, align_corners); + + if (interpolation_mode == GridSamplerInterpolation::Bilinear) { + // get corner pixel values from (x, y) + // for 4d, we use north-east-south-west + int64_t ix_nw = static_cast(std::floor(ix)); + int64_t iy_nw = static_cast(std::floor(iy)); + + int64_t ix_ne = ix_nw + 1; + int64_t iy_ne = iy_nw; + + int64_t ix_sw = ix_nw; + int64_t iy_sw = iy_nw + 1; + + int64_t ix_se = ix_nw + 1; + int64_t iy_se = iy_nw + 1; + + + // get surfaces to each neighbor: + scalar_t nw = (ix_se - ix) * (iy_se - iy); + scalar_t ne = (ix - ix_sw) * (iy_sw - iy); + scalar_t sw = (ix_ne - ix) * (iy - iy_ne); + scalar_t se = (ix - ix_nw) * (iy - iy_nw); + + // calculate bilinear weighted pixel value and set output pixel + const scalar_t *inp_ptr_NC = inp_ptr_N; + scalar_t *out_ptr_NCHW = out_ptr + n * out_sN + h * out_sH + w * out_sW; + for (int64_t c = 0; c < C; ++c, out_ptr_NCHW += out_sC, inp_ptr_NC += inp_sC) { + auto res = static_cast(0); + if (within_bounds_2d(iy_nw, ix_nw, inp_H, inp_W)) { + res += inp_ptr_NC[iy_nw * inp_sH + ix_nw * inp_sW] * nw; + } + if (within_bounds_2d(iy_ne, ix_ne, inp_H, inp_W)) { + res += inp_ptr_NC[iy_ne * inp_sH + ix_ne * inp_sW] * ne; + } + if (within_bounds_2d(iy_sw, ix_sw, inp_H, inp_W)) { + res += inp_ptr_NC[iy_sw * inp_sH + ix_sw * inp_sW] * sw; + } + if (within_bounds_2d(iy_se, ix_se, inp_H, inp_W)) { + res += inp_ptr_NC[iy_se * inp_sH + ix_se * inp_sW] * se; + } + *out_ptr_NCHW = res; + } + } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { + int64_t ix_nearest = static_cast(std::nearbyint(ix)); + int64_t iy_nearest = static_cast(std::nearbyint(iy)); + + // assign nearest neighbour pixel value to output pixel + scalar_t *out_ptr_NCHW = out_ptr + n * out_sN + h * out_sH + w * out_sW; + const scalar_t *inp_ptr_NC = inp_ptr_N; + for (int64_t c = 0; c < C; ++c, out_ptr_NCHW += out_sC, inp_ptr_NC += inp_sC) { + if (within_bounds_2d(iy_nearest, ix_nearest, inp_H, inp_W)) { + *out_ptr_NCHW = inp_ptr_NC[iy_nearest * inp_sH + ix_nearest * inp_sW]; + } else { + *out_ptr_NCHW = static_cast(0); + } + } + } else if (interpolation_mode == GridSamplerInterpolation::Bicubic) { + // grid_sampler_compute_source_index will "clip the value" of idx depends on the padding, + // which would cause calculation to be wrong, + // for example x = -0.1 -> ix = 0 for zero padding, but in bicubic ix = floor(x) = -1 + // There would be more problem in reflection padding, since the -1 and +1 direction is not fixed in boundary condition + ix = grid_sampler_unnormalize(x, inp_W, align_corners); + iy = grid_sampler_unnormalize(y, inp_H, align_corners); + + scalar_t ix_nw = std::floor(ix); + scalar_t iy_nw = std::floor(iy); + + const scalar_t tx = ix - ix_nw; + const scalar_t ty = iy - iy_nw; + + const scalar_t *inp_ptr_NC = inp_ptr_N; + scalar_t *out_ptr_NCHW = out_ptr + n * out_sN + h * out_sH + w * out_sW; + for (int64_t c = 0; c < C; ++c, out_ptr_NCHW += out_sC, inp_ptr_NC += inp_sC) { + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t coefficients[4]; + + // Interpolate 4 values in the x direction + for (const auto i : c10::irange(4)) { + coefficients[i] = cubic_interp1d( + get_value_bounded(inp_ptr_NC, ix_nw - 1, iy_nw - 1 + i, inp_W, inp_H, inp_sW, inp_sH, padding_mode, align_corners), + get_value_bounded(inp_ptr_NC, ix_nw + 0, iy_nw - 1 + i, inp_W, inp_H, inp_sW, inp_sH, padding_mode, align_corners), + get_value_bounded(inp_ptr_NC, ix_nw + 1, iy_nw - 1 + i, inp_W, inp_H, inp_sW, inp_sH, padding_mode, align_corners), + get_value_bounded(inp_ptr_NC, ix_nw + 2, iy_nw - 1 + i, inp_W, inp_H, inp_sW, inp_sH, padding_mode, align_corners), + tx); + } + + // Interpolate in the y direction + *out_ptr_NCHW = cubic_interp1d( + coefficients[0], + coefficients[1], + coefficients[2], + coefficients[3], + ty); + } + } + } + } + } + }); + return output; +} + +std::tuple +_grid_sampler_2d_cpu_fallback_backward(const Tensor& grad_output, + const Tensor& input, const Tensor& grid, + int64_t interpolation_mode_, + int64_t padding_mode_, + bool align_corners) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_2d(input, grid); + + const auto interpolation_mode = static_cast(interpolation_mode_); + const auto padding_mode = static_cast(padding_mode_); + using scalar_t = float; + + auto grad_input = at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + auto grad_grid = at::empty_like(grid, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + if (grid.numel() == 0 || input.numel() == 0) { + grad_grid.zero_(); + return std::make_tuple(std::move(grad_input), std::move(grad_grid)); + } + // If interpolation mode is Nearest, then grad_grid is not filled in the + // loop below. + if (interpolation_mode == GridSamplerInterpolation::Nearest) { + grad_grid.zero_(); + } + int64_t N = input.size(0); + int64_t C = input.size(1); + int64_t inp_H = input.size(2); + int64_t inp_W = input.size(3); + int64_t out_H = grid.size(1); + int64_t out_W = grid.size(2); + int64_t inp_sN = input.stride(0); + int64_t inp_sC = input.stride(1); + int64_t inp_sH = input.stride(2); + int64_t inp_sW = input.stride(3); + int64_t grid_sN = grid.stride(0); + int64_t grid_sH = grid.stride(1); + int64_t grid_sW = grid.stride(2); + int64_t grid_sCoor = grid.stride(3); + int64_t gOut_sN = grad_output.stride(0); + int64_t gOut_sC = grad_output.stride(1); + int64_t gOut_sH = grad_output.stride(2); + int64_t gOut_sW = grad_output.stride(3); + int64_t gInp_sN = grad_input.stride(0); + int64_t gInp_sC = grad_input.stride(1); + int64_t gInp_sH = grad_input.stride(2); + int64_t gInp_sW = grad_input.stride(3); + int64_t gGrid_sN = grad_grid.stride(0); + int64_t gGrid_sW = grad_grid.stride(2); + const scalar_t *inp_ptr = input.const_data_ptr(); + const scalar_t *grid_ptr = grid.const_data_ptr(); + const scalar_t *gOut_ptr = grad_output.const_data_ptr(); + scalar_t *gInp_ptr = grad_input.mutable_data_ptr(); + scalar_t *gGrid_ptr = grad_grid.data_ptr(); + // loop over each output pixel + at::parallel_for(0, N, 0, [&](int64_t start, int64_t end) { + for (const auto n : c10::irange(start, end)) { + const scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; + const scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; + scalar_t *gGrid_ptr_NHW = gGrid_ptr + n * gGrid_sN; + for (const auto h : c10::irange(out_H)) { + for (int64_t w = 0; w < out_W; ++w, gGrid_ptr_NHW += gGrid_sW /* grad_grid is contiguous */ ) { + // get the corresponding input x, y coordinates from grid + const scalar_t *grid_ptr_NHW = grid_ptr_N + h * grid_sH + w * grid_sW; + scalar_t x = *grid_ptr_NHW; + scalar_t y = grid_ptr_NHW[grid_sCoor]; + + // multipliers for gradients on ix, iy + scalar_t gix_mult{}, giy_mult{}; + scalar_t ix = grid_sampler_compute_source_index_set_grad(x, inp_W, padding_mode, align_corners, &gix_mult); + scalar_t iy = grid_sampler_compute_source_index_set_grad(y, inp_H, padding_mode, align_corners, &giy_mult); + + if (interpolation_mode == GridSamplerInterpolation::Bilinear) { + // get corner pixel values from (x, y) + // for 4d, we use north-east-south-west + int64_t ix_nw = static_cast(std::floor(ix)); + int64_t iy_nw = static_cast(std::floor(iy)); + + int64_t ix_ne = ix_nw + 1; + int64_t iy_ne = iy_nw; + + int64_t ix_sw = ix_nw; + int64_t iy_sw = iy_nw + 1; + + int64_t ix_se = ix_nw + 1; + int64_t iy_se = iy_nw + 1; + + // get surfaces to each neighbor: + scalar_t nw = (ix_se - ix) * (iy_se - iy); + scalar_t ne = (ix - ix_sw) * (iy_sw - iy); + scalar_t sw = (ix_ne - ix) * (iy - iy_ne); + scalar_t se = (ix - ix_nw) * (iy - iy_nw); + + scalar_t gix = static_cast(0), giy = static_cast(0); + const scalar_t *gOut_ptr_NCHW = gOut_ptr + n * gOut_sN + h * gOut_sH + w * gOut_sW; + scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; + const scalar_t *inp_ptr_NC = inp_ptr_N; + // calculate bilinear weighted pixel value and set output pixel + for (int64_t c = 0; c < C; ++c, gOut_ptr_NCHW += gOut_sC, gInp_ptr_NC += gInp_sC, inp_ptr_NC += inp_sC) { + scalar_t gOut = *gOut_ptr_NCHW; + + // calculate and set grad_input + safe_add_2d(gInp_ptr_NC, iy_nw, ix_nw, gInp_sH, gInp_sW, inp_H, inp_W, nw * gOut); + safe_add_2d(gInp_ptr_NC, iy_ne, ix_ne, gInp_sH, gInp_sW, inp_H, inp_W, ne * gOut); + safe_add_2d(gInp_ptr_NC, iy_sw, ix_sw, gInp_sH, gInp_sW, inp_H, inp_W, sw * gOut); + safe_add_2d(gInp_ptr_NC, iy_se, ix_se, gInp_sH, gInp_sW, inp_H, inp_W, se * gOut); + + // calculate grad_grid + if (within_bounds_2d(iy_nw, ix_nw, inp_H, inp_W)) { + scalar_t nw_val = inp_ptr_NC[iy_nw * inp_sH + ix_nw * inp_sW]; + gix -= nw_val * (iy_se - iy) * gOut; + giy -= nw_val * (ix_se - ix) * gOut; + } + if (within_bounds_2d(iy_ne, ix_ne, inp_H, inp_W)) { + scalar_t ne_val = inp_ptr_NC[iy_ne * inp_sH + ix_ne * inp_sW]; + gix += ne_val * (iy_sw - iy) * gOut; + giy -= ne_val * (ix - ix_sw) * gOut; + } + if (within_bounds_2d(iy_sw, ix_sw, inp_H, inp_W)) { + scalar_t sw_val = inp_ptr_NC[iy_sw * inp_sH + ix_sw * inp_sW]; + gix -= sw_val * (iy - iy_ne) * gOut; + giy += sw_val * (ix_ne - ix) * gOut; + } + if (within_bounds_2d(iy_se, ix_se, inp_H, inp_W)) { + scalar_t se_val = inp_ptr_NC[iy_se * inp_sH + ix_se * inp_sW]; + gix += se_val * (iy - iy_nw) * gOut; + giy += se_val * (ix - ix_nw) * gOut; + } + } + + // assuming grad_grid is contiguous + gGrid_ptr_NHW[0] = gix_mult * gix; + gGrid_ptr_NHW[1] = giy_mult * giy; + } else if (interpolation_mode == GridSamplerInterpolation::Nearest) { + int64_t ix_nearest = static_cast(std::nearbyint(ix)); + int64_t iy_nearest = static_cast(std::nearbyint(iy)); + + // assign nearest neighbour pixel value to output pixel + const scalar_t *gOut_ptr_NCHW = gOut_ptr + n * gOut_sN + h * gOut_sH + w * gOut_sW; + scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; + for (int64_t c = 0; c < C; ++c, gOut_ptr_NCHW += gOut_sC, gInp_ptr_NC += gInp_sC) { + // calculate and set grad_input + safe_add_2d(gInp_ptr_NC, iy_nearest, ix_nearest, gInp_sH, gInp_sW, + inp_H, inp_W, *gOut_ptr_NCHW); + } + } else if (interpolation_mode == GridSamplerInterpolation::Bicubic) { + + ix = grid_sampler_unnormalize_set_grad(x, inp_W, align_corners, &gix_mult); + iy = grid_sampler_unnormalize_set_grad(y, inp_H, align_corners, &giy_mult); + + scalar_t ix_nw = std::floor(ix); + scalar_t iy_nw = std::floor(iy); + + const scalar_t tx = ix - ix_nw; + const scalar_t ty = iy - iy_nw; + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t x_coeffs[4]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t y_coeffs[4]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t x_coeffs_grad[4]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t y_coeffs_grad[4]; + + get_cubic_upsample_coefficients(x_coeffs, tx); + get_cubic_upsample_coefficients(y_coeffs, ty); + get_cubic_coefficients_grad(x_coeffs_grad, tx); + get_cubic_coefficients_grad(y_coeffs_grad, ty); + + scalar_t gix = static_cast(0); + scalar_t giy = static_cast(0); + + const scalar_t *gOut_ptr_NCHW = gOut_ptr + n * gOut_sN + h * gOut_sH + w * gOut_sW; + scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; + const scalar_t *inp_ptr_NC = inp_ptr_N; + + for (int64_t c = 0; c < C; ++c, gOut_ptr_NCHW += gOut_sC, gInp_ptr_NC += gInp_sC, inp_ptr_NC+= inp_sC) { + scalar_t gOut = *gOut_ptr_NCHW; + + for (const auto i : c10::irange(4)) { + for (const auto j : c10::irange(4)) { + + // set input gradient + add_value_bounded(gInp_ptr_NC, ix_nw - 1 + i, iy_nw - 1 + j, + inp_W, inp_H, gInp_sW, gInp_sH, gOut * x_coeffs[i] * y_coeffs[j], padding_mode, align_corners); + + // set grid gradient + scalar_t val = get_value_bounded(inp_ptr_NC, ix_nw - 1 + i, iy_nw - 1 + j, + inp_W, inp_H, inp_sW, inp_sH, padding_mode, align_corners); + + gix -= val * x_coeffs_grad[i] * y_coeffs[j] * gOut; + giy -= val * y_coeffs_grad[j] * x_coeffs[i] * gOut; + } + } + } + gGrid_ptr_NHW[0] = gix_mult * gix; + gGrid_ptr_NHW[1] = giy_mult * giy; + } + } + } + } + }); + return std::make_tuple(std::move(grad_input), std::move(grad_grid)); +} + +Tensor grid_sampler_2d_cpu(const Tensor& input, const Tensor& grid, + int64_t interpolation_mode, int64_t padding_mode, + bool align_corners) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_2d(input, grid); + + if (input.scalar_type() == kQUInt8) { + return native::_grid_sampler_2d_cpu_quantized( + input, grid, interpolation_mode, padding_mode, align_corners); + } + // AVX gather instructions use signed 32-bit offsets to gather float values. + // Check for possible overflow and fallback to scalar implementation + if (input.scalar_type() == kFloat) { + auto sizes = input.sizes(); + auto strides = input.strides(); + const auto grid_sW = grid.strides()[2]; + // NOTE: Gather offsets are only used for the input H, W dimensions + // or only for strided access to the grid tensor + auto max_gather_offset = std::max( + (sizes[2] - 1) * strides[2] + (sizes[3] - 1) * strides[3], + grid_sW * (vec::Vectorized::size() - 1)); + + if (max_gather_offset > std::numeric_limits::max()) { + return native::_grid_sampler_2d_cpu_fallback( + input, grid, interpolation_mode, padding_mode, align_corners); + } + } + + auto in_size = input.sizes(); + auto grid_size = grid.sizes(); + auto output = at::empty( + {in_size[0], in_size[1], grid_size[1], grid_size[2]}, input.options()); + grid_sampler_2d_cpu_kernel( + kCPU, output, input, grid, interpolation_mode, padding_mode, align_corners); + return output; +} + +DEFINE_DISPATCH(grid_sampler_2d_cpu_kernel); + + +Tensor grid_sampler_3d_cpu(const Tensor& input, const Tensor& grid, + int64_t interpolation_mode, int64_t padding_mode, + bool align_corners) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_3d(input, grid, interpolation_mode); + + return AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "grid_sampler3d_cpu", [&] { + return grid_sampler_3d_cpu_impl( + input, grid, static_cast(interpolation_mode), + static_cast(padding_mode), align_corners); + }); +} + +std::tuple +grid_sampler_2d_backward_cpu(const Tensor& grad_output, const Tensor& input, const Tensor& grid, + int64_t interpolation_mode, int64_t padding_mode, bool align_corners, + std::array output_mask) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_2d(input, grid); + + // AVX gather instructions use signed 32-bit offsets to gather float values. + // Check for possible overflow and fallback to scalar implementation + if (input.scalar_type() == kFloat) { + auto isizes = input.sizes(); + auto istrides = input.strides(); + auto gsizes = grad_output.sizes(); + auto gstrides = grad_output.strides(); + const auto grid_sW = grid.strides()[2]; + // NOTE: Gather offsets are only used for the height and width dimensions + auto max_gather_offset = std::max( + { + (isizes[2] - 1) * istrides[2] + (isizes[3] - 1) * istrides[3], + (gsizes[2] - 1) * gstrides[2] + (gsizes[3] - 1) * gstrides[3], + grid_sW * (vec::Vectorized::size() - 1)}); + + if (max_gather_offset > std::numeric_limits::max()) { + return native::_grid_sampler_2d_cpu_fallback_backward( + grad_output, input, grid, interpolation_mode, padding_mode, align_corners); + } + } + + auto input_requires_grad = output_mask[0]; + Tensor grad_input = ([&]() { + if (input_requires_grad) { + return at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + } else { + return Tensor(); + } + })(); + auto grad_grid = at::empty_like(grid, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + grid_sampler_2d_backward_cpu_kernel( + kCPU, grad_input, grad_grid, grad_output, input, grid, + interpolation_mode, padding_mode, align_corners, output_mask); + return std::make_tuple(std::move(grad_input), std::move(grad_grid)); +} + +DEFINE_DISPATCH(grid_sampler_2d_backward_cpu_kernel); + +std::tuple +grid_sampler_3d_backward_cpu(const Tensor& grad_output, const Tensor& input, const Tensor& grid, + int64_t interpolation_mode, int64_t padding_mode, bool align_corners, + std::array output_mask) { + // See NOTE [ grid_sampler Native Functions ]. + // Add checks here in case this is called instead of grid_sampler. + check_grid_sampler_common(input, grid); + check_grid_sampler_3d(input, grid, interpolation_mode); + + return AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "grid_sampler_3d_backward_cpu", [&] { + return grid_sampler_3d_backward_cpu_impl( + grad_output, input, grid, + static_cast(interpolation_mode), + static_cast(padding_mode), + align_corners, output_mask); + }); +} + +// See NOTE [ grid_sampler Native Functions ]. +Tensor grid_sampler( + const Tensor& input, + const Tensor& grid, + int64_t interpolation_mode, + int64_t padding_mode, + bool align_corners +) { + if (cond_cudnn_grid_sampler(input, grid) && + static_cast(interpolation_mode) == + GridSamplerInterpolation::Bilinear && + static_cast(padding_mode) == + GridSamplerPadding::Zeros && + align_corners) { + return cudnn_grid_sampler(input, grid); + } + + if (input.dim() == 4) { + return at::grid_sampler_2d( + input, grid, interpolation_mode, padding_mode, align_corners); + } else { + return at::grid_sampler_3d( + input, grid, interpolation_mode, padding_mode, align_corners); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/GridSampler.h b/western_ai/usa/pytorch/aten/src/ATen/native/GridSampler.h new file mode 100644 index 0000000000000000000000000000000000000000..92e61f75539dc9a5a45a966170bb0827de82feda --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/GridSampler.h @@ -0,0 +1,298 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace at::native { + +using detail::GridSamplerInterpolation; +using detail::GridSamplerPadding; + +// Unnormalizes a coordinate from the -1 to +1 scale to its pixel index value, +// where we view each pixel as an area between (idx - 0.5) and (idx + 0.5). +// if align_corners: -1 and +1 get sent to the centers of the corner pixels +// -1 --> 0 +// +1 --> (size - 1) +// scale_factor = (size - 1) / 2 +// if not align_corners: -1 and +1 get sent to the image edges +// -1 --> -0.5 +// +1 --> (size - 1) + 0.5 == size - 0.5 +// scale_factor = size / 2 +template +static inline scalar_t grid_sampler_unnormalize(scalar_t coord, int64_t size, + bool align_corners) { + if (align_corners) { + // unnormalize coord from [-1, 1] to [0, size - 1] + return ((coord + 1) / 2) * (size - 1); + } else { + // unnormalize coord from [-1, 1] to [-0.5, size - 0.5] + return ((coord + 1) * size - 1) / 2; + } +} + +// grid_sampler_unnormalize_set_grad works the same as grid_sampler_unnormalize +// except that it also returns the `d output / d input` via pointer argument +// `grad_in`. +// This is useful in the backward pass of grid_sampler. +template +static inline scalar_t grid_sampler_unnormalize_set_grad(scalar_t coord, int64_t size, + bool align_corners, scalar_t *grad_in) { + if (align_corners) { + // unnormalize coord from [-1, 1] to [0, size - 1] + *grad_in = static_cast(size - 1) / 2; + return ((coord + 1) / 2) * (size - 1); + } else { + // unnormalize coord from [-1, 1] to [-0.5, size - 0.5] + *grad_in = static_cast(size) / 2; + return ((coord + 1) * size - 1) / 2; + } +} + +// Clips coordinates to between 0 and clip_limit - 1 +template +static inline scalar_t clip_coordinates(scalar_t in, int64_t clip_limit) { + return std::min(static_cast(clip_limit - 1), std::max(in, static_cast(0))); +} + +// clip_coordinates_set_grad works similarly to clip_coordinates except that +// it also returns the `d output / d input` via pointer argument `grad_in`. +// This is useful in the backward pass of grid_sampler. +template +static inline scalar_t clip_coordinates_set_grad(scalar_t in, int64_t clip_limit, + scalar_t *grad_in) { + // Note that it is important for the gradient calculation that borders + // are considered out of bounds. + if (in <= static_cast(0)) { + *grad_in = static_cast(0); + return static_cast(0); + } else { + scalar_t max = static_cast(clip_limit - 1); + if (in >= max) { + *grad_in = static_cast(0); + return max; + } else { + *grad_in = static_cast(1); + return in; + } + } +} + +// Reflects coordinates until they fall between low and high (inclusive). +// The bounds are passed as twice their value so that half-integer values +// can be represented as ints. +template +static inline scalar_t reflect_coordinates(scalar_t in, int64_t twice_low, + int64_t twice_high) { + if (twice_low == twice_high) { + return static_cast(0); + } + scalar_t min = static_cast(twice_low) / 2; + scalar_t span = static_cast(twice_high - twice_low) / 2; + in = std::fabs(in - min); + // `fmod` returns same sign as `in`, which is positive after the `fabs` above. + scalar_t extra = std::fmod(in, span); + int flips = static_cast(std::floor(in / span)); + if (flips % 2 == 0) { + return extra + min; + } else { + return span - extra + min; + } +} + +// reflect_coordinates_set_grad works similarly to reflect_coordinates except +// that it also returns the `d output / d input` via pointer argument +// `grad_in`. +// This is useful in the backward pass of grid_sampler. +template +static inline scalar_t reflect_coordinates_set_grad(scalar_t in, int64_t twice_low, + int64_t twice_high, scalar_t *grad_in) { + if (twice_low == twice_high) { + *grad_in = static_cast(0); + return static_cast(0); + } + int grad_in_mult_; + scalar_t min = static_cast(twice_low) / 2; + scalar_t span = static_cast(twice_high - twice_low) / 2; + in = in - min; + if (in < static_cast(0)) { + grad_in_mult_ = -1; + in = -in; + } else { + grad_in_mult_ = 1; + } + // `fmod` returns same sign as `in`, which is positive after the `if` above. + scalar_t extra = std::fmod(in, span); + int flips = static_cast(std::floor(in / span)); + if (flips % 2 == 0) { + *grad_in = static_cast(grad_in_mult_); + return extra + min; + } else { + *grad_in = static_cast(-grad_in_mult_); + return span - extra + min; + } +} + +// Mapping the out-of-boundary points back into boundary +// This would only affect padding_mode=border or reflection +template +static inline scalar_t compute_coordinates(scalar_t coord, int64_t size, + GridSamplerPadding padding_mode, + bool align_corners) { + if (padding_mode == GridSamplerPadding::Border) { + // clip coordinates to image borders + coord = clip_coordinates(coord, size); + } else if (padding_mode == GridSamplerPadding::Reflection) { + // reflect coordinates by image borders + if (align_corners) { + coord = reflect_coordinates(coord, 0, 2*(size - 1)); + } else { + coord = reflect_coordinates(coord, -1, 2*size - 1); + } + // clip coordinates to image borders + coord = clip_coordinates(coord, size); + } + return coord; +} + +// Computes the pixel source index value for a grid coordinate +template +static inline scalar_t grid_sampler_compute_source_index( + scalar_t coord, + int64_t size, + GridSamplerPadding padding_mode, + bool align_corners) { + coord = grid_sampler_unnormalize(coord, size, align_corners); + coord = compute_coordinates(coord, size, padding_mode, align_corners); + return coord; +} + +// grid_sampler_compute_source_index_set_grad works similarly to +// grid_sampler_compute_source_index except that it also returns the +// `d output / d input` via pointer argument `grad_in`. +// This is useful in the backward pass of grid_sampler. +template +static inline scalar_t grid_sampler_compute_source_index_set_grad( + scalar_t coord, + int64_t size, + GridSamplerPadding padding_mode, + bool align_corners, + scalar_t *grad_in) { + scalar_t grad_clip, grad_refl; + coord = grid_sampler_unnormalize_set_grad(coord, size, align_corners, grad_in); + if (padding_mode == GridSamplerPadding::Border) { + // clip coordinates to image borders + coord = clip_coordinates_set_grad(coord, size, &grad_clip); + *grad_in = (*grad_in) * grad_clip; + } else if (padding_mode == GridSamplerPadding::Reflection) { + // reflect coordinates by image borders + if (align_corners) { + coord = reflect_coordinates_set_grad(coord, 0, 2*(size - 1), &grad_refl); + } else { + coord = reflect_coordinates_set_grad(coord, -1, 2*size - 1, &grad_refl); + } + // clip coordinates to image borders + coord = clip_coordinates_set_grad(coord, size, &grad_clip); + *grad_in = (*grad_in) * grad_refl * grad_clip; + } + return coord; +} + +static inline bool within_bounds_2d(int64_t h, int64_t w, int64_t H, int64_t W) { + return h >= 0 && h < H && w >= 0 && w < W; +} + +static inline bool within_bounds_3d(int64_t d, int64_t h, int64_t w, int64_t D, int64_t H, int64_t W) { + return d >= 0 && d < D && h >= 0 && h < H && w >= 0 && w < W; +} + +template +static inline scalar_t get_value_bounded( + const scalar_t* data, + scalar_t x, + scalar_t y, + int64_t W, + int64_t H, + int64_t sW, + int64_t sH, + GridSamplerPadding padding_mode, + bool align_corners) { + + x = compute_coordinates(x, W, padding_mode, align_corners); + y = compute_coordinates(y, H, padding_mode, align_corners); + + int64_t ix = static_cast(x); + int64_t iy = static_cast(y); + + if (within_bounds_2d(iy, ix, H, W)) { + return data[iy * sH + ix * sW]; + } + return static_cast(0); +} + +template +static inline void safe_add_2d(scalar_t *data, int64_t h, int64_t w, + int64_t sH, int64_t sW, int64_t H, int64_t W, + scalar_t delta) { + if (within_bounds_2d(h, w, H, W)) { + data[h * sH + w * sW] += delta; + } +} + +template +static inline void safe_add_3d(scalar_t *data, int64_t d, int64_t h, int64_t w, + int64_t sD, int64_t sH, int64_t sW, + int64_t D, int64_t H, int64_t W, + scalar_t delta) { + if (within_bounds_3d(d, h, w, D, H, W)) { + data[d * sD + h * sH + w * sW] += delta; + } +} + +template +static inline void add_value_bounded( + scalar_t* data, + scalar_t x, + scalar_t y, + int64_t W, + int64_t H, + int64_t sW, + int64_t sH, + scalar_t delta, + GridSamplerPadding padding_mode, + bool align_corners) { + + x = compute_coordinates(x, W, padding_mode, align_corners); + y = compute_coordinates(y, H, padding_mode, align_corners); + + int64_t ix = static_cast(x); + int64_t iy = static_cast(y); + + safe_add_2d(data, iy, ix, sH, sW, H, W, delta); +} + +// Calculate the differential of the cubic convolution, i.e. `d coeff / d x` +template +static inline void get_cubic_coefficients_grad( + scalar_t coeffs[4], + scalar_t t) { + + // Must be the same as forward calculation in + // aten/src/ATen/native/UpSample.h:get_cubic_upsample_coefficients + scalar_t A = -0.75; + + scalar_t x; + x = -1 - t; // 1 < x = |-1 - tx| < 2 + coeffs[0] = (-3 * A * x - 10 * A ) * x - 8 * A; + x = -t; // x = |0 - tx| <= 1 + coeffs[1] = (-3 * (A + 2) * x - 2 * (A + 3)) * x; + x = 1 - t; // x = |1 - tx| <= 1 + coeffs[2] = (3 * (A + 2) * x - 2 * (A + 3)) * x; + x = 2 - t; // 1 < x = |2 - tx| < 2 + coeffs[3] = (3 * A * x - 10 * A) * x + 8 * A; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/GridSamplerUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/GridSamplerUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..c0b5cc1ac1654b4b7bebcd84763a81e1665821dc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/GridSamplerUtils.h @@ -0,0 +1,111 @@ +#pragma once + +// See NOTE: [Tensor vs. TensorBase] +// https://github.com/pytorch/pytorch/pull/66979 +#include +#include +#include + +namespace at::native { + +namespace detail { + +enum class GridSamplerInterpolation {Bilinear, Nearest, Bicubic}; +enum class GridSamplerPadding {Zeros, Border, Reflection}; + +} // namespace detail + +using detail::GridSamplerInterpolation; +using detail::GridSamplerPadding; + +// See NOTE [ grid_sampler Native Functions ]. +inline void check_grid_sampler_common( + const TensorBase& input, + const TensorBase& grid +) { + auto input_opt = input.options(); + auto grid_opt = grid.options(); + + TORCH_CHECK( + input.defined(), + "grid_sampler(): expected input to not be undefined"); + TORCH_CHECK( + grid.defined(), + "grid_sampler(): expected grid to not be undefined"); + TORCH_CHECK( + input_opt.device() == grid_opt.device(), + "grid_sampler(): expected input and grid to be on same device, but input " + "is on ", input_opt.device(), " and grid is on ", grid_opt.device()); + TORCH_CHECK( + input_opt.layout() == kStrided && grid_opt.layout() == kStrided, + "grid_sampler(): expected input and grid to have torch.strided layout, but " + "input has ", input_opt.layout(), " and grid has ", grid_opt.layout()); + TORCH_CHECK( + input.size(0) == grid.size(0), + "grid_sampler(): expected grid and input to have same batch size, but got " + "input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes()); + TORCH_CHECK( + grid.size(-1) == input.dim() - 2, + "grid_sampler(): expected grid to have size ", input.dim() - 2, " in last " + "dimension, but got grid with sizes ", grid.sizes()); + + for (const auto i : c10::irange(2, input.dim())) { + TORCH_CHECK(input.size(i) > 0, + "grid_sampler(): expected input to have non-empty spatial dimensions, " + "but input has sizes ", input.sizes(), " with dimension ", i, " being " + "empty"); + } +} + +// See NOTE [ grid_sampler Native Functions ]. +inline void check_grid_sampler_2d( + const TensorBase& input, + const TensorBase& grid +) { + TORCH_CHECK( + input.dim() == 4 && input.dim() == grid.dim(), + "grid_sampler(): expected 4D input and grid with same number of " + "dimensions, but got input with sizes ", input.sizes(), + " and grid with sizes ", grid.sizes()); +} + +// See NOTE [ grid_sampler Native Functions ]. +inline void check_grid_sampler_3d( + const TensorBase& input, + const TensorBase& grid, + int64_t interpolation_mode +) { + TORCH_CHECK( + input.dim() == 5 && input.dim() == grid.dim(), + "grid_sampler(): expected 5D input and grid with same number of " + "dimensions, but got input with sizes ", input.sizes(), + " and grid with sizes ", grid.sizes()); + TORCH_CHECK( + !(input.dim() == 5 && + static_cast(interpolation_mode) == + GridSamplerInterpolation::Bicubic), + "grid_sampler(): bicubic interpolation only supports 4D input"); +} + +// See NOTE [ grid_sampler Native Functions ]. +// cudnn does not support inputs larger than 1024. +inline bool cond_cudnn_grid_sampler( + const TensorBase& input, + const TensorBase& grid +) { + auto st = input.scalar_type(); + if (!(st == kDouble || st == kFloat || st == kHalf)) + return false; + st = grid.scalar_type(); + if (!(st == kDouble || st == kFloat || st == kHalf)) + return false; + return ( + at::native::cudnn_is_acceptable(input) && + at::native::cudnn_is_acceptable(grid) && + at::native::canUse32BitIndexMath(input) && + at::native::canUse32BitIndexMath(grid) && + input.dim() == 4 && + input.sym_size(1) <= 1024); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/GroupedMMUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/GroupedMMUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..07708409c3895367d85d8bdc0483c3eb3c264087 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/GroupedMMUtils.h @@ -0,0 +1,175 @@ +#pragma once + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +inline bool check_valid_strides_and_return_transposed(const Tensor& mat) { + IntArrayRef tensor_strides = mat.strides(); + IntArrayRef tensor_sizes = mat.sizes(); + int end_dim = mat.dim() - 1; + int alignment = 16 / mat.element_size(); + bool is_cpu = mat.device().is_cpu(); + TORCH_CHECK(is_cpu || uint64_t(mat.data_ptr()) % 16 == 0, "expected data_ptr to be aligned to 16 bytes"); + if ((tensor_strides[end_dim - 1] == 1) && (tensor_strides[end_dim] >= std::max(1, tensor_sizes[end_dim - 1]))) { + TORCH_CHECK(tensor_strides[end_dim] % alignment == 0, "strides should be multiple of 16 bytes"); + return true; + } else if ((tensor_strides[end_dim] == 1) && (tensor_strides[end_dim - 1] >= std::max(1, tensor_sizes[end_dim]))) { + TORCH_CHECK(tensor_strides[end_dim - 1] % alignment == 0, "strides should be multiple of 16 bytes"); + return false; + } else { + TORCH_CHECK(false, "Invalid strides/sizes, got ", mat.strides(), " for strides and ", mat.sizes(), " for sizes"); + } +} + +inline at::Tensor create_grouped_gemm_output_tensor(const Tensor& mat_a, +const Tensor& mat_b, +const std::optional& offs, +c10::ScalarType out_dtype +) { + c10::SmallVector out_size; + const bool a_is_2d = mat_a.dim() == 2; + const bool b_is_2d = mat_b.dim() == 2; + if (a_is_2d) { + if (b_is_2d) { + out_size = {offs->size(0), mat_a.size(0), mat_b.size(1)}; + } else { + TORCH_CHECK(offs->size(0) == mat_b.size(0), "matrix batch sizes have to match"); + out_size = {mat_a.size(0), mat_b.size(-1)}; + } + } else { + if (b_is_2d) { + // this case is not actually encountered for MoE gemms + TORCH_CHECK(offs->size(0) == mat_a.size(0), "matrix batch sizes have to match"); + out_size = {mat_a.size(1), mat_b.size(1)}; + } else { // regular bmm + TORCH_CHECK(mat_a.size(0) == mat_b.size(0), "batched dimension has to match"); + out_size = {mat_a.size(0), mat_a.size(1), mat_b.size(-1)}; + } + } + + #ifndef USE_ROCM + // For TMA transfers, strides of output tensor have to be either + // 1, or aligned to 16 bytes. + const auto last_dim = out_size.size() - 1; + const auto alignment = 16 / c10::elementSize(out_dtype); + const int64_t size_padded = (out_size[last_dim] + alignment - 1) / alignment * alignment; + std::vector out_stride; + if (a_is_2d != b_is_2d) { + out_stride = {size_padded, 1}; + } else { + out_stride = {out_size[1] * size_padded, size_padded, 1}; + } + return at::empty_strided(out_size, out_stride, mat_a.options().dtype(out_dtype)); + #else + // For ROCm 2D-2D case (output is 3D), zero-initialize to handle K=0 or small K + // groups correctly. When K=0, the mathematically correct result is zeros, + // but CK kernel may not write to the output region. + if (a_is_2d && b_is_2d) { + return at::zeros(out_size, mat_a.options().dtype(out_dtype)); + } + return at::empty(out_size, mat_a.options().dtype(out_dtype)); + #endif +} + +inline void _grouped_mm_validate_inputs(const Tensor& mat_a, const Tensor& mat_b, +const std::optional& offs, +const std::optional& bias, +std::optional out_dtype) { + TORCH_CHECK((mat_a.dtype() == at::kBFloat16) || (mat_a.dtype() == at::kFloat) || (mat_a.dtype() == at::kHalf), "Expected mat_a to be Float32, BFloat16 or Float16 matrix, got ", mat_a.scalar_type()); + TORCH_CHECK((mat_b.dtype() == at::kBFloat16) || (mat_b.dtype() == at::kFloat) || (mat_b.dtype() == at::kHalf), "Expected mat_b to be Float32, BFloat16 or Float16 matrix, got ", mat_b.scalar_type()); + TORCH_CHECK(mat_a.dim() == 2 || mat_a.dim() == 3, "mat_a has to be 2 or 3d"); + TORCH_CHECK(mat_b.dim() == 2 || mat_b.dim() == 3, "mat_b has to be 2 or 3d"); + const bool a_is_2d = mat_a.dim() == 2; + const bool b_is_2d = mat_b.dim() == 2; + if (!a_is_2d || !b_is_2d) { + TORCH_CHECK(mat_a.size(-1) == mat_b.size(-2), "contraction dimension of mat_a and mat_b must match"); + } + + // check that the strides are valid, the fn will throw an error if not + check_valid_strides_and_return_transposed(mat_a); + check_valid_strides_and_return_transposed(mat_b); + TORCH_CHECK(offs.has_value() == (a_is_2d || b_is_2d), "Have to provide offsets if there is a 2d matrix, or no offset if both matrices are 3d"); + + if (offs.has_value()) { + TORCH_CHECK(offs->dim() == 1, "offs has to be 1D"); + TORCH_CHECK(offs->dtype() == at::kInt, "Offsets have to be int32"); + } + TORCH_CHECK(!bias.has_value(), "Bias not supported yet"); +} + +inline c10::ScalarType _resolve_grouped_mm_out_dtype(const Tensor& mat_a, [[maybe_unused]] const Tensor& mat_b, +std::optional out_dtype) { + const auto out_dtype_ = out_dtype.value_or(mat_a.scalar_type()); + // TODO(future PR): enable float32 output dtype for bfloat16 and float16 inputs + TORCH_CHECK(out_dtype_ == mat_a.dtype(), "Grouped gemm output dtype must match `mat_a` dtype"); + return out_dtype_; +} + + +inline void _grouped_mm_fallback(const Tensor& mat_a, const Tensor& mat_b, +const std::optional& offs, +const std::optional& bias, +std::optional out_dtype, +Tensor out) { + LOG(INFO) << "fallback path for `torch._grouped_mm`, performance may not be optimal"; + const bool a_is_2d = mat_a.dim() == 2; + const bool b_is_2d = mat_b.dim() == 2; + if (a_is_2d && !b_is_2d) { + // 2d x 3d with offsets + int group_start_idx = 0; + auto offs_cpu = offs.value().cpu(); + for (int group_idx = 0; group_idx < offs_cpu.size(0); group_idx++) { + int group_end_idx = offs_cpu[group_idx].item(); + auto mat_a_slice = mat_a.slice(0, group_start_idx, group_end_idx); + auto out_slice = out.slice(0, group_start_idx, group_end_idx); + at::mm_out(out_slice, mat_a_slice, mat_b[group_idx]); + group_start_idx = group_end_idx; + } + + } else if (!a_is_2d && b_is_2d) { + // 3d x 2d with offsets + int group_start_idx = 0; + auto offs_cpu = offs.value().cpu(); + for (int group_idx = 0; group_idx < offs_cpu.size(0); group_idx++) { + int group_end_idx = offs_cpu[group_idx].item(); + auto mat_b_slice = mat_b.slice(1, group_start_idx, group_end_idx); + auto out_slice = out.slice(1, group_start_idx, group_end_idx); + at::mm_out(out_slice, mat_a[group_idx], mat_b_slice); + group_start_idx = group_end_idx; + } + + } else if (a_is_2d && b_is_2d) { + // 2d x 2d with offsets + int group_start_idx = 0; + auto offs_cpu = offs.value().cpu(); + for (int group_idx = 0; group_idx < offs_cpu.size(0); group_idx++) { + int group_end_idx = offs_cpu[group_idx].item(); + auto mat_a_slice = mat_a.slice(1, group_start_idx, group_end_idx); + auto mat_b_slice = mat_b.slice(0, group_start_idx, group_end_idx); + auto out_slice = out[group_idx]; + at::mm_out(out_slice, mat_a_slice, mat_b_slice); + group_start_idx = group_end_idx; + } + + } else { + // 3d x 3d without offsets - regular bmm + at::bmm_out(out, mat_a, mat_b); + } +} + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Histogram.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Histogram.cpp new file mode 100644 index 0000000000000000000000000000000000000000..862a4891413af1a6f40300498edfa187a0300b1a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Histogram.cpp @@ -0,0 +1,480 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Implements a numpy-like histogramdd function running on cpu + * https://numpy.org/doc/stable/reference/generated/numpy.histogramdd.html + * + * See the docstr for torch.histogramdd in torch/functional.py for further explanation. + * + * - torch.histogramdd(input, bins, range=None, weight=None, density=False) + * input - tensor with shape (M, N). input is interpreted as M coordinates in N-dimensional space. + * If a tensor with more than 2 dimensions is passed, all but the last dimension will be flattened. + * bins - int[] of length N or tensor list of length N. If int[], defines the number of equal-width bins + * in each dimension. If tensor list, defines the sequences of bin edges, including rightmost edges, + * for each dimension. + * range - float[] of length 2 * N, optional. If specified, defines the leftmost and rightmost bin edges + * for each dimension. + * weight - tensor, optional. If provided, weight should have the same shape as input excluding its last dimension. + * Each N-dimensional value in input contributes its associated weight towards its bin's result. + * If weight is not specified, each value has weight 1 by default. + * density - bool, optional. If false (default), the result will contain the total count (weight) in each bin. + * If True, each count (weight) is divided by the total count (total weight), then divided by the + * volume of its associated bin. + * + * Returns: + * hist - N-dimensional tensor containing the values of the histogram. + * bin_edges - tensor list of length N containing the edges of the histogram bins in each dimension. + * Bins include their left edge and exclude their right edge, with the exception of the + * rightmost bin in each dimension which includes both of its edges. + * + * Restrictions are defined in histogram_check_inputs() and in select_outer_bin_edges(). + */ + +namespace at::native { + +DEFINE_DISPATCH(histogramdd_stub); +DEFINE_DISPATCH(histogramdd_linear_stub); +DEFINE_DISPATCH(histogram_select_outer_bin_edges_stub); + +namespace { + +/* Checks properties of input tensors input, bins, and weight. + */ +void histogramdd_check_inputs(const Tensor& input, const TensorList& bins, const std::optional& weight) { + TORCH_CHECK(input.dim() >= 2, "torch.histogramdd: input tensor should have at least 2 dimensions, but got ", + input.dim()); + + const int64_t N = input.size(-1); + + TORCH_CHECK(static_cast(bins.size()) == N, "torch.histogramdd: expected ", N, " sequences of bin edges for a ", N, + "-dimensional histogram but got ", bins.size()); + + auto input_dtype = input.dtype(); + for (const auto dim : c10::irange(N)) { + const Tensor& dim_bins = bins[dim]; + + auto bins_dtype = dim_bins.dtype(); + TORCH_CHECK(input_dtype == bins_dtype, "torch.histogramdd: input tensor and bins tensors should", + " have the same dtype, but got input with dtype ", input_dtype, + " and bins for dimension ", dim, " with dtype ", bins_dtype); + + const int64_t dim_bins_dim = dim_bins.dim(); + TORCH_CHECK(dim_bins_dim == 1, "torch.histogramdd: bins tensor should have one dimension,", + " but got ", dim_bins_dim, " dimensions in the bins tensor for dimension ", dim); + + const int64_t numel = dim_bins.numel(); + TORCH_CHECK(numel > 0, "torch.histogramdd: bins tensor should have at least 1 element,", + " but got ", numel, " elements in the bins tensor for dimension ", dim); + } + + if (weight.has_value()) { + TORCH_CHECK(input.dtype() == weight.value().dtype(), "torch.histogramdd: if weight tensor is provided," + " input tensor and weight tensor should have the same dtype, but got input(", input.dtype(), ")", + ", and weight(", weight.value().dtype(), ")"); + + /* If a weight tensor is provided, we expect its shape to match that of + * the input tensor excluding its innermost dimension N. + */ + auto input_sizes = input.sizes().vec(); + input_sizes.pop_back(); + + auto weight_sizes = weight.value().sizes().vec(); + if (weight_sizes.empty()) { + // correctly handle scalars + weight_sizes = {1}; + } + + TORCH_CHECK(input_sizes == weight_sizes, "torch.histogramdd: if weight tensor is provided it should have" + " the same shape as the input tensor excluding its innermost dimension, but got input with shape ", + input.sizes(), " and weight with shape ", weight.value().sizes()); + } +} + +/* Checks properties of output tensors hist and bin_edges, then resizes them. + */ +void histogramdd_prepare_out(const Tensor& input, const std::vector& bin_ct, + const Tensor& hist, const TensorList& bin_edges) { + const int64_t N = input.size(-1); + + TORCH_INTERNAL_ASSERT((int64_t)bin_ct.size() == N); + TORCH_INTERNAL_ASSERT((int64_t)bin_edges.size() == N); + + TORCH_CHECK(input.dtype() == hist.dtype(), "torch.histogram: input tensor and hist tensor should", + " have the same dtype, but got input ", input.dtype(), " and hist ", hist.dtype()); + + for (const auto dim : c10::irange(N)) { + TORCH_CHECK(input.dtype() == bin_edges[dim].dtype(), "torch.histogram: input tensor and bin_edges tensor should", + " have the same dtype, but got input ", input.dtype(), " and bin_edges ", bin_edges[dim].dtype(), + " for dimension ", dim); + + TORCH_CHECK(bin_ct[dim] > 0, + "torch.histogram(): bins must be > 0, but got ", bin_ct[dim], " for dimension ", dim); + + at::native::resize_output(bin_edges[dim], bin_ct[dim] + 1); + } + + at::native::resize_output(hist, bin_ct); +} + +void histogramdd_prepare_out(const Tensor& input, TensorList bins, + const Tensor& hist, const TensorList& bin_edges) { + std::vector bin_ct(bins.size()); + std::transform(bins.begin(), bins.end(), bin_ct.begin(), [](Tensor t) { return t.numel() - 1; }); + histogramdd_prepare_out(input, bin_ct, hist, bin_edges); +} + +/* Determines the outermost bin edges. For simplicity when calling into aminmax, + * assumes that input has already been reshaped to (M, N). + */ +std::pair, std::vector> +select_outer_bin_edges(const Tensor& input, std::optional> range) { + TORCH_INTERNAL_ASSERT(input.dim() == 2, "expected input to have shape (M, N)"); + const int64_t N = input.size(-1); + + // Default ranges for empty input matching numpy.histogram's default + std::vector leftmost_edges(N, 0.); + std::vector rightmost_edges(N, 1.); + + if (range.has_value()) { + // range is specified + TORCH_CHECK((int64_t)range.value().size() == 2 * N, "torch.histogramdd: for a ", N, "-dimensional histogram", + " range should have ", 2 * N, " elements, but got ", range.value().size()); + + for (const auto dim : c10::irange(N)) { + leftmost_edges[dim] = range.value()[2 * dim]; + rightmost_edges[dim] = range.value()[2 * dim + 1]; + } + } else if (input.numel() > 0) { + // non-empty input + + histogram_select_outer_bin_edges_stub(input.device().type(), input, N, leftmost_edges, rightmost_edges); + } + + for (const auto dim : c10::irange(N)) { + double leftmost_edge = leftmost_edges[dim]; + double rightmost_edge = rightmost_edges[dim]; + + TORCH_CHECK(std::isfinite(leftmost_edge) && std::isfinite(rightmost_edge), + "torch.histogramdd: dimension ", dim, "'s range [", + leftmost_edge, ", ", rightmost_edge, "] is not finite"); + + TORCH_CHECK(leftmost_edge <= rightmost_edge, "torch.histogramdd: min should not exceed max, but got", + " min ", leftmost_edge, " max ", rightmost_edge, " for dimension ", dim); + + // Expand empty range to match numpy behavior and avoid division by 0 in normalization + if (leftmost_edge == rightmost_edge) { + leftmost_edges[dim] -= 0.5; + rightmost_edges[dim] += 0.5; + } + } + + return std::make_pair(leftmost_edges, rightmost_edges); +} + + +/* Bin edges correction based on the precision representation. + * To maintain the backward compatibility we take max(std::nextafter<>, +1) + * and min(std::nextafter<>, -1) for scalar types. For other types +/- 1 as usual. + */ +void bins_edges_correction(const ScalarType& t, double &leftmost_edge, double &rightmost_edge) +{ +#define UPDATE_WITH_LIMIT(real_type, scalartype) \ + case ScalarType::scalartype: \ + leftmost_edge = std::min( \ + static_cast( \ + std::nexttoward( \ + static_cast(leftmost_edge), \ + std::numeric_limits::lowest() \ + ) \ + ), \ + leftmost_edge - 1. \ + ); \ + rightmost_edge = std::max( \ + static_cast( \ + std::nexttoward( \ + static_cast(rightmost_edge), \ + std::numeric_limits::max() \ + ) \ + ), \ + rightmost_edge + 1. \ + ); \ + break; + + switch (t) { + UPDATE_WITH_LIMIT(double, Double) + UPDATE_WITH_LIMIT(float, Float) + default: + // Fallback to the default behavior for other types + leftmost_edge -= 1; + rightmost_edge += 1; + } +#undef UPDATE_WITH_LIMIT +} + +/* histc's version of the logic for outermost bin edges. + */ +std::pair histc_select_outer_bin_edges(const Tensor& input, + const Scalar& min, const Scalar& max) { + double leftmost_edge = min.to(); + double rightmost_edge = max.to(); + + if (leftmost_edge == rightmost_edge && input.numel() > 0) { + auto extrema = aminmax(input); + leftmost_edge = std::get<0>(extrema).item(); + rightmost_edge = std::get<1>(extrema).item(); + } + + if (leftmost_edge == rightmost_edge) { + bins_edges_correction(input.dtype().toScalarType(), leftmost_edge, rightmost_edge); + } + + TORCH_CHECK(!(std::isinf(leftmost_edge) || std::isinf(rightmost_edge) || + std::isnan(leftmost_edge) || std::isnan(rightmost_edge)), + "torch.histc: range of [", leftmost_edge, ", ", rightmost_edge, "] is not finite"); + + TORCH_CHECK(leftmost_edge < rightmost_edge, "torch.histc: max must be larger than min"); + + return std::make_pair(leftmost_edge, rightmost_edge); +} + +} // namespace + +static std::vector allocate_bin_edges_tensors(const Tensor& self) { + TORCH_CHECK(self.dim() >= 2, "torch.histogramdd: input tensor should have at least 2 dimensions"); + const int64_t N = self.size(-1); + std::vector bin_edges_out(N); + for (const auto dim : c10::irange(N)) { + bin_edges_out[dim] = at::empty({0}, self.options(), MemoryFormat::Contiguous); + } + return bin_edges_out; +} + +/* Versions of histogramdd in which bins is a Tensor[] defining the sequences of bin edges. + */ +static Tensor& histogramdd_out(const Tensor& self, TensorList bins, + const std::optional& weight, bool density, + Tensor& hist, TensorList& bin_edges) { + histogramdd_check_inputs(self, bins, weight); + histogramdd_prepare_out(self, bins, hist, bin_edges); + + for (const auto dim : c10::irange(bins.size())) { + bin_edges[dim].copy_(bins[dim]); + } + + histogramdd_stub(self.device().type(), self, weight, density, hist, bin_edges); + return hist; +} + +Tensor _histogramdd(const Tensor& self, TensorList bins, + const std::optional& weight, bool density) { + Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); + std::vector bin_edges_out = allocate_bin_edges_tensors(self); + TensorList bin_edges_out_tl(bin_edges_out); + + histogramdd_out(self, bins, weight, density, hist, bin_edges_out_tl); + return hist; +} + +/* Versions of histogramdd in which bins is an int[] + * defining the number of bins in each dimension. + */ +static std::vector& histogramdd_bin_edges_out(const Tensor& self, IntArrayRef bin_ct, + std::optional> range, + const std::optional& weight, bool density, + std::vector& bin_edges_out) { + TensorList bin_edges_out_tl(bin_edges_out); + + const int64_t N = self.size(-1); + const int64_t M = std::accumulate(self.sizes().begin(), self.sizes().end() - 1, + static_cast(1), std::multiplies()); + Tensor reshaped_self = self.reshape({ M, N }); + + auto outer_bin_edges = select_outer_bin_edges(reshaped_self, range); + + const int64_t bin_size = bin_ct.size(); + TORCH_CHECK( + N == bin_size, + "histogramdd: The size of bins must be equal to the innermost dimension of the input."); + for (const auto dim : c10::irange(N)) { + at::linspace_out(bin_edges_out[dim], outer_bin_edges.first[dim], outer_bin_edges.second[dim], + bin_ct[dim] + 1); + } + + return bin_edges_out; +} + +std::vector histogramdd_bin_edges(const Tensor& self, IntArrayRef bin_ct, + std::optional> range, + const std::optional& weight, bool density) { + std::vector bin_edges_out = allocate_bin_edges_tensors(self); + return histogramdd_bin_edges_out(self, bin_ct, range, weight, density, bin_edges_out); +} + +static Tensor& histogramdd_out(const Tensor& self, IntArrayRef bin_ct, + std::optional> range, + const std::optional& weight, bool density, + Tensor& hist, TensorList& bin_edges) { + std::vector bins = histogramdd_bin_edges(self, bin_ct, range, weight, density); + + histogramdd_check_inputs(self, bins, weight); + histogramdd_prepare_out(self, bins, hist, bin_edges); + + for (const auto dim : c10::irange(bins.size())) { + bin_edges[dim].copy_(bins[dim]); + } + + histogramdd_linear_stub(self.device().type(), self, weight, density, hist, bin_edges, true); + return hist; +} + +Tensor _histogramdd(const Tensor& self, IntArrayRef bin_ct, + std::optional> range, + const std::optional& weight, bool density) { + Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); + std::vector bin_edges_out = allocate_bin_edges_tensors(self); + TensorList bin_edges_out_tl(bin_edges_out); + + histogramdd_out(self, bin_ct, range, weight, density, hist, bin_edges_out_tl); + return hist; +} + +/* Versions of histogram in which bins is a Tensor defining the sequence of bin edges. + */ +std::tuple +histogram_out(const Tensor& self, const Tensor& bins, + const std::optional& weight, bool density, + Tensor& hist, Tensor& bin_edges) { + Tensor reshaped_self = self.reshape({ self.numel(), 1 }); + std::optional reshaped_weight = weight.has_value() + ? weight.value().reshape({ weight.value().numel() }) : weight; + TensorList bins_in = bins; + TensorList bins_out = bin_edges; + + histogramdd_out(reshaped_self, bins_in, reshaped_weight, density, hist, bins_out); + + return std::forward_as_tuple(hist, bin_edges); +} + +std::tuple +histogram(const Tensor& self, const Tensor& bins, + const std::optional& weight, bool density) { + Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); + Tensor bin_edges = at::empty({0}, bins.options(), MemoryFormat::Contiguous); + return histogram_out(self, bins, weight, density, hist, bin_edges); +} + +/* Versions of histogram in which bins is an integer specifying the number of equal-width bins. + */ +std::tuple +histogram_out(const Tensor& self, int64_t bin_ct, std::optional> range, + const std::optional& weight, bool density, + Tensor& hist, Tensor& bin_edges) { + Tensor reshaped_self = self.reshape({ self.numel(), 1 }); + std::optional reshaped_weight = weight.has_value() + ? weight.value().reshape({ weight.value().numel() }) : weight; + TensorList bins_in = bin_edges; + TensorList bins_out = bin_edges; + + histogramdd_prepare_out(reshaped_self, std::vector{bin_ct}, hist, bins_out); + auto outer_bin_edges = select_outer_bin_edges(reshaped_self, range); + at::linspace_out(bin_edges, outer_bin_edges.first[0], outer_bin_edges.second[0], bin_ct + 1); + + histogramdd_check_inputs(reshaped_self, bins_in, reshaped_weight); + + histogramdd_linear_stub(reshaped_self.device().type(), reshaped_self, reshaped_weight, density, hist, bin_edges, true); + return std::forward_as_tuple(hist, bin_edges); +} + +std::tuple +histogram(const Tensor& self, int64_t bin_ct, std::optional> range, + const std::optional& weight, bool density) { + Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); + Tensor bin_edges_out = at::empty({0}, self.options()); + return histogram_out(self, bin_ct, range, weight, density, hist, bin_edges_out); +} + +/* Narrowed interface for the legacy torch.histc function. + */ +Tensor& histogram_histc_out(const Tensor& self, int64_t bin_ct, + const Scalar& min, const Scalar& max, Tensor& hist) { + Tensor bin_edges = at::empty({0}, self.options()); + + Tensor reshaped = self.reshape({ self.numel(), 1 }); + TensorList bins_in = bin_edges; + TensorList bins_out = bin_edges; + + histogramdd_prepare_out(reshaped, std::vector{bin_ct}, hist, bins_out); + + auto outer_bin_edges = histc_select_outer_bin_edges(self, min, max); + at::linspace_out(bin_edges, outer_bin_edges.first, outer_bin_edges.second, bin_ct + 1); + + histogramdd_check_inputs(reshaped, bins_in, {}); + + histogramdd_linear_stub(reshaped.device().type(), reshaped, + std::optional(), false, hist, bin_edges, false); + return hist; +} + +Tensor histogram_histc(const Tensor& self, int64_t bin_ct, + const Scalar& min, const Scalar& max) { + Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); + return histogram_histc_out(self, bin_ct, min, max, hist); +} + +std::tuple> histogramdd( + const Tensor &self, TensorList bins, std::optional> /*range*/, + const std::optional &weight, bool density) { + auto hist = at::_histogramdd_from_bin_tensors(self, bins, weight, density); + return std::tuple>{ + std::move(hist), bins.vec()}; +} + +std::tuple> histogramdd( + const Tensor &self, IntArrayRef bins, std::optional> range, + const std::optional &weight, bool density) { + auto bin_edges = at::_histogramdd_bin_edges(self, bins, range, weight, density); + auto hist = at::_histogramdd_from_bin_cts(self, bins, range, weight, density); + return std::tuple>{ + std::move(hist), std::move(bin_edges)}; +} + +std::tuple> histogramdd( + const Tensor &self, int64_t bins, std::optional> range, + const std::optional &weight, bool density) { + DimVector bins_v(self.size(-1), bins); + return at::native::histogramdd(self, bins_v, range, weight, density); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Histogram.h b/western_ai/usa/pytorch/aten/src/ATen/native/Histogram.h new file mode 100644 index 0000000000000000000000000000000000000000..d49ad5b2b1b164f2554556bca220c5c622a128e0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Histogram.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +namespace at::native { + +using histogramdd_fn = void(*)(const Tensor&, const std::optional&, bool, Tensor&, const TensorList&); +using histogramdd_linear_fn = void(*)(const Tensor&, const std::optional&, bool, Tensor&, const TensorList&, bool); +using histogram_select_outer_bin_edges_fn = void(*)(const Tensor& input, const int64_t N, std::vector &leftmost_edges, std::vector &rightmost_edges); + +DECLARE_DISPATCH(histogramdd_fn, histogramdd_stub) +DECLARE_DISPATCH(histogramdd_linear_fn, histogramdd_linear_stub) +DECLARE_DISPATCH(histogram_select_outer_bin_edges_fn, histogram_select_outer_bin_edges_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Im2Col.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Im2Col.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45b295f0ebefe758a20f6f617dd1e084b7c50a53 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Im2Col.cpp @@ -0,0 +1,156 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { +namespace { + +void im2col_out_cpu_template( + Tensor& output, + const Tensor& input_, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride) { + TORCH_CHECK( + kernel_size.size() == 2, + "It is expected kernel_size equals to 2, but got size ", + kernel_size.size()); + + TORCH_CHECK( + dilation.size() == 2, + "It is expected dilation equals to 2, but got size ", + dilation.size()); + + TORCH_CHECK( + padding.size() == 2, + "It is expected padding equals to 2, but got size ", + padding.size()); + + TORCH_CHECK( + stride.size() == 2, + "It is expected stride equals to 2, but got size ", + stride.size()); + + int64_t kernel_height = kernel_size[0]; + int64_t kernel_width = kernel_size[1]; + int64_t dilation_height = dilation[0]; + int64_t dilation_width = dilation[1]; + int64_t pad_height = padding[0]; + int64_t pad_width = padding[1]; + int64_t stride_height = stride[0]; + int64_t stride_width = stride[1]; + + im2col_shape_check( + input_, + Tensor(), + kernel_height, + kernel_width, + dilation_height, + dilation_width, + pad_height, + pad_width, + stride_height, + stride_width); + + Tensor input = input_.contiguous(); + + bool batched_input = true; + + if (input.dim() == 3) { + batched_input = false; + input = input.view({1, input.size(0), input.size(1), input.size(2)}); + } + + int64_t batch_size = input.size(0); + int64_t n_input_plane = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + + int64_t output_height = (input_height + 2 * pad_height - + (dilation_height * (kernel_height - 1) + 1)) / + stride_height + + 1; + int64_t output_width = (input_width + 2 * pad_width - + (dilation_width * (kernel_width - 1) + 1)) / + stride_width + + 1; + int64_t n_output_plane = n_input_plane * kernel_width * kernel_height; + int64_t output_length = output_height * output_width; + + output.resize_({batch_size, n_output_plane, output_length}); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3(kBFloat16, kHalf, kBool, + input.scalar_type(), "im2col_out_cpu", [&] { + Tensor input_n; + Tensor output_n; + + for (const auto elt : c10::irange(batch_size)) { + input_n = input.select(0, elt); + output_n = output.select(0, elt); + + im2col( + input_n.const_data_ptr(), + n_input_plane, + input_height, + input_width, + output_height, + output_width, + kernel_height, + kernel_width, + pad_height, + pad_width, + stride_height, + stride_width, + dilation_height, + dilation_width, + output_n.mutable_data_ptr()); + } + + if (!batched_input) { + output.resize_({n_output_plane, output_length}); + } + }); +} + +} // namespace + +Tensor& im2col_out_cpu(const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride, + Tensor& output) { + im2col_out_cpu_template( + output, input, kernel_size, dilation, padding, stride); + return output; +} + +Tensor im2col_cpu( + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride) { + Tensor output = at::empty_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + + im2col_out_cpu_template( + output, input, kernel_size, dilation, padding, stride); + return output; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/IndexKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/IndexKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e1709eca647f2a878355947bee7e2defab79fcdb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/IndexKernel.h @@ -0,0 +1,41 @@ +#pragma once +#include +#include + +namespace at { +class Tensor; +class TensorBase; +struct TensorIterator; +struct TensorIteratorBase; +} + +namespace c10 { +class Scalar; +} + +namespace at::native { + +using index_fn = void(*)(TensorIteratorBase &, IntArrayRef indexed_sizes, IntArrayRef indexed_strides); +using index_fill_fn = void(*)(TensorIterator & iter, int64_t dim, int64_t self_dim_size, int64_t self_dim_stride, const Scalar& source); +using index_copy_fn = void(*)(TensorIterator & iter, int64_t dim, int64_t self_dim_size, int64_t self_dim_stride); +using index_put_fn = void(*)(TensorIterator &, IntArrayRef indexed_sizes, IntArrayRef indexed_strides, bool accumulate); +using put_fn = void(*)(TensorIterator & iter, const TensorBase& self, const bool accumulate); +using take_fn = void(*)(TensorIterator & iter, const TensorBase& input); +using flip_fn = void(*)(TensorIterator &, const bool); +using masked_fill_fn = void(*)(TensorIterator &, const Scalar& scalar); +using masked_select_fn = void(*)(TensorIterator &, int64_t orig_stride); +using masked_scatter_fn = void(*)(TensorIterator &, const TensorBase &); + +DECLARE_DISPATCH(index_fn, index_stub) +DECLARE_DISPATCH(index_fill_fn, index_fill_stub) +DECLARE_DISPATCH(index_copy_fn, index_copy_stub) +DECLARE_DISPATCH(index_put_fn, index_put_stub) +DECLARE_DISPATCH(put_fn, put_stub) +DECLARE_DISPATCH(take_fn, take_stub) +DECLARE_DISPATCH(flip_fn, flip_stub) +DECLARE_DISPATCH(masked_fill_fn, masked_fill_stub) +DECLARE_DISPATCH(masked_select_fn, masked_select_serial_stub) +DECLARE_DISPATCH(masked_select_fn, masked_select_stub) +DECLARE_DISPATCH(masked_scatter_fn, masked_scatter_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/IndexingUtils.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/IndexingUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1dd356dc86c4812800bc3cdd2d79de7fe06922c7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/IndexingUtils.cpp @@ -0,0 +1,33 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +namespace at::native { + +bool canUse32BitIndexMath(const TensorBase& t, int64_t max_elem) { + auto elements = t.sym_numel(); + if (elements >= max_elem) { + return false; + } + if (elements == 0) { + return max_elem > 0; + } + + c10::SymInt offset = 0; + auto linearId = elements - 1; + + // NOTE: Assumes all strides are positive, which is true for now + for (auto i = t.dim() - 1; i >= 0; --i) { + auto curDimIndex = linearId % t.sym_size(i); + auto curDimOffset = curDimIndex * t.sym_stride(i); + offset += curDimOffset; + linearId /= t.sym_size(i); + } + + if (offset >= max_elem) { + return false; + } + + return true; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/IndexingUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/IndexingUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..2af44d5cdda0b31ee9a5e58e46c3ee02277ded49 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/IndexingUtils.h @@ -0,0 +1,186 @@ +#pragma once +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at::native { + +[[noreturn]] +static void invalid_mask(const Tensor & self, int64_t idx, const Tensor & mask, int64_t maskIdx) { + TORCH_CHECK_INDEX(false, "The shape of the mask ", mask.sizes(), " at index ", maskIdx, + " does not match the shape of the indexed tensor ", self.sizes(), " at index ", idx); +} + +[[maybe_unused]] static std::vector expandTensors( + const Tensor& self, + IOptTensorListRef indices, + bool ensure_same_device = false) { + // If indices come in as ByteTensor or BoolTensor (masks), expand them into + // the equivalent indexing by LongTensors + std::vector result; + for (const auto& index_opt : indices) { + if (!index_opt.has_value()) { + result.emplace_back(); + } else { + const auto& index = *index_opt; + if (index.scalar_type() == kByte || index.scalar_type() == kBool) { + if (index.scalar_type() == kByte) { + TORCH_WARN("indexing with dtype torch.uint8 is now deprecated," \ + " please use a dtype torch.bool instead."); + } + // The sizes of the ByteTensor mask or bool tensor must match the sizes of the + // corresponding dimensions in self + for (const auto j : c10::irange(index.dim())) { + int64_t srcIdx = static_cast(result.size() + j); + if (index.size(j) != self.size(srcIdx)) { + invalid_mask(self, srcIdx, index, j); + } + } + // Replace with nonzeros + at::Tensor nonzero; + if (ensure_same_device && index.device() != self.device()) { + bool non_blocking = index.is_cpu() && self.device().is_cuda(); + auto out = at::empty({0}, index.options().dtype(kLong).pinned_memory(non_blocking)); + nonzero = at::nonzero_out(out, index).to(self.device(), non_blocking); + } else { + nonzero = index.nonzero(); + } + for (const auto j : c10::irange(index.dim())) { + result.emplace_back(nonzero.select(1, j)); + } + } else if (ensure_same_device && index.device() != self.device()) { + result.emplace_back(index.to(self.device())); + } else { + result.emplace_back(index); + } + } + } + return result; +} + +[[maybe_unused]] static void checkIndexTensorTypes( + IOptTensorListRef indices, + bool allow_int = false) { + for (const auto& tensor : indices) { + if (tensor.has_value() && tensor->defined()) { + auto scalarType = tensor->scalar_type(); + if (allow_int) { + if (scalarType != kLong && scalarType != kByte && scalarType != kBool && scalarType != kInt) { + TORCH_CHECK_INDEX(false, "tensors used as indices must be long, int, byte or bool tensors"); + } + } else { + if (scalarType != kLong && scalarType != kByte && scalarType != kBool) { + TORCH_CHECK_INDEX(false, "tensors used as indices must be long, byte or bool tensors"); + } + } + } + } +} + +inline torch::List> toListOfOptionalTensors(ArrayRef list) { + torch::List> result; + result.reserve(list.size()); + for (const Tensor& a : list) { + result.push_back(a); + } + return result; +} + +inline torch::List> toListOfOptionalTensors(ArrayRef list) { + torch::List> result; + result.reserve(list.size()); + for (const IValue& a : list) { + result.push_back(a.isTensor() ? std::optional(a.toTensor()) : std::optional()); + } + return result; +} + +[[maybe_unused]] static bool hasContiguousSubspace(TensorList tl) { + // true if all the non-null tensors are adjacent + auto isDefined = [](const Tensor & tensor){ return tensor.defined(); }; + auto isNull = [](const Tensor & tensor){ return !tensor.defined(); }; + auto start = std::find_if(tl.begin(), tl.end(), isDefined); + if (start == tl.end()) { + return true; + } + auto stop = std::find_if(tl.rbegin(), tl.rend(), isDefined); + auto it = std::find_if(start, stop.base(), isNull); + return it == stop.base(); +} + +// Transposes the tensor and indices together so that all the non-null indices +// index the first k dimensions of the tensor. Returns the transposed tensor +// and the reordered indices. For example: +// transposeToFront(tensor, {nullptr, a, nullptr, b}) +// returns +// tensor.permute([1, 3, 0, 2]), {a, b, nullptr, nullptr} +[[maybe_unused]] static std::tuple> transposeToFront( + const Tensor& self, + TensorList indices) { + std::vector dims; + std::vector transposedIndices; + dims.reserve(self.dim()); + transposedIndices.reserve(self.dim()); + for (const auto i : c10::irange(self.dim())) { + if (indices[i].defined()) { + dims.push_back(i); + transposedIndices.emplace_back(indices[i]); + } + } + for (const auto i : c10::irange(self.dim())) { + if (!indices[i].defined()) { + dims.push_back(i); + transposedIndices.emplace_back(); + } + } + return std::make_tuple(self.permute(dims), std::move(transposedIndices)); +} + +inline std::tuple, std::vector> +transposeToFrontAndInvPerm(const Tensor& self, TensorList indices) { + std::vector dims; + std::vector invPerm; + std::vector transposedIndices; + dims.reserve(self.dim()); + invPerm.resize(self.dim()); + transposedIndices.reserve(self.dim()); + for (const auto i : c10::irange(self.dim())) { + if (indices[i].defined()) { + dims.push_back(i); + transposedIndices.emplace_back(indices[i]); + } + } + for (const auto i : c10::irange(self.dim())) { + if (!indices[i].defined()) { + dims.push_back(i); + transposedIndices.emplace_back(); + } + } + for (const auto i : c10::irange(self.dim())) { + invPerm[dims[i]] = i; + } + return std::make_tuple(self.permute(dims), std::move(transposedIndices), std::move(invPerm)); +} + +struct AdvancedIndex { + AdvancedIndex(const Tensor& src, TensorList indices); + + Tensor src; + std::vector indices; + DimVector indexed_sizes; + DimVector indexed_strides; + int64_t dims_before; + int64_t dims_after; +}; + + +} //namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Integration.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Integration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74974db643171d5f8904d1c5fdc19d3ab3ffd014 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Integration.cpp @@ -0,0 +1,171 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { +namespace { + +// The estimated integral of a function y of x, +// sampled at points (y_1, ..., y_n) that are separated by distance (dx_1, ..., dx_{n-1}), +// is given by the trapezoid rule: +// +// \sum_{i=1}^{n-1} dx_i * (y_i + y_{i+1}) / 2 +// +// TODO: if we extend TensorIterator to accept 3 inputs, +// we can probably make this a bit more performant. +Tensor do_trapezoid(const Tensor& y, const Tensor& dx, int64_t dim) { + Tensor left = y.slice(dim, 0, -1); + Tensor right = y.slice(dim, 1); + // If the dimensions of 'dx' and '(left + right)' do not match + // broadcasting is attempted here. + return ((left + right) * dx).sum(dim) / 2.; +} + +// When dx is constant, the above formula simplifies +// to dx * [(\sum_{i=1}^n y_i) - (y_1 + y_n)/2] +Tensor do_trapezoid(const Tensor& y, double dx, int64_t dim) { + return (y.sum(dim) - (y.select(dim, 0) + y.select(dim, -1)) * 0.5) * dx; +} + +Tensor zeros_like_except(const Tensor& y, int64_t dim) { + auto sizes = y.sym_sizes().vec(); + dim = maybe_wrap_dim(dim, y.dim()); + sizes.erase(sizes.begin() + dim); + return at::zeros_symint(sizes, y.options()); +} + +Tensor do_cumulative_trapezoid(const Tensor& y, const Tensor& dx, int64_t dim) { + Tensor left = y.slice(dim, 0, -1); + Tensor right = y.slice(dim, 1); + + return ((left + right) * dx).cumsum(dim) / 2.; +} + +Tensor do_cumulative_trapezoid(const Tensor& y, double dx, int64_t dim) { + Tensor left = y.slice(dim, 0, -1); + Tensor right = y.slice(dim, 1); + + return (dx /2. * (left + right)).cumsum(dim); +} +// Given the current shape of a Tensor and a target number of dimensions, +// returns a new shape with the same values as the original shape, +// but with '1's padded in the beginning to match the target number of dimensions. +// For example, curr_shape = (5,5,5) and target_n_dim = 6 ==> (1,1,1,5,5,5) +// Note that no padding will be added if the current shape has the greater than or equal +// number of dimensions than the target numbers of dimensions. +SymDimVector add_padding_to_shape(SymIntArrayRef curr_shape, int64_t target_n_dim) { + const auto curr_size = static_cast(curr_shape.size()); + if (curr_size >= target_n_dim){ + target_n_dim = curr_size; + } + SymDimVector new_shape(target_n_dim, 1); + for (const auto i : c10::irange(curr_size)) { + new_shape[target_n_dim-i-1] = curr_shape[curr_size-i-1]; + } + return new_shape; +} +} + +Tensor trapezoid(const Tensor& y, const Tensor& x, int64_t dim) { + dim = maybe_wrap_dim(dim, y); + // asking for the integral with zero samples is a bit nonsensical, + // but we'll return "0" to match numpy behavior. + if (y.sym_size(dim) == 0) { + return zeros_like_except(y, dim); + } + TORCH_CHECK(y.scalar_type() != kBool && x.scalar_type() != kBool, "trapezoid: received a bool input for `x` or `y`, but bool is not supported") + Tensor x_viewed; + // Note that we explicitly choose not to broadcast 'x' to match the shape of 'y' here because + // we want to follow NumPy's behavior of broadcasting 'dx' and 'dy' together after the differences are taken. + if (x.dim() == 1) { + // This step takes 'x' with dimension (n,), and returns 'x_view' with + // dimension (1,1,...,n,...,1,1) based on dim and y.dim() so that, later on, 'dx' + // can be broadcast to match 'dy' at the correct dimensions. + TORCH_CHECK(x.sym_size(0) == y.sym_size(dim), "trapezoid: There must be one `x` value for each sample point"); + SymDimVector new_sizes(y.dim(), 1); // shape = [1] * y. + new_sizes[dim] = x.sym_size(0); // shape[axis] = d.shape[0] + x_viewed = x.view_symint(new_sizes); + } else if (x.dim() < y.dim()) { + // When 'y' has more dimension than 'x', this step takes 'x' with dimension (n_1, n_2, ...), + // and add '1's as dimensions in front to become (1, 1, ..., n_1, n_2), matching the dimension of 'y'. + // This allows the subsequent slicing operations to proceed with any 'dim' without going out of bound. + SymDimVector new_sizes = add_padding_to_shape(x.sym_sizes(), y.dim()); + x_viewed = x.view_symint(new_sizes); + } else { + x_viewed = x; + } + // Note the .slice operation reduces the dimension along 'dim' by 1, + // while the sizes of other dimensions are untouched. + Tensor x_left = x_viewed.slice(dim, 0, -1); + Tensor x_right = x_viewed.slice(dim, 1); + + Tensor dx = x_right - x_left; + return do_trapezoid(y, dx, dim); +} + +Tensor trapezoid(const Tensor& y, const Scalar& dx, int64_t dim) { + // see above + if (y.sym_size(dim) == 0) { + return zeros_like_except(y, dim); + } + TORCH_CHECK(y.scalar_type() != kBool, "trapezoid: received a bool input for `y`, but bool is not supported") + TORCH_CHECK(!(dx.isComplex() || dx.isBoolean()), "trapezoid: Currently, we only support dx as a real number."); + return do_trapezoid(y, dx.toDouble(), dim); +} + +Tensor trapz(const Tensor& y, const Tensor& x, int64_t dim) { + return at::native::trapezoid(y, x, dim); +} + +Tensor trapz(const Tensor& y, double dx, int64_t dim) { + return at::native::trapezoid(y, dx, dim); +} + +Tensor cumulative_trapezoid(const Tensor& y, const Tensor& x, int64_t dim) { + dim = maybe_wrap_dim(dim, y); + TORCH_CHECK(y.scalar_type() != kBool && x.scalar_type() != kBool, "cumulative_trapezoid: received a bool input for `x` or `y`, but bool is not supported") + Tensor x_viewed; + if (x.dim() == 1) { + // See trapezoid for implementation notes + TORCH_CHECK(x.sym_size(0) == y.sym_size(dim), "cumulative_trapezoid: There must be one `x` value for each sample point"); + SymDimVector new_sizes(y.dim(), 1); // shape = [1] * y. + new_sizes[dim] = x.sym_size(0); // shape[axis] = d.shape[0] + x_viewed = x.view_symint(new_sizes); + } else if (x.dim() < y.dim()) { + // See trapezoid for implementation notes + SymDimVector new_sizes = add_padding_to_shape(x.sym_sizes(), y.dim()); + x_viewed = x.view_symint(new_sizes); + } else { + x_viewed = x; + } + Tensor x_left = x_viewed.slice(dim, 0, -1); + Tensor x_right = x_viewed.slice(dim, 1); + Tensor dx = x_right - x_left; + + return do_cumulative_trapezoid(y, dx, dim); +} + +Tensor cumulative_trapezoid(const Tensor& y, const Scalar& dx, int64_t dim) { + TORCH_CHECK(y.scalar_type() != kBool, "cumulative_trapezoid: received a bool input for `y`, but bool is not supported") + TORCH_CHECK(!(dx.isComplex() || dx.isBoolean()), "cumulative_trapezoid: Currently, we only support dx as a real number."); + + return do_cumulative_trapezoid(y, dx.toDouble(), dim); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Itertools.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Itertools.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06b27ac53061b807f01250a5a53e1f88ce305a56 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Itertools.cpp @@ -0,0 +1,75 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +#include + +namespace { + +using namespace at; + +Tensor _triu_mask(c10::SymInt n, int64_t dims, bool diagonal, TensorOptions opt) { + // get a mask that has value 1 whose indices satisfies i < j < k < ... + // or i <= j <= k <= ... (depending on diagonal) + Tensor range = at::arange(std::move(n), opt.dtype(kLong)); + std::vector index_grids = at::meshgrid(std::vector(dims, range), "ij"); + Tensor mask = at::full(index_grids[0].sizes(), true, opt.dtype(kBool)); + if(diagonal) { + for(int64_t i = 0; i < dims - 1; i++) { + mask *= index_grids[i] <= index_grids[i+1]; + } + } else { + for(int64_t i = 0; i < dims - 1; i++) { + mask *= index_grids[i] < index_grids[i+1]; + } + } + return mask; +} + +} // namespace + +namespace at::native { + +Tensor cartesian_prod(TensorList tensors) { + for(const Tensor &t : tensors) { + TORCH_CHECK(t.dim() == 1, "Expect a 1D vector, but got shape ", t.sizes()); + } + if (tensors.size() == 1) { + return tensors[0]; + } + std::vector grids = at::meshgrid(tensors, "ij"); + for(Tensor &t : grids) { + t = t.flatten(); + } + return at::stack(grids, 1); +} + +Tensor combinations(const Tensor& self, int64_t r, bool with_replacement) { + TORCH_CHECK(self.dim() == 1, "Expect a 1D vector, but got shape ", self.sizes()); + TORCH_CHECK(r >= 0, "Expect a non-negative number, but got ", r); + if (r == 0) { + return at::empty({0}, self.options()); + } + c10::SymInt num_elements = self.sym_numel(); + std::vector grids = at::meshgrid(std::vector(r, self), "ij"); + Tensor mask = _triu_mask(std::move(num_elements), r, with_replacement, self.options()); + for(Tensor &t : grids) { + t = t.masked_select(mask); + } + return at::stack(grids, 1); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LegacyBatching.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LegacyBatching.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05401920c3953197abbc40018e881eec983018fc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LegacyBatching.cpp @@ -0,0 +1,122 @@ +#include +#include +#include +#include + +#ifdef AT_PER_OPERATOR_HEADERS +#include +#include +#endif + +namespace at::native { + +// Adds a batch dimension to the tensor `self` out-of-place +Tensor _add_batch_dim(const Tensor& self, int64_t batch_dim, int64_t level) { + return addBatchDim(self, level, batch_dim); +} + +static bool has_level(const Tensor& self, int64_t level) { + const auto* batched = maybeGetBatchedImpl(self); + if (!batched) { + return false; + } + auto bdims = batched->bdims(); + auto* it = std::find_if(bdims.begin(), bdims.end(), [&](const BatchDim& bdim) { + return bdim.level() == level; + }); + return it != bdims.end(); +} + +// Returns a Tensor with batch dim with level `level` turned into a regular dimension, +// as well as a logical dim index of where said dimension is in the returned tensor. +// A call to this function is always followed by a call to `movedim`. +// +// Preconditions: A BatchDim with level `level` must exist inside `batched`. +// +// The reason why we want to return the index of where said dimension is in the returned +// tensor is because we want to keep track of which dimension used to be the batch +// dimension so that we can move it to the correct logical dimension specified by +// `out_dims` in vmap. For example, if we had +// >>> x = torch.randn(2, 3, 5) +// >>> vmap(lambda x: x, in_dims=0, out_dims=1)(x) +// then right when we are about to exit the vmap block, x is a BatchedTensor with a +// batch dimension at (physical) index 0. Note that the batch dimension doesn't +// always have to exist at (physical) index 0. When we undo the batch dimension, +// we want to move it to dimension 1 (as specified by out_dims). So we return the +// index at which the batch dim appears so that we can move it to the correct place. +// later down the line via a call to `movedim`. +static std::pair remove_existing_batch_dim( + const BatchedTensorImpl* batched, int64_t level) { + auto bdims = batched->bdims(); + if (bdims.size() == 1) { + TORCH_INTERNAL_ASSERT(bdims[0].level() == level); + return std::make_pair(batched->value(), bdims[0].dim()); + } + BatchDims new_bdims; + int64_t newly_exposed_physical_dim = -1; + new_bdims.reserve(bdims.size() - 1); + for (const auto& bdim : bdims) { + if (bdim.level() == level) { + newly_exposed_physical_dim = bdim.dim(); + } else { + new_bdims.push_back(bdim); + } + } + // Because a BatchDim with level `level` must exist inside `batched, + // we should have found a `newly_exposed_logical_dim`. + TORCH_INTERNAL_ASSERT(newly_exposed_physical_dim != -1); + int64_t num_batch_dims_before_newly_exposed_physical_dim = std::count_if( + new_bdims.begin(), new_bdims.end(), + [&](const BatchDim& bdim) { + return bdim.dim() < newly_exposed_physical_dim; + }); + int64_t newly_exposed_logical_dim = + newly_exposed_physical_dim - num_batch_dims_before_newly_exposed_physical_dim; + auto result_tensor = makeBatched(batched->value(), std::move(new_bdims)); + return std::make_pair(std::move(result_tensor), newly_exposed_logical_dim); +} + +// at::movedim but may return the original tensor if dst is the same as src. +static Tensor maybe_movedim(const Tensor& self, int64_t src, int64_t dst) { + auto logical_dim = self.dim(); + src = maybe_wrap_dim(src, logical_dim); + dst = maybe_wrap_dim(dst, logical_dim); + if (src == dst) { + return self; + } + return self.movedim(src, dst); +} + +// Removes the batch dim with level `level` from `self`. If this causes the +// last batch dim to be removed from a BatchedTensor, then this returns a +// regular Tensor. +// +// If the `level` of the batch dim to remove does not exist in `self`, then we +// add the batch dim in. This can happen if `self` didn't interact with a tensor +// inside the vmap level, for example, +// self = torch.randn(3) +// y = torch.randn(5) +// out = vmap(lambda x: vmap(lambda y: x)(y))(self) +// assert out.shape == (3, 5) +// Inside the inner vmap, `x` is a BatchedTensor with a single batch dimension +// corresponding to the *outer* vmap level and it doesn't have any dimensions that +// correspond to the inner vmap level so we need to create one for the user. +// +// `out_dim` controls where we should put the batch dimension in the output tensor. +Tensor _remove_batch_dim(const Tensor& self, int64_t level, int64_t batch_size, int64_t out_dim) { + if (!has_level(self, level)) { + auto self_sizes = self.sizes(); + VmapDimVector expanded_sizes(self_sizes.begin(), self_sizes.end()); + expanded_sizes.insert(expanded_sizes.begin() + out_dim, batch_size); + return self.expand(expanded_sizes); + } + + // Must be batched if has_level(self, /*any_level*/) + const auto* batched = maybeGetBatchedImpl(self); + TORCH_INTERNAL_ASSERT(batched != nullptr); + + auto [self_without_bdim, newly_exposed_logical_dim] = remove_existing_batch_dim(batched, level); + return maybe_movedim(self_without_bdim, newly_exposed_logical_dim, out_dim); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Lerp.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Lerp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..978932826073eeac814ba4c9eaf90e0d26cc2f98 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Lerp.cpp @@ -0,0 +1,59 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace at::meta { + +TORCH_META_FUNC(lerp_Tensor)( + const Tensor& self, const Tensor& end, const Tensor& weight) { + TORCH_CHECK(self.dtype() == end.dtype(), "expected dtype ", self.dtype(), + " for `end` but got dtype ", end.dtype()); + bool promote_weight = weight.dim() == 0; + if (!promote_weight) { + TORCH_CHECK(self.dtype() == weight.dtype(), "expected dtype ", self.dtype(), + " for `weight` but got dtype ", weight.dtype()); + } + build(at::TensorIteratorConfig() + .allow_cpu_scalars(true) + .promote_inputs_to_common_dtype(promote_weight) + .enforce_safe_casting_to_output(promote_weight) + .cast_common_dtype_to_outputs(promote_weight) + .add_output(maybe_get_output()) + .add_const_input(self) + .add_const_input(end) + .add_const_input(weight)); +} + +TORCH_META_FUNC(lerp_Scalar)( + const Tensor& self, const Tensor& end, const Scalar& /*weight*/) { + TORCH_CHECK(self.dtype() == end.dtype(), "expected dtype ", self.dtype(), + " for `end` but got dtype ", end.dtype()); + build_binary_op(maybe_get_output(), self, end); +} + +} // namespace at::meta + +namespace at::native { + +TORCH_IMPL_FUNC(lerp_Tensor)( + const Tensor& /*self*/, const Tensor& /*end*/, const Tensor& weight, const Tensor& /*out*/) { + lerp_kernel_tensor_weight(device_type(), *this); +} + +TORCH_IMPL_FUNC(lerp_Scalar)( + const Tensor& /*self*/, const Tensor& /*end*/, const Scalar& weight, const Tensor& /*out*/) { + lerp_kernel_scalar_weight(device_type(), *this, weight); +} + +DEFINE_DISPATCH(lerp_kernel_scalar_weight); +DEFINE_DISPATCH(lerp_kernel_tensor_weight); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Lerp.h b/western_ai/usa/pytorch/aten/src/ATen/native/Lerp.h new file mode 100644 index 0000000000000000000000000000000000000000..5bfc29b25fcad3264f8e6b0c108cbb1169281682 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Lerp.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include +#include +#include + +namespace at::native { + +template +C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(scalar_t weight) { + return std::abs(weight) < scalar_t(0.5); +} +template +C10_HOST_DEVICE C10_ALWAYS_INLINE bool is_lerp_weight_small(c10::complex weight) { + // Avoid the sqrt in abs(weight) + return (weight.real() * weight.real() + weight.imag() * weight.imag()) < scalar_t(0.25); +} + +template +C10_HOST_DEVICE C10_ALWAYS_INLINE scalar_t lerp(scalar_t self_, scalar_t end_, weight_t weight_) { + using opmath_t = at::opmath_type; + using opmath_weight_t = at::opmath_type; + + opmath_t self = self_; + opmath_t end = end_; + opmath_weight_t weight = weight_; + + // Conditional for better numeric. This has been discussed in + // https://github.com/pytorch/pytorch/pull/18871 + return is_lerp_weight_small(weight) + ? self + weight * (end - self) + : end - (end - self) * (opmath_t(1) - weight); +} + +using lerp_fn_scalar = void (*)( + at::TensorIteratorBase& iter, + const Scalar& weight); + +using lerp_fn_tensor = void (*)( + at::TensorIteratorBase& iter); + +DECLARE_DISPATCH(lerp_fn_scalar, lerp_kernel_scalar_weight) +DECLARE_DISPATCH(lerp_fn_tensor, lerp_kernel_tensor_weight) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Linear.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Linear.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd77b971bfe2d2bcb8e29f1e9c8f7999877da36e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Linear.cpp @@ -0,0 +1,923 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include + +namespace at::native { + +// Parse environment variable "TORCH_LINEAR_FLATTEN_3D" +static inline bool parseLinearFlatten3d() { + // Uninitialized value + static auto value = c10::utils::check_env("TORCH_LINEAR_FLATTEN_3D"); + return value.has_value() && value.value(); +} + +// `_flatten_nd_linear` flattens all but the last dimension of the input tensor +// before passing it to linear operation +static inline Tensor _flatten_nd_linear(const Tensor& input, const Tensor& weight, const Tensor& bias) { + const auto input_sizes = input.sym_sizes(); + + const auto result_flattened = [&]() -> Tensor { + const auto input_ncols = input_sizes.back(); + const auto input_flattened_nrows = [&]() -> c10::SymInt { + // can't use -1 in reshape because it errors when a dimension is 0 + auto flattened_nrows = c10::SymInt{1}; + for (const auto& size : input_sizes.slice(0, input_sizes.size() - 1)) { + flattened_nrows *= size; + } + return flattened_nrows; + }(); + + const auto input_flattened = input.view_symint({input_flattened_nrows, input_ncols}); + if (weight.layout() == c10::kStrided) { + return at::addmm(bias, input_flattened, weight.t()); + } else { + // weight is sparse, and addmm for sparse expects matmul lhs to be sparse, + // so we transpose the problem. + // NOTE: at::matmul handles (dense @ sparse) similarly. + const auto bias_t = (bias.dim() >= 2) ? bias.mT() : bias.unsqueeze(-1); + return at::addmm(bias_t, weight, input_flattened.t()).t(); + } + }(); + + // Unflatten flattened row dims + auto result_sizes = c10::SymDimVector{input_sizes.begin(), input_sizes.end()}; + result_sizes.back() = result_flattened.sym_size(1); + return result_flattened.view_symint(result_sizes); +} + + +Tensor linear(const Tensor& input, const Tensor& weight, const std::optional& bias_opt) { + // _matmul_impl checks this again later, but _flatten_nd_linear does not work on scalars inputs, + // so let's try to catch this here already + const auto input_dim = input.dim(); + const auto weight_dim = weight.dim(); + TORCH_CHECK(input_dim != 0 && weight_dim != 0, + "both arguments to linear need to be at least 1D, but they are ", + input_dim, "D and ", weight_dim, "D"); + + // See [Note: hacky wrapper removal for optional tensor] + auto bias = bias_opt.has_value() + ? c10::MaybeOwned::borrowed(*bias_opt) + : c10::MaybeOwned::owned(std::in_place); + if (input.is_mkldnn()) { + return at::mkldnn_linear(input, weight, *bias); + } +#if defined(C10_MOBILE) + if (xnnpack::use_linear(input, weight, *bias)) { + return xnnpack::linear(input, weight, *bias); + } +#endif + if (input_dim == 2 && bias->defined()) { + // Fused op is marginally faster. + return at::addmm(*bias, input, weight.t()); + } + + const auto is_bias_likely_fusable = ( + bias->defined() && + // cuBLASLt: will fuse in the epilogue without copies + // when input/weight/bias are all strided. + // When weight is not strided, bias will not be fused, + // but we can still dispatch here to avoid at::matmul + // path which will probably use a very similar + // flattening optimization. + ((bias->dim() == 1 || bias->squeeze().dim() == 1) && bias->is_contiguous_or_false()) + ); + if (is_bias_likely_fusable && !input.is_xla()) { + // Also hit the fused path for contiguous nD input, if not using xla + // backend. Reshaping/flattening has some performance implications on xla. + if (input.is_contiguous_or_false()) { + return _flatten_nd_linear(input, weight, *bias); + } else if (parseLinearFlatten3d()) { + // If user forces flattening via env var + const Tensor input_cont = input.contiguous(); + return _flatten_nd_linear(input_cont, weight, *bias); + } + } + auto output = at::matmul(input, weight.t()); + if (bias->defined()) { + // for composite compliance use out-of-place version of `add` + if (isTensorSubclassLike(*bias) || + bias->_fw_grad(/*level*/ 0).defined()) { + output = at::add(output, *bias); + } else { + output.add_(*bias); + } + } + return output; +} + +Tensor& linear_out(const Tensor& input, const Tensor& weight, const std::optional& bias_opt, Tensor& output) { + TORCH_CHECK(!input.is_mkldnn(), "linear doesn't support out for MKLDNN tensors"); + // See [Note: hacky wrapper removal for optional tensor] + auto bias = bias_opt.has_value() + ? c10::MaybeOwned::borrowed(*bias_opt) + : c10::MaybeOwned::owned(std::in_place); + + if (input.dim() == 2 && bias->defined()) { + // Fused op is marginally faster. + return at::addmm_out(output, *bias, input, weight.t()); + } + output = at::matmul_out(output, input, weight.t()); + if (bias->defined()) { + output.add_(*bias); + } + return output; +} + +// sumproduct_pair computes `(left*right).sum(sumdims)` by means of permutation and +// batch matrix multiplication +// its main purpose is to provide a pairwise reduction for einsum +static Tensor sumproduct_pair(const Tensor& left_, const Tensor& right_, IntArrayRef sum_dims_, bool keepdim) { + // assumes that tensors have been pre-unsqueezed (so that all dimensions match - after broadcasting) + // but makes no other assumptions on the order of dimensions + TORCH_CHECK(left_.dim()==right_.dim(), "number of dimensions must match"); + if (sum_dims_.empty()) + return at::mul(left_, right_); + int64_t dim = left_.dim(); + auto sum_dims = at::dim_list_to_bitset(sum_dims_, dim); + // dimensions that will be part of the output (i.e. not summed over) in three vectors: + // dims in lro appear in left, right and output, similarly, lo: left and output, ro: right and output + // also the sizes are kept track of for reshaping + std::vector lro, lo, ro; + SymInt lro_size = 1, lo_size = 1, ro_size = 1, sum_size = 1; + Tensor left = left_; + Tensor right = right_; + for (const auto i : c10::irange(dim)) { + auto sl = TORCH_GUARD_OR_TRUE(left.sym_size(i).sym_ne(1)); + auto sr = TORCH_GUARD_OR_TRUE(right.sym_size(i).sym_ne(1)); + if (sum_dims[i]) { // first dimensions that will be summed over after multiplication + if (sl && sr) { // dimensions nontrivially in both left and right must be of the same size + TORCH_SYM_CHECK(left.sym_size(i).sym_eq(right.sym_size(i)), "non-broadcast dimensions must match"); + sum_size *= left.sym_size(i); + } else if (sl) { // if it is only in one of left and right, we can sum right away + left = left.sum(i, true); + } else if (sr) { + right = right.sum(i, true); + } + } else if (sl && sr) { // now deal with dimensions that will be in the output + // dimensions nontrivially in both left and right must be of the same size + TORCH_SYM_CHECK(left.sym_size(i).sym_eq(right.sym_size(i)), "non-broadcast dimensions must match"); + lro.push_back(i); + lro_size *= left.sym_size(i); + } else if (sl) { // keep track of dimensions appearing only once + lo.push_back(i); + lo_size *= left.sym_size(i); + } else { + ro.push_back(i); + ro_size *= right.sym_size(i); + } + } + // we now work with the following permutations / shapes. + // the pipeline is permute inputs -> reshape inputs -> batch matrix mul -> reshape(view) output -> permute output + // output: "lro, lo, 1-for-summed-dims, ro" with original shape dimensions + // left: "lro, lo, summed" permuted with lpermutation and the three flattened + // right: "lro, summed, ro" permuted with rpermutation and the three flattened + // then the permuted output is a view of bmm(left, right) + // finally, opermutation reverts the permutation to the original order of dimensions + // By default the output is "lro, lo, 1-for-summed-dims, ro" with original shape dimensions. + // However, if all dimensions from the right operand appear before those from the left + // operand in the final output, we can swap the operands so that bmm directly produces + // the result in the correct memory order. + + bool swap_lo_ro = !lo.empty() && !ro.empty() && ro.back() < lo.front(); + if (swap_lo_ro) { + std::swap(left, right); + std::swap(lo, ro); + std::swap(lo_size, ro_size); + } + auto out_num_dim = lro.size() + lo.size() + sum_dims_.size() + ro.size(); + std::vector out_size; + out_size.reserve(out_num_dim); + for (auto& d : lro) out_size.push_back(left.sym_size(d)); + for (auto& d : lo) out_size.push_back(left.sym_size(d)); + for (auto& d : sum_dims_) { out_size.emplace_back(1); (void)d; }; // avoid warning about not using d + for (auto& d : ro) out_size.push_back(right.sym_size(d)); + + std::vector lpermutation(lro); + lpermutation.insert(lpermutation.end(), lo.begin(), lo.end()); + lpermutation.insert(lpermutation.end(), sum_dims_.begin(), sum_dims_.end()); + lpermutation.insert(lpermutation.end(), ro.begin(), ro.end()); + + std::vector rpermutation(lro); + rpermutation.insert(rpermutation.end(), sum_dims_.begin(), sum_dims_.end()); + rpermutation.insert(rpermutation.end(), ro.begin(), ro.end()); + rpermutation.insert(rpermutation.end(), lo.begin(), lo.end()); + + std::vector opermutation(out_num_dim, -1); + { + int64_t i = 0; + + for (auto it = lro.cbegin(); it != lro.cend(); i++, it++) { + opermutation[*it] = i; + } + for (auto it = lo.cbegin(); it != lo.cend(); i++, it++) { + opermutation[*it] = i; + } + for (auto it = sum_dims_.cbegin(); it != sum_dims_.cend(); i++, it++) { + opermutation[*it] = i; + } + for (auto it = ro.cbegin(); it != ro.cend(); i++, it++) { + opermutation[*it] = i; + } + } + + // now we can execute the operations above + left = left.permute(lpermutation).reshape_symint({lro_size, std::move(lo_size), sum_size}); + right = right.permute(rpermutation).reshape_symint({std::move(lro_size), std::move(sum_size), std::move(ro_size)}); + Tensor result = at::bmm(left, right); + result = result.view_symint(out_size).permute(opermutation); + + // finally squeeze summed dimensions if desired + if (! keepdim) { + auto sizes = result.sizes().vec(); + for (auto i = dim-1; i>=0; i--) { + if (sum_dims[i]) { + sizes.erase(sizes.begin() + i); + } + } + result = result.view(sizes); + } + return result; +} + +// There are roughly three parts to computing einsum: +// 1. Parse equation to extract the labels for each input operand and output +// 2. Unsqueeze missing dimensions from input operands and permute to align them +// 3. Compute result by multiplying input operands and summing contraction +// dimensions. We do the last part by reducing to bmm. +// If a path is specified, we reduce in the order specified by the path, else we +// default to going left => right. The path is a list of indices processed the same +// way as opt-einsum: https://optimized-einsum.readthedocs.io/en/stable/path_finding.html#format-of-the-path +Tensor einsum(std::string_view equation, TensorList operands, at::OptionalIntArrayRef path) { + TORCH_CHECK(!operands.empty(), "einsum(): must provide at least one operand"); + const auto num_ops = operands.size(); + + if (path.has_value()) { + const auto path_size = num_ops == 1 ? 1 : (num_ops - 1) * 2; + TORCH_CHECK( + path->size() == path_size, + "einsum(): expected contraction path given in path parameter to have size ", + path_size, + " but got ", + path->size()); + } + + // Labels must be in range [A-Za-z] + constexpr uint8_t NUM_OF_LETTERS = 'z' - 'a' + 1; + constexpr uint8_t TOTAL_LABELS = NUM_OF_LETTERS * 2; + + // Code used to identify ELLIPSIS ("...") + constexpr uint8_t ELLIPSIS = TOTAL_LABELS; + + // Convert label in [A-Za-z] to subscript in [0, TOTAL_LABELS) + auto label_to_subscript = [=](unsigned char label) -> uint8_t { + return std::isupper(label) ? label - 'A' : label - 'a' + NUM_OF_LETTERS; + }; + +#ifndef STRIP_ERROR_MESSAGES + // Convert subscript in [0, TOTAL_LABELS) to label in [A-Za-z] + auto subscript_to_label = [=](uint8_t s) -> unsigned char { + return s < NUM_OF_LETTERS ? s + 'A' : s + 'a' - NUM_OF_LETTERS; + }; +#endif + + // Find arrow (->) to split equation into lhs and rhs + const auto arrow_pos = equation.find("->"); + const auto lhs = equation.substr(0, arrow_pos); + + // Convert labels for input operands into an index in [0, 52) and store + // them in op_labels for each operand along with ELLIPSIS if present. + std::vector> op_labels(num_ops); + bool ell_in_input = false; + std::size_t curr_op = 0; + for (std::size_t i = 0; i < lhs.length(); ++i) { + const unsigned char label = lhs[i]; + switch (label) { + case ' ': + // Ignore spaces + break; + + case '.': + TORCH_CHECK( + // Only one ellipsis per operand can be given + !ell_in_input, + "einsum(): found \'.\' for operand ", + curr_op, + " for which an ellipsis was already found"); + TORCH_CHECK( + // Ensure it's a valid ellipsis + i + 2 < lhs.length() && lhs[++i] == '.' && lhs[++i] == '.', + "einsum(): found \'.\' for operand ", + curr_op, + " that is not part of any ellipsis"); + op_labels[curr_op].push_back(ELLIPSIS); + ell_in_input = true; + break; + + case ',': + // Move onto next operand + ++curr_op; + TORCH_CHECK( + curr_op < num_ops, + "einsum(): fewer operands were provided than specified in the equation"); + ell_in_input = false; + break; + + default: + // Parse label + TORCH_CHECK( + std::isalpha(label), + "einsum(): invalid subscript given at index ", + i, + " in the equation string, subscripts must be in [a-zA-Z]"); + op_labels[curr_op].push_back(label_to_subscript(label)); + } + } + + TORCH_CHECK( + curr_op == num_ops - 1, + "einsum(): more operands were provided than specified in the equation"); + + std::vector label_count(TOTAL_LABELS, 0); + + // The maximum number of dimensions covered by any ellipsis, needed when + // unsqueezing missing dimensions from operands to permute and broadcast + int64_t ell_num_dim = 0; + + // Compute label frequency and number of dimensions covered by ellipsis + // We do this after parsing labels to make it more readable and simpler + // to compute the number of dimensions covered by ellipsis. + for(const auto i : c10::irange(num_ops)) { + const auto& operand = operands[i]; + const auto labels = op_labels[i]; + const auto ndims = operand.dim(); + int64_t nlabels = static_cast(labels.size()); + bool has_ellipsis = false; + + for (const auto& label : labels) { + if (label == ELLIPSIS) { + --nlabels; + has_ellipsis = true; + ell_num_dim = std::max(ell_num_dim, ndims - nlabels); + } else { + ++label_count[label]; + } + } + + TORCH_CHECK( + has_ellipsis ? nlabels <= ndims : nlabels == ndims, + "einsum(): the number of subscripts in the equation (", + nlabels, + has_ellipsis ? ") is more than the number of dimensions (" + : ") does not match the number of dimensions (", + ndims, + ") for operand ", + i, + has_ellipsis ? "" : " and no ellipsis was given"); + } + + // We want to align the dimensions of every input tensor to have + // shape out_dims + sum_dims. For this, we create a mapping of label + // to index into the permuted shape. + std::vector label_perm_index(TOTAL_LABELS, -1); + + // Current index in the permuted shape + int64_t perm_index = 0; + + // Start index of ellipsis dimensions in the permuted shape + int64_t ell_index = 0; + bool ell_in_output = false; + + if (arrow_pos == std::string::npos) { + // Implicit output is ellipsis (...) + labels seen only once + perm_index = ell_num_dim; + // ell_in_output is used to stop us from reducing ellipses dims later + ell_in_output = true; + for (const auto label : c10::irange(TOTAL_LABELS)) { + if (label_count[label] == 1) { + label_perm_index[label] = perm_index++; + } + } + } else { + // Parse explicit output + const auto rhs = equation.substr(arrow_pos + 2); + for (std::size_t i = 0; i < rhs.length(); ++i) { + const unsigned char label = rhs[i]; + switch (label) { + case ' ': + // Ignore spaces + break; + + case '.': + TORCH_CHECK( + // There can only be one ellipsis in the output + !ell_in_output, + "einsum(): found \'.\' for output but an ellipsis (...) was already found"); + TORCH_CHECK( + // Ensure ellipsis is correct + i + 2 < rhs.length() && rhs[++i] == '.' && rhs[++i] == '.', + "einsum(): found \'.\' for output that is not part of any ellipsis (...)"); + ell_index = perm_index; + perm_index += ell_num_dim; + ell_in_output = true; + break; + + default: + TORCH_CHECK( + std::isalpha(label), + "einsum(): invalid subscript given at index ", + lhs.size() + 2 + i, + " in the equation string, subscripts must be in [a-zA-Z]"); + const auto index = label_to_subscript(label); + TORCH_CHECK( + // Ensure label appeared at least once for some input operand and at + // most once for the output + label_count[index] > 0 && label_perm_index[index] == -1, + "einsum(): output subscript ", + label, + label_perm_index[index] > -1 + ? " appears more than once in the output" + : " does not appear in the equation for any input operand"); + label_perm_index[index] = perm_index++; + } + } + } + + // Save number of dimensions in output before adding contraction dims (dims to sum out) + const int64_t out_num_dim = perm_index; + + // If ellipsis is not part of the output, add to contraction dimensions + if (!ell_in_output) { + ell_index = perm_index; + perm_index += ell_num_dim; + } + + // Add contraction labels (labels not present in output) + for (const auto label : c10::irange(TOTAL_LABELS)) { + if (label_count[label] > 0 && label_perm_index[label] == -1) { + label_perm_index[label] = perm_index++; + } + } + + // Next: we check the sizes, take diagonals for repeated labels, unsqueeze + // missing dimensions so all operands have the same dimensions and permute + // the operands to align the dimensions following the indices computed above. + // We also count how many operands have dimension with size != 1 for each + // label used to identify which dimensions can be contracted. + std::vector label_size(TOTAL_LABELS, 1); + std::vector ell_sizes(ell_num_dim, 1); + std::vector dim_counts(perm_index, 0); + std::deque ops; + for (const auto i : irange(num_ops)) { + auto op = operands[i]; + std::vector permutation(perm_index, -1); + std::int64_t dim = 0; + for (const auto s : op_labels[i]) { + if (s == ELLIPSIS) { + // Iterate over each dimension covered by ellipsis + const auto ndim = operands[i].ndimension() - (static_cast(op_labels[i].size()) - 1); + for (auto j = ell_num_dim - ndim; j < ell_num_dim; ++j) { + if (TORCH_GUARD_OR_TRUE(op.sym_size(dim).sym_ne(1))) { + // Update ellipsis size + TORCH_SYM_CHECK( + ell_sizes[j].sym_eq(1).sym_or(ell_sizes[j].sym_eq(op.sym_size(dim))), + "einsum(): dimension ", + dim, + " covered by ellipsis in operand ", + i, + "has size ", + op.size(dim), + " which does not broadcast with previously seen ellipsis with size ", + ell_sizes[j], + " for the respective dimension"); + ell_sizes[j] = op.sym_size(dim); + ++dim_counts[ell_index + j]; + } + permutation[ell_index + j] = dim++; + } + } else if (permutation[label_perm_index[s]] == -1) { + if (TORCH_GUARD_OR_TRUE(op.sym_size(dim).sym_ne(1))) { + // Update subscript + TORCH_SYM_CHECK( + label_size[s].sym_eq(1).sym_or(label_size[s].sym_eq(op.sym_size(dim))), + "einsum(): subscript ", + subscript_to_label(s), + " has size ", + op.sym_size(dim), + " for operand ", + i, + " which does not broadcast with previously seen size ", + label_size[s]); + label_size[s] = op.sym_size(dim); + ++dim_counts[label_perm_index[s]]; + } + permutation[label_perm_index[s]] = dim++; + } else { + // Repeated label, take diagonal + const auto prev_dim = permutation[label_perm_index[s]]; + TORCH_CHECK( + op.sym_size(dim) == op.sym_size(prev_dim), + "einsum(): subscript ", + subscript_to_label(s), + " is repeated for operand ", + i, + " but the sizes don't match, ", + op.sym_size(dim), + " != ", + op.sym_size(prev_dim)); + op = op.diagonal(0, prev_dim, dim).movedim(-1, prev_dim); + } + } + + // Add dimensions for missing labels + for (auto& val : permutation) { + if (val == -1) { + op = op.unsqueeze(dim); + val = dim++; + } + } + ops.emplace_back(op.permute(permutation)); + } + + const auto contract_path = path.value_or(std::vector{}); + auto it = contract_path.begin(); + + // Contract + while (ops.size() > 1) { + int64_t i = 0; + int64_t j = 1; + + if (path.has_value()) { + i = *it++; + j = *it++; + if (j < i) { + std::swap(i, j); + } + + TORCH_CHECK( + i != j && i >= 0 && j < static_cast(ops.size()), + "einsum(): invalid contraction (", + i, + ", ", + j, + i == j ? ") cannot contract an operand with itself" + : ") operand index is out of bounds"); + } + + auto a = ops[i]; + auto b = ops[j]; + ops.erase(ops.begin() + j); + ops.erase(ops.begin() + i); + + // Collect dimensions that can be summed now + std::vector sum_dims; + SmallVector a_dims_to_sum; + SmallVector b_dims_to_sum; + for (auto dim = out_num_dim; dim < perm_index; ++dim) { + auto sa = TORCH_GUARD_OR_TRUE(a.sym_size(dim).sym_ne(1)); + auto sb = TORCH_GUARD_OR_TRUE(b.sym_size(dim).sym_ne(1)); + + if (sa && sb) { + // if both a and b are equal, or we can't tell that its a broadcast for sure, + // we assume non-broadcast. + TORCH_SYM_CHECK(a.sym_size(dim).sym_eq(b.sym_size(dim)), "non-broadcast dimensions must match"); + if (--dim_counts[dim] == 1) { + sum_dims.push_back(dim); + dim_counts[dim] = 0; + } + } else if (dim_counts[dim] == 1) { + if (sa) { + a_dims_to_sum.push_back(dim); + dim_counts[dim] = 0; + } else if (sb) { + b_dims_to_sum.push_back(dim); + dim_counts[dim] = 0; + } + } + } + + // Sum multiple dims at a time to minimize the number of kernel calls to sum + if (!a_dims_to_sum.empty()) { + a = a.sum(a_dims_to_sum, true); + } + if (!b_dims_to_sum.empty()) { + b = b.sum(b_dims_to_sum, true); + } + + if (path.has_value()) { + ops.emplace_back(sumproduct_pair(a, b, sum_dims, true)); + } else { + ops.emplace_front(sumproduct_pair(a, b, sum_dims, true)); + } + } + + // Sum out contraction dims + if (perm_index - out_num_dim > 0) { + // if there were ops to contract, we would have already done so + // in the previous loop and all the dims to sum are now 1 + // NB: use view instead of squeeze (or sum) for faster (mps) performance + if (num_ops > 1) { + auto sizes = ops[0].sym_sizes().vec(); + for (auto dim = perm_index - 1; dim >= out_num_dim; --dim) { + sizes.erase(sizes.begin() + dim); + } + return ops[0].view_symint(sizes); + } else { + std::vector sum_dims(perm_index - out_num_dim); + std::iota(sum_dims.begin(), sum_dims.end(), out_num_dim); + return ops[0].sum(sum_dims); + } + } + + return std::move(ops[0]); +} + +// _trilinear computes a trilinear einstein sum with an unrolled dimension +// the result is `(i1.unsqueeze(expand1)*i2.unsqueeze(expand2)*i2.unsqueeze(expand3)).sum(sumdim)` +// the computation is unrolled in the unroll_dim dimension +// its main purpose is to unify the computations in bilinear and bilinear_backward +Tensor _trilinear(const Tensor& i1_, const Tensor& i2_, const Tensor& i3_, + IntArrayRef expand1_, IntArrayRef expand2_, IntArrayRef expand3_, + IntArrayRef sumdim_, int64_t unroll_dim) { + int64_t total_dim = i1_.dim()+expand1_.size(); + TORCH_CHECK((unroll_dim >= 0) && (unroll_dim < total_dim), "unroll_dim must be in [0,", total_dim-1, "]"); + auto expand1 = at::dim_list_to_bitset(expand1_, total_dim); + auto expand2 = at::dim_list_to_bitset(expand2_, total_dim); + auto expand3 = at::dim_list_to_bitset(expand3_, total_dim); + auto sumdim = at::dim_list_to_bitset(sumdim_, total_dim); + Tensor i1 = i1_; + Tensor i2 = i2_; + Tensor i3 = i3_; + std::vector output_size; + std::vector sum_dims_12, sum_dims_23; + output_size.reserve(total_dim); + int64_t unroll_size = -1; + // asserts... + for (const auto i : c10::irange(total_dim)) { + c10::SymInt s = 0; + if (expand1[i]) { + i1 = i1.unsqueeze(i); + } else { + s = i1.sym_size(i); + } + if (expand2[i]) { + i2 = i2.unsqueeze(i); + } else { + s = i2.sym_size(i); + } + if (expand3[i]) { + i3 = i3.unsqueeze(i); + if (sumdim[i] && (i != unroll_dim)) + sum_dims_12.push_back(i); + } else { + s = i3.sym_size(i); + if (sumdim[i] && (i != unroll_dim)) + sum_dims_23.push_back(i); + } + output_size.push_back(sumdim[i] ? 1 : s); + if (i == unroll_dim) + unroll_size = s.guard_int(__FILE__, __LINE__); + } + int64_t slicemul1 = (expand1[unroll_dim] ? 0 : 1); + int64_t slicemul2 = (expand2[unroll_dim] ? 0 : 1); + int64_t slicemul3 = (expand3[unroll_dim] ? 0 : 1); + + auto output = at::zeros_symint(output_size, i1.options()); + + // Three conditionals are necessary since this function is meant to work for both + // forward and backward, which changes the dimensions of the inputs. + // Note that if output has zero elems is because (at least) one of i1, i2, i3 has zero elems. + if (i1.sym_numel() != 0 && i2.sym_numel() != 0 && i3.sym_numel() != 0) { + if (! sumdim[unroll_dim]) { + for (const auto k : c10::irange(unroll_size)) { + Tensor buf = at::native::sumproduct_pair(i1.narrow(unroll_dim, k * slicemul1, 1), + i2.narrow(unroll_dim, k * slicemul2, 1), + sum_dims_12, true); + buf = at::native::sumproduct_pair(buf, i3.narrow(unroll_dim, k * slicemul3, 1), sum_dims_23, true); + output.narrow(unroll_dim, k, 1).add_(buf); + } + } + else { + for (const auto k : c10::irange(unroll_size)) { + Tensor buf = at::native::sumproduct_pair(i1.narrow(unroll_dim, k*slicemul1, 1), + i2.narrow(unroll_dim, k*slicemul2, 1), sum_dims_12, true); + buf = at::native::sumproduct_pair(buf, i3.narrow(unroll_dim, k*slicemul3, 1), sum_dims_23, true); + output.add_(buf); + } + } + } + for (int64_t i = output.dim()-1; i >= 0; i--) + if (sumdim[i]) + output.squeeze_(i); + return output; +} + +Tensor bilinear(const Tensor& input1, const Tensor& input2, const Tensor& weight, const std::optional& bias_opt) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + if (bias.defined()) { + TORCH_CHECK( + input1.dtype() == input2.dtype() && input1.dtype() == weight.dtype() && + input1.dtype() == bias.dtype(), + "All tensors must have the same dtype, got input1: ", + input1.dtype(), + ", input2: ", + input2.dtype(), + ", weight: ", + weight.dtype(), + ", bias: ", + bias.dtype()); + } else { + TORCH_CHECK( + input1.dtype() == input2.dtype() && input1.dtype() == weight.dtype(), + "All tensors must have the same dtype, got input1: ", + input1.dtype(), + ", input2: ", + input2.dtype(), + ", weight: ", + weight.dtype()); + } + + TORCH_CHECK(input1.dim() == input2.dim(), "bilinear(): input dimensions do not match: got ", input1.dim(), " and ", input2.dim()); + for (const auto i : c10::irange(input1.dim() - 1)) { + TORCH_CHECK(input1.sym_size(i) == input2.sym_size(i), + "bilinear(): input batch dimensions do not match at dim ", i, ": got ", input1.sym_size(i), " and ", input2.sym_size(i)); + } + TORCH_CHECK(input1.sym_size(input1.dim() - 1) == weight.sym_size(1), + "bilinear(): input1 size does not match weight size: got ", + input1.sym_size(input1.dim() - 1), " but expected ", weight.sym_size(1)); + TORCH_CHECK(input2.sym_size(input2.dim() - 1) == weight.sym_size(2), + "bilinear(): input2 size does not match weight size: got ", + input2.sym_size(input2.dim() - 1), " but expected ", weight.sym_size(2)); + TORCH_CHECK(!bias.defined() || bias.sym_size(0) == weight.sym_size(0), + "bilinear(): bias size does not match weight size: got ", + bias.sym_size(0), " but expected ", weight.sym_size(0)); + + std::vector output_size; + auto size1 = input1.sym_sizes(); + output_size.reserve(size1.size()); + output_size.insert(output_size.end(), size1.begin(), size1.end() - 1); + output_size.push_back(weight.sym_size(0)); + auto input1_flattened = input1.reshape_symint({-1, input1.sym_size(-1)}); + auto input2_flattened = input2.reshape_symint({-1, input2.sym_size(-1)}); + Tensor output = at::_trilinear(input1_flattened, weight, input2_flattened, {1,3}, {0}, {1,2}, {2,3}).reshape_symint(output_size); + if (bias.defined()) { + output = output + bias; + } + return output; +} + +// implements tensordot, a matrix-multiplication-like contraction, but the dimensions given +// in the two dimension lists +Tensor tensordot(const Tensor& input1, const Tensor& input2, IntArrayRef dims1, IntArrayRef dims2) { + TORCH_CHECK(dims1.size() == dims2.size(), "both dimension lists should have same length"); + TORCH_CHECK(input1.scalar_type() == input2.scalar_type(), "both inputs should have same dtype"); + SymInt csize = 1; // total size of the contracted dimensions + Tensor t1 = input1; + Tensor t2 = input2; + for (const auto i : c10::irange(dims1.size())) { + SymInt s1 = input1.sym_size(dims1[i]); + SymInt s2 = input2.sym_size(dims2[i]); + if (s2 == 1) { // broadcasted dimensions can be summed right away + t1 = t1.sum(dims1[i], true, t1.scalar_type()); + } else if (s1 == 1) { + t2 = t2.sum(dims2[i], true, t2.scalar_type()); + } else { + TORCH_CHECK(s1 == s2, "contracted dimensions need to match, but first has size ", s1, " in dim ", dims1[i], + " and second has size ", s2, " in dim ", dims2[i]); + csize *= s1; + } + } + + auto cdims1 = at::dim_list_to_bitset(dims1, input1.dim()); + auto cdims2 = at::dim_list_to_bitset(dims2, input2.dim()); + std::vector p1, p2; // p1, p2: input permutations + std::vector rsizes; // rsizes: sizes of the result + p1.reserve(input1.dim()); + p2.reserve(input2.dim()); + rsizes.reserve(input1.dim() + input2.dim() - static_cast(dims1.size())); + SymInt size1 = 1; // number of non-contracted elements in input1 + SymInt size2 = 1; // number of non-contracted elements in input2 + + // fill the permutations and compute sizes + for (const auto i : c10::irange(input1.dim())) { + if (! cdims1[i]) { + p1.emplace_back(i); + size1 *= t1.sym_size(i); + rsizes.emplace_back(t1.sym_size(i)); + } + } + for (const auto x : dims1) { + p1.emplace_back(x); + } + for (const auto x : dims2) { + p2.emplace_back(x); + } + for (const auto i : c10::irange(input2.dim())) { + if (! cdims2[i]) { + p2.emplace_back(i); + size2 *= t2.sym_size(i); + rsizes.emplace_back(t2.sym_size(i)); + } + } + + // Full contraction (size1 == 1 and size2 == 1) is much faster when done with dot ... + // TODO(@nikitaved): there are other cases where dot outperforms gemms, + // like, for example, when the non-contracted dims are relatively small. + // NOTE(@nikitaved): contract with gemm when on MPS, + // otherwise issues with the tests xpassing/xfailing + // when enabling the fast-path with dot. + // TODO: resolve that + if ((t1.device().type() == at::kMPS || t2.device().type() == at::kMPS) || size1 != 1 || size2 != 1) { + // permute and reshape for matrix multiplication + t1 = t1.permute(p1).reshape_symint({size1, csize}); + t2 = t2.permute(p2).reshape_symint({csize, size2}); + // multiply and reshape to target size + return at::mm(t1, t2).reshape_symint(rsizes); + } else { + // permute to align for contraction + t1 = t1.permute(p1); + t2 = t2.permute(p2); + + if (t1.is_contiguous() && t2.is_contiguous()) { + // If t1 and t2 are both contiguous, then flatten is a view, + // then dot is the method of choice + return at::dot(t1.flatten(), t2.flatten()).reshape_symint(rsizes); + } else { + // Otherwise mul + sum can be faster as it avoids at most 2x contiguous() calls + // NOTE: t1.dtype == t2.dtype -- check above + return (t1.squeeze() * t2.squeeze()).sum(t1.scalar_type()).reshape_symint(rsizes); + } + } +} + +Tensor &tensordot_out(const Tensor& input1, const Tensor& input2, IntArrayRef dims1, IntArrayRef dims2, Tensor& result) { + Tensor result_tmp = at::native::tensordot(input1, input2, dims1, dims2); + auto result_dtype = result_tmp.scalar_type(); + auto output_tensor_dtype = result.scalar_type(); + auto output_device = result.device(); + auto input1_device = input1.device(); + auto input2_device = input2.device(); + + if(result.defined()) { + TORCH_CHECK( + !(result.requires_grad() && at::GradMode::is_enabled() && result.sizes() != result_tmp.sizes()), + "tensordot(): the 'out' tensor was specified and requires gradients, and its shape does not match the expected result. " + "Either remove the 'out' argument, ensure it does not require gradients, or make sure its shape matches the expected output." + ); + } + // check if the input & output tensors are on the same device. + TORCH_CHECK( + (output_device == input1_device) && (input1_device == input2_device), + "tensordot: Expected the output and input tensors to be on the " + "same device, but got the output tensor on ", output_device, + ", input tensor a on ", input1_device, ", and input tensor b on ", input2_device); + // check if the computed result has the same dtype as the out tensor + // (because tensordot does not support type promotion) + TORCH_CHECK( + result_dtype == output_tensor_dtype, "tensordot", + ": Expected the output tensor to have dtype ", result_dtype, + ", but got an output tensor with dtype ", output_tensor_dtype); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebra.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebra.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80fd71c1002a49ca319e3f9ea454acbec3fd23fb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebra.cpp @@ -0,0 +1,3803 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#if !defined(__s390x__) && !defined(__powerpc__) +#include +#endif + +namespace at { + +namespace detail { + static void check_linalg_norm_dtype(std::optional opt_dtype, ScalarType self_dtype, const char* const name) { + if (opt_dtype.has_value()) { + auto dtype = opt_dtype.value(); + TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype), name, ": dtype should" + " be floating point or complex, but got ", dtype); + TORCH_CHECK(isComplexType(self_dtype) == isComplexType(dtype), + name, ": dtype should be ", isComplexType(self_dtype) ? "complex" : "real", + " for ", isComplexType(self_dtype) ? "complex" : "real", " inputs, but got ", dtype); + TORCH_CHECK(promoteTypes(self_dtype, dtype) == dtype, + name, ": the dtype of the input ", "(", self_dtype, ") should be convertible ", + "without narrowing to the specified dtype (", dtype, ")"); + } + } +} + +namespace meta { + +#define ADDMM_META() \ + TORCH_CHECK(self.scalar_type() == mat2.scalar_type(), "self and mat2 must have the same dtype, but got ", self.scalar_type(), " and ", mat2.scalar_type()); \ + TORCH_CHECK(mat1.scalar_type() == mat2.scalar_type(), "mat1 and mat2 must have the same dtype, but got ", mat1.scalar_type(), " and ", mat2.scalar_type()); \ + TORCH_CHECK(mat1.dim() == 2, "mat1 must be a matrix, got ", mat1.dim(), "-D tensor"); \ + TORCH_CHECK(mat2.dim() == 2, "mat2 must be a matrix, got ", mat2.dim(), "-D tensor"); \ + TORCH_CHECK( \ + mat1.sizes()[1] == mat2.sizes()[0], "mat1 and mat2 shapes cannot be multiplied (", \ + mat1.sizes()[0], "x", mat1.sizes()[1], " and ", mat2.sizes()[0], "x", mat2.sizes()[1], ")"); \ + set_output_raw_strided(0, {mat1.sizes()[0], mat2.sizes()[1]}, {}, mat1.options()); + +TORCH_META_FUNC(addmm)(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha) { + ADDMM_META(); +} + +TORCH_META_FUNC(_addmm_activation)(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha, bool use_gelu) { + ADDMM_META(); +} + +TORCH_META_FUNC(mm)(const Tensor & self, const Tensor & mat2) { + TORCH_CHECK(self.dim() == 2, "self must be a matrix"); + TORCH_CHECK(mat2.dim() == 2, "mat2 must be a matrix"); + TORCH_CHECK( + self.sizes()[1] == mat2.sizes()[0], "mat1 and mat2 shapes cannot be multiplied (", + self.sizes()[0], "x", self.sizes()[1], " and ", mat2.sizes()[0], "x", mat2.sizes()[1], ")"); + + set_output_raw_strided(0, {self.sizes()[0], mat2.sizes()[1]}, {}, self.options()); +} + +TORCH_META_FUNC(linalg_vector_norm)(const Tensor& self, const Scalar& scalar_ord, OptionalIntArrayRef opt_dim, bool keepdim, std::optional opt_dtype) { + at::native::checkFloatingOrComplex(self, "linalg.vector_norm"); + TORCH_CHECK(!at::isComplexType(scalar_ord.type()), "linalg.vector_norm: Expected a non-complex scalar as the order of norm."); + + auto dim = opt_dim.value_or(IntArrayRef{}); + // Casting a large integer to a double will just introduce an error for + // values larger than 10^53 (same for negative numbers), so that's fine. + auto ord = scalar_ord.toDouble(); + + // For more context, see issue 52783 + // If the tensor is empty and norm < 0 || norm == infty + // - We cannot reduce the whole tensor + // - We cannot reduce over an empty dimension + if (self.numel() == 0 && (ord < 0. || ord == INFINITY)) { + // dim=None or dim=() reduces the whole tensor + TORCH_CHECK(opt_dim.has_value() && !opt_dim->empty(), + "linalg.vector_norm cannot compute the ", scalar_ord, " norm on an empty ", + "tensor because the operation does not have an identity"); + for (auto dim_num : dim) { + TORCH_CHECK(self.size(dim_num) != 0, + "linalg.vector_norm cannot compute the ", scalar_ord, " norm on the dimension ", dim_num , + "because this dimension is empty and the operation does not have an identity"); + } + } + + at::detail::check_linalg_norm_dtype(opt_dtype, self.scalar_type(), "linalg.vector_norm"); + + auto mask = at::native::make_dim_mask(dim, self.dim()); + auto shape = at::native::shape_from_dim_mask(self, std::move(mask), keepdim); + auto options = self.options() + .dtype(toRealValueType(opt_dtype.value_or(self.scalar_type()))); + + set_output_raw_strided(0, shape, {}, options); +} + +TORCH_META_FUNC(_linalg_det)(const Tensor& A) { + at::native::squareCheckInputs(A, "linalg.det"); + at::native::checkFloatingOrComplex(A, "linalg.det"); + + auto shape = A.sizes(); + auto ndim = shape.size(); + + // det + set_output_contiguous(0, shape.slice(0, ndim - 2), A.options()); + + // LU + auto LU_strides = at::native::batched_matrix_contiguous_strides(shape, /*f-contig*=*/true); + set_output_strided(1, shape, LU_strides, A.options()); + + // pivots + set_output_contiguous(2, shape.slice(0, ndim - 1), A.options().dtype(kInt)); +} + +TORCH_META_FUNC(_linalg_slogdet)(const Tensor& A) { + at::native::squareCheckInputs(A, "linalg.slogdet"); + at::native::checkFloatingOrComplex(A, "linalg.slogdet", /*low_precision*/false); + + auto shape= A.sizes(); + auto ndim = shape.size(); + + auto shape_outputs = shape.slice(0, ndim - 2); + + // sign + set_output_contiguous(0, shape_outputs, A.options()); + + // logabsdet + set_output_contiguous(1, shape_outputs, A.options().dtype(toRealValueType(A.scalar_type()))); + + // LU + auto LU_strides = at::native::batched_matrix_contiguous_strides(shape, /*f-contig*=*/true); + set_output_strided(2, shape, LU_strides, A.options()); + + // pivots + set_output_contiguous(3, shape.slice(0, ndim - 1), A.options().dtype(kInt)); +} + +template +static void common_checks_baddbmm_bmm(Meta& meta, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha, bool is_bmm, const std::optional& self_baddbmm = std::nullopt) { + TORCH_CHECK(batch1.dim() == 3, "batch1 must be a 3D tensor"); + TORCH_CHECK(batch2.dim() == 3, "batch2 must be a 3D tensor"); + + const auto batch1_sizes = batch1.sizes(); + const auto batch2_sizes = batch2.sizes(); + + int64_t bs = batch1_sizes[0]; + int64_t contraction_size = batch1_sizes[2]; + int64_t res_rows = batch1_sizes[1]; + int64_t res_cols = batch2_sizes[2]; + std::vector output_size {bs, res_rows, res_cols}; + + TORCH_CHECK(batch2_sizes[0] == bs && batch2_sizes[1] == contraction_size, + "Expected size for first two dimensions of batch2 tensor to be: [", + bs, ", ", contraction_size, "] but got: [", batch2_sizes[0], ", ", batch2_sizes[1], "]."); + + auto& result = meta.maybe_get_output(0); + // 'set_output' does not resize for in-place calls + meta.set_output_raw_strided(0, output_size, {}, batch2.options()); + const auto result_sizes = result.sizes(); + // Error is raised if called from in-place overload with incorrect shape + TORCH_CHECK(result_sizes == output_size, + "Expected an output tensor with shape [", output_size, "] but got shape ", result_sizes); + + if (!is_bmm) { + if (self_baddbmm.has_value()) { + const auto& self = self_baddbmm.value(); + if (beta.toComplexDouble() != 0.0) result.copy_(self); + TORCH_CHECK(self.dim() == 3, "self must be a 3D tensor"); + const auto self_sizes = self.sizes(); + TORCH_CHECK(self_sizes == output_size, + "Expected an input tensor shape with shape ", output_size, " but got shape: ", self_sizes); + } + } else { + } + +} + +TORCH_META_FUNC(bmm)(const Tensor& self, const Tensor& mat2) { + common_checks_baddbmm_bmm(*this, self, mat2, Scalar(0.0), Scalar(1.0), true); +} + +TORCH_META_FUNC(baddbmm)(const Tensor& self, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha) { + auto self_ = expand_size(self, {batch1.size(0), batch1.size(1), batch2.size(2)}, "baddbmm"); + TORCH_CHECK(self.dtype() == batch1.dtype(), "Input dtypes must be the same, got: input ", self.dtype(), ", batch1: ", batch1.dtype(), ", batch2: ", batch2.dtype()); + common_checks_baddbmm_bmm(*this, batch1, batch2, beta, alpha, false, *self_); +} + +} // namespace meta +namespace native { + +DEFINE_DISPATCH(addr_stub); + + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg.det ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// As P is a permutation matrix +// det(P) = 1 if it's an even permutation and det(P) = -1 if it's an odd permutation +static Tensor lu_det_P(const Tensor& pivots) { + return (at::arange(1, pivots.size(-1) + 1, pivots.options()) != pivots) + .sum(-1, /*keepdim=*/false, /*dtype=*/at::kLong) + .fmod_(2) + // take 0 to 1 and 1 to -1 + .mul_(-2) + .add_(1); +} + +// Auxiliary function that returns the LU decomposition to use it in the backward +TORCH_IMPL_FUNC(_linalg_det_out)(const Tensor& A, const Tensor& result, const Tensor& LU, const Tensor& pivots) { + // info is an aux tensor + auto info = at::empty({0}, A.options().dtype(kInt)); + // Optimisation: lu_factor_ex requires the input to be F-contig, otherwise it copies + // Use the transpose of if A is contiguous since det(A^T) = det(A) + // We limit this to real matrices, but it could also be implemented for complex matrices + at::linalg_lu_factor_ex_out(const_cast(LU), const_cast(pivots), const_cast(info), A.is_contiguous() && !A.is_complex() ? A.mH() : A); + + // det = det_P * prod(diag(LU)) + at::mul_out(const_cast(result), lu_det_P(pivots), at::prod(LU.diagonal(0, -2 ,-1), /*dim=*/-1)); +} + +Tensor linalg_det(const Tensor& A) { + return std::get<0>(at::_linalg_det(A)); +} + +Tensor& linalg_det_out(const Tensor& A, Tensor& result) { + auto LU = at::empty({0}, A.options()); + auto pivots = at::empty({0}, A.options().dtype(kInt)); + at::_linalg_det_out(result, LU, pivots, A); + return result; +} + +// torch.det, alias for torch.linalg.det +Tensor det(const Tensor& self) { + return at::linalg_det(self); +} + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg.slogdet ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +// Auxiliary function that returns the LU decomposition to use it in the backward +TORCH_IMPL_FUNC(_linalg_slogdet_out)(const Tensor& A, const Tensor& sign, const Tensor& logabsdet, const Tensor& LU, const Tensor& pivots) { + // info is an aux tensor + auto info = at::empty({0}, A.options().dtype(kInt)); + // Optimisation: lu_factor_ex requires the input to be F-contig, otherwise it copies + // Use the transpose of if A is contiguous since det(A^T) = det(A) + // We limit this to real matrices, but it could also be implemented for complex matrices + at::linalg_lu_factor_ex_out(const_cast(LU), const_cast(pivots), const_cast(info), A.is_contiguous() && !A.is_complex() ? A.mH() : A); + + auto diag_U = LU.diagonal(0, -2, -1); + // sign + at::mul_out(const_cast(sign), diag_U.sgn().prod(-1), lu_det_P(pivots)); + + // logabsdet + at::sum_out(const_cast(logabsdet), diag_U.abs().log_(), -1); +} + +std::tuple linalg_slogdet(const Tensor& A) { + auto out = at::_linalg_slogdet(A); + return std::make_tuple(std::move(std::get<0>(out)), std::move(std::get<1>(out))); +} + +std::tuple linalg_slogdet_out(const Tensor& A, Tensor& sign, Tensor& logabsdet) { + auto LU = at::empty({0}, A.options()); + auto pivots = at::empty({0}, A.options().dtype(kInt)); + at::_linalg_slogdet_out(sign, logabsdet, LU, pivots, A); + return std::tie(sign, logabsdet); +} + +// Alias +std::tuple slogdet(const Tensor& A) { + return at::linalg_slogdet(A); +} + +std::tuple slogdet_out(const Tensor& A, Tensor& sign, Tensor& logabsdet) { + return at::linalg_slogdet_out(sign, logabsdet, A); +} + +//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ logdet ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Tensor logdet(const Tensor& A) { + squareCheckInputs(A, "logdet"); + checkFloatingOrComplex(A, "logdet", /*low_precision*/false); + auto [sign, logabsdet] = at::linalg_slogdet(A); + + if (A.is_complex()) { + return sign.log() + logabsdet; + } else { + return at::where(sign == -1., NAN, logabsdet); + } +} + +namespace { + +// This function extracts the optional Tensors for atol and rtol +// Default value for atol is zero +// Default value for rtol is eps*max(rows, cols) +// If atol is specified and rtol is not specified then default value for rtol is zero +// It is used for matrix_rank and pinv +std::tuple get_atol_rtol( + const Tensor& input, + const std::optional& atol_opt, + const std::optional& rtol_opt, + const std::string_view function_name) { + auto options = input.options(); + if (input.device().type() == kMetal || input.device().type() == kMPS) { + options = options.dtype(ScalarType::Float); + } else { + options = options.dtype(ScalarType::Double); + } + auto atol = atol_opt.has_value() ? atol_opt.value() : at::zeros({}, options); + checkNotComplexTolerance(atol, function_name, "atol"); + Tensor rtol; + if (rtol_opt.has_value()) { + rtol = rtol_opt.value(); + checkNotComplexTolerance(rtol, function_name, "rtol"); + } else { + ScalarType real_dtype = toRealValueType(input.scalar_type()); + auto default_rtol = at::full({}, _get_epsilon(real_dtype) * std::max(input.sym_size(-1), input.sym_size(-2)), options); + rtol = atol_opt.has_value() + ? at::where(atol_opt.value() > 0, at::zeros({}, options), default_rtol) + : std::move(default_rtol); + } + return std::make_tuple(std::move(atol), std::move(rtol)); +} + +std::tuple get_atol_rtol( + const Tensor& input, + std::optional atol_opt, + std::optional rtol_opt) { + auto atol = atol_opt.has_value() ? atol_opt.value() : 0.0; + c10::SymFloat rtol; + if (rtol_opt.has_value()) { + rtol = rtol_opt.value(); + } else { + ScalarType real_dtype = toRealValueType(input.scalar_type()); + auto default_rtol = _get_epsilon(real_dtype) * std::max(input.sym_size(-1), input.sym_size(-2)); + rtol = (atol_opt.has_value() && atol_opt.value() > 0.0) + ? 0.0 + : default_rtol; + } + auto options = input.options(); + if (input.device().type() == kMetal || input.device().type() == kMPS) { + options = options.dtype(ScalarType::Float); + } else { + options = options.dtype(ScalarType::Double); + } + auto atol_tensor = at::full({}, atol, options); + auto rtol_tensor = at::full({}, rtol, options); + return std::make_tuple(std::move(atol_tensor), std::move(rtol_tensor)); +} + +} // anonymous namespace + +Tensor linalg_pinv( + const Tensor& input, + const std::optional& atol_opt, + const std::optional& rtol_opt, + bool hermitian) { + // FIXME: Whenever we have a nice lstsq, we should dispatch this function to simply be + // `torch.lstsq(A, torch.eye(A.shape[-1]), atol=atol, rtol=rtol)` + // with a driver that supports singular inputs + NoTF32Guard disable_tf32; + ScalarType t = input.scalar_type(); + TORCH_CHECK((t == ScalarType::Double || t == ScalarType::Float || t == ScalarType::ComplexFloat || t == ScalarType::ComplexDouble) + && input.dim() >= 2, + "linalg.pinv(", t, "{", input.sizes(), "}): expected a tensor with 2 or more dimensions " + "of float, double, cfloat or cdouble types"); + + auto [atol, rtol] = get_atol_rtol(input, atol_opt, rtol_opt, "torch.linalg.pinv"); + + if (input.sym_numel() == 0) { + // The implementation below uses operations that do not work for zero numel tensors + // therefore we need this early return for 'input.numel() == 0' case + // TODO: replace input.svd with linalg_svd when torch/xla can work with at::linalg_svd + auto [U, S, V] = input.svd(); + return at::matmul(V * S.reciprocal().unsqueeze(-2), U.mH()); + } + + // If not Hermitian use singular value decomposition, else use eigenvalue decomposition + if (!hermitian) { + // TODO: replace input.svd with linalg_svd + // using linalg_svd breaks pytorch/xla, see https://github.com/pytorch/xla/issues/2755 + auto [U, S, V] = input.svd(); + Tensor max_val = at::narrow(S, /*dim=*/-1, /*start=*/0, /*length=*/1); // singular values are sorted in descending order + Tensor tol = at::max(atol.unsqueeze(-1), rtol.unsqueeze(-1) * max_val); + Tensor S_pseudoinv = at::where(S > tol, S.reciprocal(), at::zeros({}, S.options())).to(input.dtype()); + // computes V @ diag(S_pseudoinv) @ U.conj().T + return at::matmul(V * S_pseudoinv.unsqueeze(-2), U.mH()); + } else { + auto [S, U] = at::linalg_eigh(input); + // For Hermitian matrices, singular values equal to abs(eigenvalues) + Tensor S_abs = S.abs(); + // eigenvalues are sorted in ascending order starting with negative values, we need a maximum value of abs(eigenvalues) + Tensor max_val = S_abs.amax(/*dim=*/-1, /*keepdim=*/true); + Tensor tol = at::max(atol.unsqueeze(-1), rtol.unsqueeze(-1) * max_val); + Tensor S_pseudoinv = at::where(S_abs > tol, S.reciprocal(), at::zeros({}, S.options())).to(input.dtype()); + // computes U @ diag(S_pseudoinv) @ U.conj().T + return at::matmul(U * S_pseudoinv.unsqueeze(-2), U.mH()); + } +} + +Tensor linalg_pinv(const Tensor& input, std::optional atol, std::optional rtol, bool hermitian) { + auto [atol_tensor, rtol_tensor] = get_atol_rtol(input, atol, rtol); + return at::linalg_pinv(input, atol_tensor, rtol_tensor, hermitian); +} + +Tensor linalg_pinv(const Tensor& input, const Tensor& rcond, bool hermitian) { + // For NumPy compatibility the rcond argument is used as relative tolerance + checkNotComplexTolerance(rcond, "torch.linalg.pinv", "rcond"); + auto options = input.options(); + if (input.device().type() == kMetal || input.device().type() == kMPS) { + options = options.dtype(ScalarType::Float); + } else { + options = options.dtype(ScalarType::Double); + } + return at::linalg_pinv(input, at::zeros({}, options), rcond, hermitian); +} + +Tensor linalg_pinv(const Tensor& input, double rcond, bool hermitian) { + // For NumPy compatibility the rcond argument is used as relative tolerance + return at::linalg_pinv(input, 0.0, rcond, hermitian); +} + +// TODO: implement _out variant avoiding copy and using already allocated storage directly +Tensor& linalg_pinv_out( + const Tensor& input, + const std::optional& atol, + const std::optional& rtol, + bool hermitian, + Tensor& result) { + checkSameDevice("linalg.pinv", result, input); + checkLinalgCompatibleDtype("linalg.pinv", result, input); + Tensor result_tmp = at::linalg_pinv(input, atol, rtol, hermitian); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +Tensor& linalg_pinv_out( + const Tensor& input, + std::optional atol, + std::optional rtol, + bool hermitian, + Tensor& result) { + checkSameDevice("linalg.pinv", result, input); + checkLinalgCompatibleDtype("linalg.pinv", result, input); + Tensor result_tmp = at::linalg_pinv(input, atol, rtol, hermitian); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +Tensor& linalg_pinv_out(const Tensor& input, const Tensor& rcond, bool hermitian, Tensor& result) { + checkSameDevice("linalg.pinv", result, input); + checkLinalgCompatibleDtype("linalg.pinv", result, input); + + Tensor result_tmp = at::linalg_pinv(input, rcond, hermitian); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +Tensor& linalg_pinv_out(const Tensor& input, double rcond, bool hermitian, Tensor& result) { + Tensor rcond_tensor = at::full({}, rcond, input.options().dtype(ScalarType::Double)); + return at::linalg_pinv_out(result, input, rcond_tensor, hermitian); +} + +Tensor pinverse(const Tensor& self, double rcond) { + return at::linalg_pinv(self, rcond, /*hermitian=*/false); +} + +// matrix_power implementation +namespace { + +/** + * @brief Raises the input matrix to the given power n + * + * If the exponent n is negative, the inverse of the input + * matrix will be raised to power abs(n). + * + * @param self (batched) square matrix to raise to power n + * @param n exponent to raise matrix (or matrices in batch) to + * @param _out optional tensor to write the output to + * @return Tensor input matrix raised to power n + */ +Tensor linalg_matrix_power_impl( + const Tensor& self, + int64_t n, + std::optional _out) { + NoTF32Guard disable_tf32; + auto out = _out.value_or(Tensor()); + + squareCheckInputs(self, "linalg.matrix_power"); + if (_out.has_value()) { + checkSameDevice("matrix_power", out, self); + checkLinalgCompatibleDtype("matrix_power", out, self); + at::native::resize_output_symint(out, self.sym_sizes()); + } + + // For n=0 we return the identity matrix of the same shape as input. + if (n == 0) { + if (!_out.has_value()) { + // Clone input to include result in the autograd graph + out = self.clone(at::MemoryFormat::Contiguous); + } + return out.copy_(at::eye_symint(self.sym_size(-2), self.options())); + } + if (n == 1) { + return _out.has_value() ? out.copy_(self) + : self.clone(at::MemoryFormat::Contiguous); + } + if (n == -1) { + return _out.has_value() ? at::linalg_inv_out(out, self) + : at::linalg_inv(self); + } + + // For negative n we inverte the input matrix before raising to power abs(n) + auto a = n < 0 ? at::linalg_inv(self) : self; + n = std::abs(n); + + // Fast paths for small powers + if (n == 2) { + return _out.has_value() ? at::matmul_out(out, a, a) : at::matmul(a, a); + } + if (n == 3) { + return _out.has_value() ? at::matmul_out(out, at::matmul(a, a), a) + : at::matmul(at::matmul(a, a), a); + } + + // This is a binary decomposition of n. + // Moving from the least significant bit to the most significant bit + // This is done to reduce the number of matrix multiplications + // by raising the input matrix in powers of 2 + // The total number of matrix multiplications are + // number of bits + number of bits that equal 1 ~ O(log n) + // instead of O(n) + Tensor z, result; + while (n > 0) { + const auto bit = n % 2; + n = n / 2; + z = z.defined() ? at::matmul(z, z) : a; + if (bit == 1) { + if (_out.has_value() && n <= 0) { + // Last multiplication can use the out version + return result.defined() ? at::matmul_out(out, result, z) : out.copy_(z); + } + result = result.defined() ? at::matmul(result, z) : z; + } + } + + return result; +} + +} // namespace + +Tensor& linalg_matrix_power_out(const Tensor& self, int64_t n, Tensor& result) { + linalg_matrix_power_impl(self, n, result); + return result; +} + +Tensor linalg_matrix_power(const Tensor& self, int64_t n) { + return linalg_matrix_power_impl(self, n, std::nullopt); +} + +Tensor& matrix_power_out(const Tensor& self, int64_t n, Tensor& result) { + return at::native::linalg_matrix_power_out(self, n, result); +} + +Tensor matrix_power(const Tensor& self, int64_t n) { + return at::native::linalg_matrix_power(self, n); +} + +namespace { + +// Computes the rank of 'input' and saves the result in-place in 'result'. +// 'hermitian' controls whether SVD or eigendecomposition is used for computing the singular values +// 'atol' and 'rtol' are the absolute and relative tolerances, respectively. +Tensor& matrix_rank_impl( + const Tensor& input, + const std::optional& atol_opt, + const std::optional& rtol_opt, + bool hermitian, + Tensor& result) { + auto [atol, rtol] = get_atol_rtol(input, atol_opt, rtol_opt, "torch.linalg.matrix_rank"); + + checkSameDevice("torch.linalg.matrix_rank", result, input); + checkSameDevice("torch.linalg.matrix_rank", atol, input, "atol"); + checkSameDevice("torch.linalg.matrix_rank", rtol, input, "rtol"); + ScalarType output_type = ScalarType::Long; + checkLinalgCompatibleDtype("torch.linalg.matrix_rank", result.scalar_type(), output_type); + + checkNotComplexTolerance(atol, "torch.linalg.matrix_rank", "atol"); + checkNotComplexTolerance(rtol, "torch.linalg.matrix_rank", "rtol"); + + // NumPy doesn't take into account possible input with no elements and it errors on max not defined for this case + // Let's output 0 for this case, since that kind of matrices have zero number of non-zero rows, hence rank is 0. + if (input.sym_numel() == 0) { + result.fill_(0); + return result; + } + + // We compute matrix rank as the number of singular or absolute eigen values + // that are above max(atol, rtol * max(S)) threshold + Tensor S, max_S; + if (!hermitian) { + S = at::linalg_svdvals(input); + // singular values are sorted in descending order + max_S = at::narrow(S, /*dim=*/-1, /*start=*/0, /*length=*/1); + } else { + S = at::linalg_eigvalsh(input); + S = S.abs(); + // eigenvalues are sorted in ascending order starting with negative values, we need a maximum value of abs(eigenvalues) + max_S = S.amax(/*dim=*/-1, /*keepdim=*/true); + } + + Tensor tol = at::max(atol.unsqueeze(-1), rtol.unsqueeze(-1) * max_S); + + if (isTensorSubclassLike(input)) { + result = at::sum(S > tol, /*dim=*/-1); + return result; + } + + result = at::sum_out(result, S > tol, /*dim=*/-1); + return result; +} + +Tensor get_matrix_rank_result_tensor(const Tensor& input) { + // Matrices or batch of matrices are allowed + checkIsMatrix(input, "torch.linalg.matrix_rank", "input"); + // For Composite Compliance, allocate `result` of correct shape to + // avoid resizing in `out` variant. + // See also `NOTE [matrix rank output shape]` + auto result_shape = + SymIntArrayRef(input.sym_sizes().cbegin(), input.sym_sizes().cend() - 2); + Tensor result = + at::empty_symint(result_shape, input.options().dtype(ScalarType::Long)); + + return result; +} + +} // anonymous namespace + +Tensor& linalg_matrix_rank_out( + const Tensor& input, + const std::optional& atol_opt, + const std::optional& rtol_opt, + bool hermitian, + Tensor& result) { + // Matrices or batch of matrices are allowed + checkIsMatrix(input, "torch.linalg.matrix_rank", "input"); + auto result_shape = + IntArrayRef(input.sizes().cbegin(), input.sizes().cend() - 2); + at::native::resize_output(result, result_shape); + return matrix_rank_impl(input, atol_opt, rtol_opt, hermitian, result); +} + +Tensor& linalg_matrix_rank_out(const Tensor& input, std::optional atol, std::optional rtol, bool hermitian, Tensor& result) { + auto [atol_tensor, rtol_tensor] = get_atol_rtol(input, atol, rtol); + result = linalg_matrix_rank_out(input, atol_tensor, rtol_tensor, hermitian, result); + return result; +} + +Tensor linalg_matrix_rank(const Tensor& input, const std::optional& atol, const std::optional& rtol, bool hermitian) { + auto result = get_matrix_rank_result_tensor(input); + return matrix_rank_impl(input, atol, rtol, hermitian, result); +} + +Tensor linalg_matrix_rank(const Tensor& input, std::optional atol, std::optional rtol, bool hermitian) { + auto result = get_matrix_rank_result_tensor(input); + + auto [atol_tensor, rtol_tensor] = get_atol_rtol(input, atol, rtol); + + return matrix_rank_impl(input, atol_tensor, rtol_tensor, hermitian, result); +} + +Tensor& linalg_matrix_rank_out(const Tensor& input, const Tensor& tol, bool hermitian, Tensor& result) { + // For NumPy compatibility tol is not scaled with max(singular_value) if the value for tol is provided + // It is assumed that the provided value is the absolute tolerance + Tensor rtol = at::zeros({}, tol.options()); + result = at::linalg_matrix_rank_outf(input, tol, rtol, hermitian, result); + return result; +} + +Tensor& linalg_matrix_rank_out(const Tensor& input, double tol, bool hermitian, Tensor& result) { + // For NumPy compatibility tol is not scaled with max(singular_value) if the value for tol is provided + // It is assumed that the provided value is the absolute tolerance + result = at::linalg_matrix_rank_outf(input, tol, 0.0, hermitian, result); + return result; +} + +Tensor linalg_matrix_rank(const Tensor& input, const Tensor& tol, bool hermitian) { + auto result = get_matrix_rank_result_tensor(input); + return matrix_rank_impl(input, tol, at::zeros({}, tol.options()), hermitian, result); +} + +Tensor linalg_matrix_rank(const Tensor& input, double tol, bool hermitian) { + auto result = get_matrix_rank_result_tensor(input); + + auto [atol_tensor, rtol_tensor] = get_atol_rtol(input, tol, 0.0); + + return matrix_rank_impl(input, atol_tensor, rtol_tensor, hermitian, result); +} + +// multi_dot helper functions +namespace { + +/** + * @brief Computes the optimal matrix chain multiplication order + * + * Follows the dynamic programming algorithm from Cormen et al., + * "Introduction to Algorithms, Third Edition", Chapter 15.2, + * p. 370-378. Note that the book uses 1-based indexing. + * + * The cost of multiplying two matrices with sizes p x q and q x r + * is defined here as p * q * r. The optimal multiplication order + * is the one that minimizes the total cost. + * + * @param tensors list of 2D tensors + * @return a 2D vector s used by #matrix_chain_multiplication to construct + * the optimal matrix multiplication order. The optimal multiplication + * order for multiplying tensors i...j is to multiply tensors i...s[i, j] + * and tensors (s[i, j] + 1)...j first and then the result of that. + */ +std::vector> matrix_chain_order(TensorList tensors) { + const size_t n = tensors.size(); + + // Tensor i has dimensions p[i] x p[i + 1] + std::vector p(n + 1); + for (const auto i : c10::irange(n)) { + p[i] = tensors[i].size(0); + } + p[n] = tensors[n - 1].size(1); + + // m[i, j] = k where k is the minimum cost for multiplying tensors i...j + std::vector> m(n, std::vector(n, 0)); + + // s[i, j] = k where k is the index at which to split the list such that + // optimally multiplying matrices i...k and k...j first and then the resulting + // matrices is the optimal order for multiplying matrices i...j. + std::vector> s(n, std::vector(n)); + + // Compute the optimal multiplication order + for (const auto l : c10::irange(1, n)) { + for (const auto i : c10::irange(n - l)) { + const auto j = i + l; + m[i][j] = std::numeric_limits::max(); + for (const auto k : c10::irange(i, j)) { + const auto q = m[i][k] + m[k + 1][j] + p[i] * p[k + 1] * p[j + 1]; + if (q < m[i][j]) { + m[i][j] = q; + s[i][j] = k; + } + } + } + } + + return s; +} + +/** + * @brief Recursively multiplies the tensors i...j using the given order + * + * @param tensors matrices to multiply together + * @param order optimal chain multiplication order from #matrix_chain_order + * @param i index of first tensor to be multiplied + * @param j index of last tensor to be multiplied + * @return Tensor result of multiplying tensors[i...j] together. + */ +Tensor matrix_chain_multiplication( + TensorList tensors, + const std::vector>& order, + int64_t i, + int64_t j) { + if (i == j) { + return tensors[i]; + } + return at::mm( + matrix_chain_multiplication(tensors, order, i, order[i][j]), + matrix_chain_multiplication(tensors, order, order[i][j] + 1, j)); +} + +// Implements torch.linalg.multi_dot +Tensor multi_dot_impl(TensorList _tensors, std::optional _out) { + const size_t n = _tensors.size(); + TORCH_CHECK(n >= 2, "multi_dot(): expected at least 2 tensors but got ", n); + + std::vector out_shape; + std::vector tensors(n); + + // If the first tensor is 1D of size n view it as a row vector (1, n) + if (_tensors[0].dim() == 1) { + tensors[0] = _tensors[0].unsqueeze(0); + } else if (_tensors[0].dim() == 2) { + tensors[0] = _tensors[0]; + out_shape.emplace_back(tensors[0].size(0)); + } else { + TORCH_CHECK( + false, + "multi_dot(): the first tensor must be 1D or 2D but got ", + _tensors[0].dim(), + "D"); + } + + // If the last tensor is 1D of size n view it as a column vector (n, 1) + if (_tensors[n - 1].dim() == 1) { + tensors[n - 1] = _tensors[n - 1].unsqueeze(-1); + } else if (_tensors[n - 1].dim() == 2) { + tensors[n - 1] = _tensors[n - 1]; + out_shape.emplace_back(tensors[n - 1].size(1)); + } else { + TORCH_CHECK( + false, + "multi_dot(): the last tensor must be 1D or 2D but got ", + _tensors[n - 1].dim(), + "D"); + } + + // Ensure middle tensors are 2D + for (const auto i : c10::irange(1, n - 1)) { + TORCH_CHECK( + _tensors[i].dim() == 2, + "multi_dot(): tensor ", + i, + " must be 2D but got ", + _tensors[i].dim(), + "D"); + tensors[i] = _tensors[i]; + } + + // Ensure all tensors have the same device and dtype and check + // that the shapes can be multiplied + const auto dtype = tensors[0].dtype(); + const auto device = tensors[0].device(); + for (const auto i : c10::irange(1, n)) { + TORCH_CHECK( + tensors[i].dtype() == dtype, + "multi_dot(): all tensors must have be the same dtype but tensor 0 is ", + dtype, + " and tensor ", + i, + " ", + tensors[i].dtype()); + TORCH_CHECK( + tensors[i].device() == device, + "multi_dot(): all tensors must be on the same device but tensor 0 is on ", + device, + " and tensor ", + i, + " on ", + tensors[i].device()); + TORCH_CHECK( + tensors[i - 1].size(-1) == tensors[i].size(0), + "multi_dot(): tensors ", + i - 1, + " and ", + i, + " with shapes ", + _tensors[i - 1].sizes(), + " and ", + _tensors[i].sizes(), + " cannot be multiplied") + } + + Tensor result; + + if (_out.has_value()) { + auto out = *_out; + TORCH_CHECK( + dtype == out.dtype(), + "multi_dot(): expected out tensor to have dtype ", + dtype, + " but got ", + out.dtype()); + TORCH_CHECK( + device == out.device(), + "multi_dot(): expected out tensor to be on device ", + device, + " but got ", + out.device()); + + // If the last and last tensors have shapes (a, b) and (b, c) the + // output has shape (a, c). If either the first or last tensor is 1D + // a and/or c dimensions will be implicitly size 1 and will be omitted + // from the output. e.g. for inputs (a, b) x (b) the output has shape (a,). + at::native::resize_output(out, out_shape); + + // View output as 2D for simplicity of computation. + result = out.view({tensors[0].size(0), tensors.back().size(-1)}); + } + + // The resize_ and view calls below are to ensure the + // output shape respects the original dimensionality of + // the first and last tensors which we are now viewed as 2D + + if (tensors.size() == 2) { + return _out.has_value() ? at::mm_out(result, tensors[0], tensors[1]) + : at::mm(tensors[0], tensors[1]).view(out_shape); + } + + // Why the separate implementation for 3 matrices? + // The logic for three matrices is much faster when done directly + // Requires 1 comparison to 4 comparisons and fewer arithmetic operations + if (tensors.size() == 3) { + const auto a = tensors[0].size(0); + const auto b = tensors[1].size(0); + const auto c = tensors[2].size(0); + const auto d = tensors[2].size(1); + + // The matrices are of size (a x b), (b x c), (c x d) + // cost_1 is the cost of parenthesizing (a x b) and (b x c) and then + // combining (c x d) cost_2 is the cost of parenthesizing (b x c) and (c x + // d) and then combining (a x b) + const auto cost_1 = (a * c) * (b + d); + const auto cost_2 = (b * d) * (a + c); + + if (cost_1 > cost_2) { + return _out.has_value() + ? at::mm_out(result, tensors[0], at::mm(tensors[1], tensors[2])) + : at::mm(tensors[0], at::mm(tensors[1], tensors[2])).view(out_shape); + } else { + return _out.has_value() + ? at::mm_out(result, at::mm(tensors[0], tensors[1]), tensors[2]) + : at::mm(at::mm(tensors[0], tensors[1]), tensors[2]).view(out_shape); + } + } + + // Algorithm for multiplying 4 or more matrices + const auto order = matrix_chain_order(tensors); + const int64_t i = 0; + const int64_t j = n - 1; + + if (_out.has_value()) { + // We manually implement the first recursive layer here so we can use mm_out + // for the final multiplication + return at::mm_out( + result, + matrix_chain_multiplication(tensors, order, i, order[i][j]), + matrix_chain_multiplication(tensors, order, order[i][j] + 1, j)); + } + return matrix_chain_multiplication(tensors, order, i, j).view(out_shape); +} + +} // namespace + +Tensor linalg_multi_dot(TensorList tensors) { + return multi_dot_impl(tensors, std::nullopt); +} + +Tensor& linalg_multi_dot_out(TensorList tensors, Tensor& result) { + multi_dot_impl(tensors, result); + return result; +} + +Tensor chain_matmul(TensorList matrices) { + TORCH_WARN_ONCE( + "torch.chain_matmul is deprecated and will be removed in a future PyTorch release. ", + "Use torch.linalg.multi_dot instead, which accepts a list of two or more tensors rather than ", + "multiple parameters." + ); + checkAllSameDim(matrices, 2); + + TORCH_CHECK( + !matrices.empty(), "chain_matmul(): Expected one or more matrices"); + + if (matrices.size() == 1) { + return matrices[0].clone(); + } + + return at::native::linalg_multi_dot(matrices); +} + +Tensor& chain_matmul_out(TensorList matrices, Tensor& result) { + TORCH_WARN_ONCE( + "torch.chain_matmul is deprecated and will be removed in a future PyTorch release. ", + "Use torch.linalg.multi_dot instead, which accepts a list of two or more tensors rather than ", + "multiple parameters." + ); + checkAllSameDim(matrices, 2); + + TORCH_CHECK( + !matrices.empty(), "chain_matmul(): Expected one or more matrices"); + + if (matrices.size() == 1) { + at::native::resize_output(result, matrices[0].sizes()); + return result.copy_(matrices[0]); + } + + return at::native::linalg_multi_dot_out(matrices, result); +} + +static void check_1d(const Tensor& t, const char* arg, const char* fn) { + TORCH_CHECK(t.dim() == 1, fn, ": Expected 1-D argument ", arg, ", but got ", t.dim(), "-D"); +} + +static void check_addr_scalar(const ScalarType dtype, + const Scalar& scalar, + const std::string& scalar_name) { + TORCH_CHECK( + !scalar.isBoolean() || dtype == ScalarType::Bool, + "Boolean ", scalar_name, " only supported for Boolean results."); + TORCH_CHECK( + isFloatingType(dtype) || isComplexType(dtype) || scalar.isIntegral(true), + "For integral input tensors, " + "argument ", scalar_name ," must not be a floating point number."); +} + +static TensorIterator build_addr_iter(Tensor& result, + const Tensor& self, + const Tensor& vec1, + const Tensor& vec2) { + check_1d(vec1, "vec1", "addr"); + check_1d(vec2, "vec2", "addr"); + + const auto vec1_size0 = vec1.sizes()[0]; + const auto vec2_size0 = vec2.sizes()[0]; + auto self_ = &result == &self + ? c10::MaybeOwned::borrowed(self) + : expand_size(self, {vec1_size0, vec2_size0}, "addr"); + TORCH_CHECK( + self_->dim() == 2, + "2D tensor expected, got ", self_->dim(), "D tensor for input" + ); + TORCH_CHECK( + self_->sizes()[0] == vec1_size0 && self_->sizes()[1] == vec2_size0, + "size mismatch, input: ", self_->sizes(), + ", v1: ", vec1.sizes(), + ", v2: ", vec2.sizes() + ); + + auto iter = TensorIteratorConfig() + .set_check_mem_overlap(true) + .add_output(result) + .add_owned_const_input(*self_) + .add_owned_const_input(vec1.reshape({vec1_size0, 1})) + .add_const_input(vec2) + .allow_cpu_scalars(true) + .promote_inputs_to_common_dtype(true) + .cast_common_dtype_to_outputs(true) + .enforce_safe_casting_to_output(true) + .build(); + return iter; +} + +Tensor addr(const Tensor& self, + const Tensor& vec1, const Tensor& vec2, + const Scalar& beta, const Scalar& alpha) { + Tensor result; + auto iter = build_addr_iter(result, self, vec1, vec2); + + check_addr_scalar(iter.dtype(), beta, "beta"); + check_addr_scalar(iter.dtype(), alpha, "alpha"); + + addr_stub(iter.device_type(), iter, beta, alpha); + return iter.output(); +} + +Tensor& addr_(Tensor& self, + const Tensor& vec1, const Tensor& vec2, + const Scalar& beta, const Scalar& alpha) { + return at::addr_out(self, self, vec1, vec2, beta, alpha); +} + +Tensor& addr_out(const Tensor& self, + const Tensor& vec1, const Tensor& vec2, + const Scalar& beta, const Scalar& alpha, Tensor &result) { + auto iter = build_addr_iter(result, self, vec1, vec2); + + check_addr_scalar(iter.dtype(), beta, "beta"); + check_addr_scalar(iter.dtype(), alpha, "alpha"); + + addr_stub(iter.device_type(), iter, beta, alpha); + return result; +} + +// The math_addr and math_addr_out functions support backends +// other than CPU and CUDA, such as XLA. +// They are implemented using the composition of existing ops +Tensor math_addr(const Tensor& self, + const Tensor& vec1, const Tensor& vec2, + const Scalar& beta, const Scalar& alpha) { + // when beta==0, values in self should be ignored, + // nans and infs in self should not propagate. + Tensor out; + if (beta.toComplexDouble() == 0.0) { + if (alpha.toComplexDouble() == 1.0) { + out = at::outer(vec1, vec2); + } else { + out = alpha * at::outer(vec1, vec2); + } + } else if (beta.toComplexDouble() == 1.0) { + if (alpha.toComplexDouble() == 1.0) { + out = self + at::outer(vec1, vec2); + } else { + out = self + alpha * at::outer(vec1, vec2); + } + } else if (alpha.toComplexDouble() == 1.0) { + out = beta * self + at::outer(vec1, vec2); + } else { + out = beta * self + alpha * at::outer(vec1, vec2); + } + auto result_type = c10::promoteTypes(c10::promoteTypes(self.scalar_type(), vec1.scalar_type()), vec2.scalar_type()); + return out.to(c10::TensorOptions().dtype(result_type)); +} + +Tensor& math_addr_out(const Tensor& self, + const Tensor& vec1, const Tensor& vec2, + const Scalar& beta, const Scalar& alpha, Tensor &result) { + auto addr_result = at::addr(self, vec1, vec2, beta, alpha); + + // Validates safe casting + const auto result_dtype = addr_result.scalar_type(); + TORCH_CHECK(canCast(result_dtype, result.scalar_type()), + "result type ", result_dtype, + " can't be cast to the desired output type ", result.scalar_type()); + + at::native::resize_output(result, addr_result.sizes().vec()); + result.copy_(addr_result); + return result; +} + +// torch.ger, alias for torch.outer +Tensor& ger_out(const Tensor& self, const Tensor& vec2, Tensor &result) { + TORCH_WARN("torch.ger is deprecated and will be removed in a future PyTorch release. " + "Use torch.outer instead."); + return at::outer_out(result, self, vec2); +} + +Tensor ger(const Tensor& self, const Tensor& vec2) { + return self.outer(vec2); +} + +Tensor& inner_out(const Tensor& self, const Tensor& other, Tensor& out) { + checkDeviceType("inner()", {out, self, other}, self.device().type()); + + // If either self or other is a scalar just multiply them + if (self.dim() == 0 || other.dim() == 0) { + at::mul_out(out, self, other); + return out; + } + + // Last dimension should match (tensordot does not enforce this) + TORCH_CHECK( + self.size(-1) == other.size(-1), + "inner() the last dimension must match on both input tensors but got shapes ", + self.sizes(), + " and ", + other.sizes()); + + at::tensordot_out(out, self, other, -1, -1); + return out; +} + +Tensor inner(const Tensor& self, const Tensor& other) { + checkDeviceType("inner()", {self, other}, self.device().type()); + + // If either self or other is a scalar just multiply them + if (self.dim() == 0 || other.dim() == 0) { + return self * other; + } + + // Last dimension should match (tensordot does not enforce this) + TORCH_CHECK( + self.sym_size(-1) == other.sym_size(-1), + "inner() the last dimension must match on both input tensors but got shapes ", + self.sym_sizes(), + " and ", + other.sym_sizes()); + + return at::tensordot(self, other, -1, -1); +} + +Tensor& outer_out(const Tensor& self, const Tensor& vec2, Tensor &result) { + check_1d(self, "self", "outer"); + check_1d(vec2, "vec2", "outer"); + + // torch.outer is implemented as a composite op using reshape and mul + at::mul_out(result, self.reshape({self.size(0), 1}), vec2); + return result; +} + +Tensor outer(const Tensor& self, const Tensor& vec2) { + check_1d(self, "self", "outer"); + check_1d(vec2, "vec2", "outer"); + + return self.reshape_symint({self.sym_size(0), 1}) * vec2; +} + + +#if !defined(C10_MOBILE) +#define _AT_DISPATCH_ADDMM_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND6( \ + kBFloat16, kHalf, kFloat8_e5m2, kFloat8_e4m3fn, kFloat8_e5m2fnuz, kFloat8_e4m3fnuz, \ + TYPE, NAME, __VA_ARGS__) +#else +// Include half dtype in ADDMM. Used to build ExecuTorch in xplat. +#if defined(C10_MOBILE_HALF) +#define _AT_DISPATCH_ADDMM_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, \ + TYPE, NAME, __VA_ARGS__) +#else +#define _AT_DISPATCH_ADDMM_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND(kBFloat16, \ + TYPE, NAME, __VA_ARGS__) +#endif +#endif + + +#if !defined(__aarch64__) || AT_MKLDNN_ACL_ENABLED() +// Used by default on x86 platforms and on AArch64+ACL +static inline int64_t get_mkldnn_matmul_min_dim() { + static auto value = [&] { + const int64_t default_min_dim = [&] { + // Minimum dimension requirement for MKLDNN; derived based on experiments. + //it's enabled on all Neoverse cpus. + return is_arm_neoverse() ? 8 : 0; + }(); + const auto value = c10::utils::get_env("TORCH_MKLDNN_MATMUL_MIN_DIM"); + return value.has_value() ? std::stoi(value.value()) : default_min_dim; + }(); + return value; +} + + +static inline int64_t get_mkldnn_matmul_min_size() { + static auto value = [&] { + const int64_t default_min_size = [&] { + // Minimum size requirement for MKLDNN; derived based on experiments. + // it's enabled on all Neoverse cpus. + return is_arm_neoverse() ? 8 * 1024 : 0; + }(); + const auto value = c10::utils::get_env("TORCH_MKLDNN_MATMUL_MIN_SIZE"); + return value.has_value() ? std::stoi(value.value()) : default_min_size; + }(); + return value; +} + + +static inline bool apply_mkldnn_matmul_heur(int64_t m, int64_t k, int64_t n) { + const int64_t min_dim = get_mkldnn_matmul_min_dim(); + const int64_t min_size = get_mkldnn_matmul_min_size(); + return at::globalContext().userEnabledMkldnn() && m > min_dim && k > min_dim && n > min_dim && m * k * n > min_size; +} +#endif +static void addmm_impl_cpu_( + Tensor &result, const Tensor &self, Tensor m1, Tensor m2, const Scalar& beta, const Scalar& alpha) { + TORCH_INTERNAL_ASSERT(self.dim() == 2 && m1.dim() == 2 && m2.dim() == 2); + + TORCH_CHECK( + m1.dtype() == m2.dtype(), + "expected m1 and m2 to have the same dtype, but got: ", m1.dtype(), " != ", m2.dtype() + ) + // Array access is faster than .size(n) and .stride(n) + const auto self_sizes = self.sizes(); + auto m1_strides = m1.strides(); + auto m1_sizes = m1.sizes(); + auto m2_strides = m2.strides(); + auto m2_sizes = m2.sizes(); + + TORCH_CHECK( + self_sizes[0] == m1_sizes[0] && self_sizes[1] == m2_sizes[1], + "input shape is incompatible with matrix multiplication (", + m1_sizes[0], "x", m1_sizes[1], " @ ", m2_sizes[0], "x", m2_sizes[1], " != ", + self_sizes[0], "x", self_sizes[1], ")"); + + at::native::resize_output(result, self_sizes); + const auto result_strides = result.strides(); + const auto result_sizes = result.sizes(); + + if (result.numel() == 0) { + return; + } + + // Some paths in the code below do not handle multiplications of the form [a, 0] x [0, b] + if (m1_sizes[1] == 0) { + if (beta.toComplexDouble() == 0.0) { + result.zero_(); + } else { + if (!self.is_same(result)) { + result.copy_(self); + } + result.mul_(beta); + } + return; + } + + if (beta.toComplexDouble() != 0.0 && !self.is_same(result)) { + result.copy_(self); + } + + bool transpose_c = false; + Tensor c; + + // Cast result as matrix a + if (result_strides[0] == 1 && + (result_sizes[1] == 1 || result_strides[1] >= std::max(int64_t{1}, result_sizes[0]))) { + transpose_c = false; + c = result.resolve_conj(); + } else if (result_strides[1] == 1 && + (result_sizes[0] == 1 || result_strides[0] >= std::max(int64_t{1}, result_sizes[1]))) { + std::swap(m1, m2); + std::swap(m1_sizes, m2_sizes); + std::swap(m1_strides, m2_strides); + transpose_c = true; + c = result.resolve_conj(); + } else { + transpose_c = false; + // make c FORTRAN contiguous + c = result.resolve_conj().transpose(0, 1).contiguous().transpose_(0, 1); + } + + const int64_t m = result_sizes[transpose_c ? 1 : 0]; + const int64_t n = result_sizes[transpose_c ? 0 : 1]; + const int64_t k = m1_sizes[transpose_c ? 0 : 1]; + + // Cast m1 as matrix a + bool transpose_a = false; + Tensor a; + /* Need lda >= max(1, (transpose_a ? k : m)) */ + if (m1_strides[transpose_c ? 1 : 0] == 1 && + m1_strides[transpose_c ? 0 : 1] >= std::max(int64_t{1}, m)) { + transpose_a = false; + a = m1.resolve_conj(); + } else if (m1_strides[transpose_c ? 0 : 1] == 1 && + m1_strides[transpose_c ? 1 : 0] >= std::max(int64_t{1}, k)) { + transpose_a = true; + a = m1; + } else { + transpose_a = !transpose_c; + a = m1.clone(at::MemoryFormat::Contiguous); + } + + // Cast m2 as matrix b + bool transpose_b = false; + Tensor b; + /* Need ldm2_ >= max(1, (transpose_m2 == 'n' ? k : n)) */ + if (m2_strides[transpose_c ? 1 : 0] == 1 && + m2_strides[transpose_c ? 0 : 1] >= std::max(int64_t{1}, k)) { + transpose_b = false; + b = m2.resolve_conj(); + } else if (m2_strides[transpose_c ? 0 : 1] == 1 && + m2_strides[transpose_c ? 1 : 0] >= std::max(int64_t{1}, n)) { + transpose_b = true; + b = m2; + } else { + transpose_b = !transpose_c; + b = m2.clone(at::MemoryFormat::Contiguous); + } + + const int64_t lda = a.strides()[(transpose_a == transpose_c) ? 1 : 0]; + const int64_t ldb = b.strides()[(transpose_b == transpose_c) ? 1 : 0]; + const int64_t ldc = c.strides()[transpose_c ? 0 : 1]; + + // Always ensure the conjugation for c is resolved since there's no way to specify c's conjugation in the gemm call + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!c.is_conj()); + + bool dispatched = false; +#if defined(__aarch64__) && AT_MKLDNN_ACL_ENABLED() + // On AArch64 if LHS matrix in BLAS routine is transposed but RHS is not then + // it is faster to call oneDNN matrix multiplication primitive with RHS*LHS + // that will call then into Arm® Compute Library (ACL) GEMM kernel and also + // additionally have support for running kernel with BF16 instructions + if (transpose_c) { + bool apply_heur = + apply_mkldnn_matmul_heur(b.sizes()[0], b.sizes()[1], a.sizes()[1]); + if (apply_heur && transpose_a && !transpose_b && + (result.scalar_type() == at::ScalarType::Float || + result.scalar_type() == at::ScalarType::BFloat16 || + result.scalar_type() == at::ScalarType::Half)) { + try { + mkldnn_matmul(b, a, c, beta.to(), alpha.to()); + // We have dispatched to ACL GEMM for single precision float + // so do not need to dispatch to BLAS GEMM below + dispatched = true; + } catch (const std::exception& e) { + TORCH_WARN("mkldnn_matmul failed, switching to BLAS gemm:", e.what()); + at::globalContext().setUserEnabledMkldnn(false); + } + } + } +#endif + + if(!dispatched) { + // Apply BLAS routine + _AT_DISPATCH_ADDMM_TYPES(result.scalar_type(), "addmm_impl_cpu_", [&]{ + using opmath_t = at::opmath_type; + at::native::cpublas::gemm( + transpose_a ? a.is_conj() ? TransposeType::ConjTranspose : TransposeType::Transpose : TransposeType::NoTranspose, + transpose_b ? b.is_conj() ? TransposeType::ConjTranspose : TransposeType::Transpose : TransposeType::NoTranspose, + m, n, k, + alpha.to(), + a.const_data_ptr(), lda, + b.const_data_ptr(), ldb, + beta.to(), + c.mutable_data_ptr(), ldc); + }); + } + + if (!c.is_same(result)) { + result.copy_(c); + } +} + +static void addbmm_impl_( + Tensor &result, const Tensor &self, const Tensor &batch1, const Tensor &batch2, const Scalar& beta, const Scalar& alpha) { + TORCH_CHECK(batch1.dim() == 3, "batch1 must be a 3D tensor"); + TORCH_CHECK(batch2.dim() == 3, "batch2 must be a 3D tensor"); + TORCH_CHECK(batch1.size(0) == batch2.size(0), + "batch1 and batch2 must have same number of batches, got ", + batch1.size(0), " and ", batch2.size(0)); + TORCH_CHECK(batch1.size(2) == batch2.size(1), + "Incompatible matrix sizes for bmm (", + batch1.size(1), "x", batch1.size(2), " and ", + batch2.size(1), "x", batch2.size(2), ")"); + + const int64_t dim1 = batch1.size(1); + const int64_t dim2 = batch2.size(2); + TORCH_CHECK(self.size(0) == dim1 && self.size(1) == dim2, + "self tensor does not match matmul output shape"); + + result.resize_as_(self); + + if (beta.to>() != 0.0 && !self.is_same(result)) { + result.copy_(self); + } + + const int64_t num_batches = batch1.size(0); + + if (num_batches == 0) { + if (beta.to>() != 0.0) { + result.mul_(beta); + } else { + result.zero_(); + } + return; + } + + auto adjusted_beta(beta); + for (const auto batch : c10::irange(num_batches)) { + result.addmm_(batch1[batch], batch2[batch], adjusted_beta, alpha); + adjusted_beta = 1; // accumulate output once + } +} + +Tensor& addbmm_out(const Tensor& self, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha, Tensor& result) { + auto b_self = expand_size(self, {batch1.size(1), batch2.size(2)}, "addbmm_out"); + { + addbmm_impl_(result, *b_self, batch1, batch2, beta, alpha); + } + return result; +} + +Tensor &addbmm_(Tensor& self, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha) { + return native::addbmm_out(self, batch1, batch2, beta, alpha, self); +} + +Tensor addbmm(const Tensor& self, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha) { + Tensor result = at::empty({0}, self.options()); + return native::addbmm_out(self, batch1, batch2, beta, alpha, result); +} + +TORCH_IMPL_FUNC(addmm_out_cpu)(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha, const Tensor &result) { + auto b_self = expand_size(self, {mat1.sizes()[0], mat2.sizes()[1]}, "addmm_out"); + { + addmm_impl_cpu_(const_cast(result), *b_self, mat1, mat2, beta, alpha); + } +} + +TORCH_IMPL_FUNC(addmm_activation_out_cpu)(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha, bool use_gelu, const Tensor &result) { + auto b_self = expand_size(self, {mat1.sizes()[0], mat2.sizes()[1]}, "addmm_out"); + { + addmm_impl_cpu_(const_cast(result), *b_self, mat1, mat2, beta, alpha); + if (use_gelu) { + at::gelu_(const_cast(result)); + } else { + at::relu_(const_cast(result)); + } + } +} + +TORCH_IMPL_FUNC(mm_out_cpu)(const Tensor & self, const Tensor & mat2, const Tensor & result) { + { + addmm_impl_cpu_(const_cast(result), result, self, mat2, 0, 1); + } +} + +template +static inline void baddbmm_cpu_kernel(const Tensor& result, const Tensor& self, const Tensor& mat2, const Scalar& beta_, const Scalar& alpha_) { + int64_t bs = result.size(0); + int64_t is = result.size(1); + int64_t js = result.size(2); + int64_t ks = self.size(2); + + using opmath_t = at::opmath_type; + opmath_t alpha = alpha_.to(); + opmath_t beta = beta_.to(); + + auto r0 = result.accessor(); + auto s0 = self.accessor(); + auto m0 = mat2.accessor(); + + int64_t grain_size = std::max(internal::GRAIN_SIZE / (is * js * ks), static_cast(1)); + using opmath_t = at::opmath_type; + parallel_for(0, bs, grain_size, [&](int64_t b_begin, int64_t b_end) { + for (const auto b : c10::irange(b_begin, b_end)) { + auto r1 = r0[b]; + auto s1 = s0[b]; + auto m1 = m0[b]; + for (const auto i : c10::irange(is)) { + auto r2 = r1[i]; + auto s2 = s1[i]; + for (const auto j : c10::irange(js)) { + opmath_t acc_value = 0;//is_bmm ? opmath_t(0) : opmath_t(r2[j]); + for (const auto k : c10::irange(ks)) { + acc_value += static_cast(s2[k]) * + static_cast(m1[k][j]); + } + if (is_bmm) { + r2[j] = acc_value; + } else { + // For beta == 0, the r's value will be ignored, especially for nan value. + if (beta == opmath_t{0}) { + r2[j] = alpha * acc_value; + } else { + r2[j] = static_cast(r2[j]) * beta + alpha * acc_value; + } + } + } + } + } + }); +} + +static void baddbmm_with_gemm_(const Tensor &result, const Tensor &mat1, const Tensor &mat2, const Scalar &beta_, const Scalar &alpha_) { + TORCH_INTERNAL_ASSERT(result.is_contiguous()); + + const auto result_sizes = result.sizes(); + const auto result_strides = result.strides(); + const auto mat1_strides = mat1.strides(); + const auto mat2_strides = mat2.strides(); + const auto mat1_sizes = mat1.sizes(); + const auto mat2_sizes = mat2.sizes(); + + auto is_transposed = [](const c10::IntArrayRef& strides, const c10::IntArrayRef& sizes) { + return strides[1] == 1 && strides[2] >= sizes[1]; + }; + + // gemm expects fortran order matrices, so we swap argument order to transpose everything + const auto transpose_a = is_transposed(mat2_strides, mat2_sizes); + const auto transpose_b = is_transposed(mat1_strides, mat1_sizes); + + const int64_t batch_size = mat1_sizes[0]; + const int64_t m = result_sizes[2]; + const int64_t n = result_sizes[1]; + const int64_t k = mat2_sizes[1]; + + const int64_t lda = mat2_strides[transpose_a ? 2 : 1]; + const int64_t ldb = mat1_strides[transpose_b ? 2 : 1]; + const int64_t ldc = result_strides[1]; + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(result.scalar_type(), "baddbmm_with_gemm", [&] { + using opmath_t = at::opmath_type; + const auto alpha = alpha_.to(); + const auto beta = beta_.to(); + at::native::cpublas::gemm_batched_with_stride( + transpose_a ? TransposeType::Transpose : TransposeType::NoTranspose, + transpose_b ? TransposeType::Transpose : TransposeType::NoTranspose, + batch_size, m, n, k, alpha, + mat2.const_data_ptr(), lda, mat2_strides[0], + mat1.const_data_ptr(), ldb, mat1_strides[0], + beta, + result.data_ptr(), ldc, result_strides[0]); + }); +} + +// This tries to apply some optimizations to bmm/baddbmm: +// - When the operand size is small, computation are parallelized over the batch +// dimension using OMP and naive matrix multiplication is applied. +// - When the operand size is larger than the threshold, if compiled with MKL, MKL's batch gemm is used. +// - Otherwise, we use a series of matrix multiplications. +// The threshold of 400 for the first has not been thoroughly benchmarked yet and may have room for further +// optimization, it likely depends on the characteristics of the CPU, MKL will be different from non-MKL etc., +// but this seems to be a first starting point. + +static inline void bmm_out_or_baddbmm_(const Tensor& self_or_result_, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha, bool is_bmm_out) { + // is_bmm_out: true for bmm_out, false for baddbmm_ + // self_or_result is "self" for baddbmm_ and "result" for bmm_out + Tensor& self_or_result = const_cast(self_or_result_); + + const auto batch1_sizes = batch1.sizes(); + const auto batch2_sizes = batch2.sizes(); + + int64_t bs = batch1_sizes[0]; + int64_t contraction_size = batch1_sizes[2]; + int64_t res_rows = batch1_sizes[1]; + int64_t res_cols = batch2_sizes[2]; + + // handle pathological cases that blas may not like + if (self_or_result.numel() == 0) { + return; + } else if (contraction_size == 0) { + if (is_bmm_out || (beta.to>() == 0.0)) { + self_or_result.zero_(); + return; + } else { + self_or_result.mul_(beta); + return; + } + } + + auto batch_items_contiguous_or_transposed = [&](const Tensor& t) { + const auto sizes = t.sizes(); + const auto strides = t.strides(); + // we do not care dimension's stride if its size equals to 1 + return (strides[2] == 1 && (sizes[1] == 1 || strides[1] >= sizes[2])) || + (strides[1] == 1 && (sizes[2] == 1 || strides[2] >= sizes[1])); + }; +#if !defined(__aarch64__) || AT_MKLDNN_ACL_ENABLED() + // Always apply mkldnn heuristic on x86 platform, but on ARM only if compiled with ACL + bool apply_heur = apply_mkldnn_matmul_heur(batch1.sizes()[1], batch1.sizes()[2], batch2.sizes()[2]); + if (apply_heur && use_mkldnn_matmul(batch1, batch2, self_or_result)) { + try { + mkldnn_matmul(batch1, batch2, self_or_result, beta.to(), alpha.to()); + return; + } catch ([[maybe_unused]]const std::exception& e) { + TORCH_WARN("mkldnn_matmul failed, switching to baddbmm:", e.what()); + at::globalContext().setUserEnabledMkldnn(false); + } + } +#endif + if (contraction_size * res_rows * res_cols < 400) { + if (is_bmm_out) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, batch1.scalar_type(), "bmm", [&] { + baddbmm_cpu_kernel(self_or_result, batch1, batch2, beta, alpha); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, batch1.scalar_type(), "baddbmm", [&] { + baddbmm_cpu_kernel(self_or_result, batch1, batch2, beta, alpha); + }); + } + } else if (at::hasMKL() && (( + self_or_result.scalar_type() != kBFloat16 && + self_or_result.scalar_type() != kHalf && + at::native::is_floating_point(self_or_result)) || + at::native::is_complex(self_or_result)) + && batch_items_contiguous_or_transposed(batch1) + && batch_items_contiguous_or_transposed(batch2) + && self_or_result.is_contiguous()) { + baddbmm_with_gemm_(self_or_result, batch1, batch2, beta, alpha); + } else { // split along batch dimension +#ifdef C10_MOBILE + /* + * We only do multithreading when Inference mode is enabled because various + * thread local state is not appropriately propagated through + * at::parallel_for. e.g. RecordFunction related state, dispatchKeySet Big + * concern with this is that if we use at::parallel_for where state is not + * propagated then dispatch machinery may work differently on main thread + * vs. other threads, leading to undefined behavior. + * Thus it is recommended to not use at::parallel_for where lambdas do + * ops that go through dispatcher. + * For now we circumvent this by InferenceMode guard in order to unlock + * performance. + * Longer term we probably want a separate API that explicitly calls out + * the TLS that it propagates. + * Also note that this is enabled for mobile only because blas + * implementation for non-mobile build is already multithreaded. + */ + // Benchmarking was done as follows: + // bmm_test: operator benchmark under + // benchmarks/operator_benchmarks/pt/bmm_test.py Ran this benchmark for + // various matrix sizes on Samsung S8U + const bool enable_multithreaded_bmm = c10::InferenceMode::is_enabled() && + bs >= 4 && res_rows >= 4 && res_cols >= 16 && contraction_size >= 16; +#else + const bool enable_multithreaded_bmm{false}; +#endif + if (is_bmm_out) { + if (enable_multithreaded_bmm) { + auto bmm_out_fn = [&](uint64_t start, uint64_t end) { + c10::InferenceMode guard; + for (const auto b : c10::irange(start, end)) { + auto r = self_or_result.select(0, b); + addmm_impl_cpu_( + r, r, batch1.select(0, b), batch2.select(0, b), 0, 1); + } + }; + // Materialize if COW, since we cannot do so during parallel_for + self_or_result.mutable_data_ptr(); + at::parallel_for(0, bs, 1, bmm_out_fn); + } else { + for (const auto b : c10::irange(bs)) { + auto r = self_or_result.select(0, b); + addmm_impl_cpu_(r, r, batch1.select(0, b), batch2.select(0, b), 0, 1); + } + } + } else { + if (enable_multithreaded_bmm) { + auto bmm_fn = [&](uint64_t start, uint64_t end) { + c10::InferenceMode guard; + for (const auto b : c10::irange(start, end)) { + self_or_result.select(0, b).addmm_( + batch1.select(0, b), batch2.select(0, b), beta, alpha); + } + }; + // Materialize if COW, since we cannot do so during parallel_for + self_or_result.mutable_data_ptr(); + at::parallel_for(0, bs, 1, bmm_fn); + } else { + for (const auto b : c10::irange(bs)) { + self_or_result.select(0, b).addmm_( + batch1.select(0, b), batch2.select(0, b), beta, alpha); + } + } + } + } + return; +} + +static void conjugate_mutable_input_if_needed(const Tensor& self, bool conjugate) { + if (conjugate) { + self.conj_physical_(); + } +} + +TORCH_IMPL_FUNC(baddbmm_out_cpu) +(const Tensor & self, const Tensor & batch1, const Tensor & batch2, const Scalar& beta, const Scalar& alpha, const Tensor& result) { + bool self_is_conj = result.is_conj(); + conjugate_mutable_input_if_needed(result, self_is_conj); + bmm_out_or_baddbmm_(result, batch1.resolve_conj(), batch2.resolve_conj(), beta, alpha, false); + conjugate_mutable_input_if_needed(result, self_is_conj); + } + +TORCH_IMPL_FUNC(bmm_out_cpu) +(const Tensor & batch1, const Tensor & batch2, const Tensor & result) { + { + bool result_is_conj = result.is_conj(); + conjugate_mutable_input_if_needed(result, result_is_conj); + bmm_out_or_baddbmm_(result, batch1.resolve_conj(), batch2.resolve_conj(), Scalar(0.0), Scalar(1.0), true); + conjugate_mutable_input_if_needed(result, result_is_conj); + } +} + +Tensor& dot_out(const Tensor& self, const Tensor& other, Tensor& result) { + auto output_device = result.device(); + auto input1_device = self.device(); + auto input2_device = other.device(); + // check if the input & output tensors are on the same device. + TORCH_CHECK( + (output_device == input1_device) && (input1_device == input2_device), + "dot: Expected the output and input tensors to be on the " + "same device, but got the output tensor on ", output_device, + ", the 'input' tensor on ", input1_device, ", and the 'other' tensor on ", input2_device); + at::native::resize_output(result, {}); + TORCH_CHECK(result.scalar_type() == self.scalar_type(), + "result dtype ", result.scalar_type(), " does not match input dtype ", self.scalar_type()); + return result.fill_(self.dot(other)); +} + +Tensor& vdot_out(const Tensor& self, const Tensor& other, Tensor& result) { + auto output_device = result.device(); + auto input1_device = self.device(); + auto input2_device = other.device(); + // check if the input & output tensors are on the same device. + TORCH_CHECK( + (output_device == input1_device) && (input1_device == input2_device), + "vdot: Expected the output and input tensors to be on the " + "same device, but got the output tensor on ", output_device, + ", the 'input' tensor on ", input1_device, ", and the 'other' tensor on ", input2_device); + at::native::resize_output(result, {}); + TORCH_CHECK(result.scalar_type() == self.scalar_type(), + "result dtype ", result.scalar_type(), " does not match input dtype ", self.scalar_type()); + return result.fill_(self.vdot(other)); +} + +static bool should_fold(const Tensor& tensor1, const Tensor& tensor2, bool has_out) { + // We check that we can fold the larger tensor into a matrix and dispatch to mm or mv rather than + // to bmm. We want to make sure we can do so without incurring in any extra copy + const auto tensor1_larger = tensor1.dim() >= tensor2.dim(); + + // We order the tensors. t1 will be the larger tensor + // We can always transpose tensor2 as the dimensions are always >= 1 (precondition from matmul) + // and tensor1_larger iff tensor2.dim() > tensor1.dim(9 + const auto t1 = tensor1_larger ? MaybeOwned::borrowed(tensor1) + : MaybeOwned::owned(tensor2.mT()); + const int64_t dim_t1 = t1->dim(); + const auto dim_t2 = tensor1_larger ? tensor2.dim() + : tensor1.dim(); + + // Just fold for dim_t1 >= 3 and (dim_t2 == 1 || dim_t2 == 2) + if (!(dim_t1 >= 3 && dim_t2 <= 2)) { + return false; + } + + // In this case we *do* incur in an extra copy to avoid creating an unnecessary large tensor in the backward + // Suppose we don't fold here. Let t1.shape = [b, m, n] t2.shape = [n, k] like in a transformer + // t2 will be expanded to a tensor of shape [b, n, k] and then we do t1.bmm(t2_expanded) + // The issue appears in the backward. + // The output gradient g of this operation would have shape [b, m, k] + // The backward wrt. t2 of bmm would be given by t1.mH @ g, which has shape [b, n, k] + // Then, the backward of expand is simply `sum(0)`. As such, we are instantiating a tensor + // of shape [b, n, k] unnecessarily, which may cause a large memory footprint, and in the + // worst case, an OOM + bool t2_requires_grad = tensor1_larger ? tensor2.requires_grad() : tensor1.requires_grad(); + if (t2_requires_grad && !has_out) { + // We should be checking !at::GradMode::is_enabled(), but apparently + // this regresses performance in some cases: + // https://github.com/pytorch/pytorch/issues/118548#issuecomment-1916022394 + return true; + } + + // Don't fold in this case, as we would have to call mm on the transposed tensor, the result + // would be contiguous, and then we would need to transpose it and call contiguous on it, thus + // having to copy the tensor + if (tensor1.dim() == 2) { + return false; + } + + // Can always fold if the tensor is empty + // This serves as a precondition for the code below + if (TORCH_GUARD_OR_FALSE(t1->sym_numel().sym_eq(0))) { + return true; + } + + // t1->view(-1, t1->size(-1)) does not copy only when the first n-1 dimensions are contiguous + // in the sense that t1_stride[i] = t1_stride[i+1]*t1_shape[i+1] + const auto t1_shape = t1->sym_sizes(); + const auto t1_strides = t1->sym_strides(); + for (auto i = int64_t{0}; i < dim_t1 - int64_t{2}; ++i) { + if (TORCH_GUARD_OR_TRUE( + t1_strides[i].sym_ne(t1_strides[i + 1] * t1_shape[i + 1]))) { + return false; + } + } + return true; +} + +/* +Matrix product of two Tensors. +The behavior depends on the dimensionality of the Tensors as follows: +- If both Tensors are 1-dimensional, (1d) the dot product (scalar) is returned. +- If the arguments are 2D - 1D or 1D - 2D, the matrix-vector product is returned. +- If both arguments are 2D, the matrix-matrix product is returned. +- If one of the arguments is ND with N >= 3 and the other is 1D or 2D, and some + conditions on the strides apply (see should_fold) we fold the first N-1 dimensions + of the ND argument to form a matrix, call mm or mv, reshape it back to ND and return it +- Otherwise, we return bmm, after broadcasting and folding the batched dimensions if + there's more than one +*/ +static Tensor _matmul_impl( + Tensor& out, + const Tensor& tensor1, + const Tensor& tensor2) { + const auto dim_tensor1 = tensor1.dim(); + const auto dim_tensor2 = tensor2.dim(); + + // This is checked up here to simplify the logic below + // Note that the strings are just evaluated on failure, so almost always we just evaluate + // the condition and move on + TORCH_CHECK(dim_tensor1 != 0 && dim_tensor2 != 0, + "both arguments to matmul need to be at least 1D, but they are ", + dim_tensor1, "D and ", dim_tensor2, "D"); + + + const bool has_out = out.defined(); + + if (has_out) { + // Usually we would rely on the out= kernels we decompose into to check this, but + // for matmul there is logic at the composite level that relies on this invariant. + TORCH_CHECK(!(tensor1.requires_grad() || tensor2.requires_grad() || out.requires_grad()) || !at::GradMode::is_enabled(), + "matmul(): functions with out=... arguments don't support automatic differentiation, " + "but one of the arguments requires grad." + ); + } + + if (dim_tensor1 == 1 && dim_tensor2 == 1) { + return has_out ? at::dot_out(out, tensor1, tensor2) : tensor1.dot(tensor2); + } else if (dim_tensor1 == 2 && dim_tensor2 == 1) { + return has_out ? at::mv_out(out, tensor1, tensor2) : tensor1.mv(tensor2); + } else if (dim_tensor1 == 1 && dim_tensor2 == 2) { + return has_out ? at::mm_out(out, tensor1.unsqueeze(0), tensor2).squeeze_(0) + : tensor1.unsqueeze(0).mm(tensor2).squeeze_(0); + } else if (dim_tensor1 == 2 && dim_tensor2 == 2) { + return has_out ? at::mm_out(out, tensor1, tensor2) : tensor1.mm(tensor2); + } else if (should_fold(tensor1, tensor2, has_out)) { + // dim_tensor1 >=3 && (dim_tensor2 == 1 || dim_tensor2 == 2) || + // dim_tensor2 >=3 && (dim_tensor1 == 1 || dim_tensor1 == 2) + // and at least one of the following two conditions hold + // - the small tensor requires grad (see should_fold for the why) + // - we can fold the larger tensor t1 into a matrix as t1.view(-1, t1.size(-1)) without copying + + // optimization: use mm instead of bmm by folding the batch of the larger tensor + // into its leading matrix dimension + const auto transpose = dim_tensor2 > dim_tensor1; + const auto t1 = transpose ? MaybeOwned::owned(tensor2.mT()) + : MaybeOwned::borrowed(tensor1); + const auto t2 = !transpose ? MaybeOwned::borrowed(tensor2) + : dim_tensor1 == 2 + ? MaybeOwned::owned(tensor1.t()) + : MaybeOwned::borrowed(tensor1); + // Invariant: t1->dim() >= 3 && (t2->dim() == 1 || t2->dim() == 2) + // and *t1 and *t2 are matmul-compatible + + // Why not t1->view(-1, sizes_1.back())? + // If the last dim is 0, then view(-1, 0) won't work because the -1 becomes ambiguous. + // This can happen in e.g. [3, 5, 0] @ [0, 0]. + const auto sizes_1 = t1->sym_sizes(); + auto output_shape = c10::SymDimVector(sizes_1.begin(), sizes_1.end() - 1); + const auto folded_dim1 = c10::multiply_integers(output_shape); + + // Readjust output_shape if we are multiplying by a matrix + const auto t2_is_matrix = t2->dim() == 2; + if (t2_is_matrix) { + output_shape.push_back(t2->sym_sizes()[1]); + } + // This will almost always be a view. + // It may not be a view if t2->requires_grad(). See should_fold for an explanation + const c10::SymDimVector t1_folded_shape{folded_dim1, sizes_1.back()}; + const auto t1_folded = at::reshape_symint(*t1, t1_folded_shape); + if (!has_out) { + if (t2_is_matrix) { + const auto output = at::_unsafe_view_symint(t1_folded.mm(*t2), output_shape); + // This copies if we perform a 2D @ 3D and the first tensor requires_grad + // See should_fold for why. + // If mm_out were differentiable, we could use it here, and pass a result with the + // correct strides to avoid this unnecessary copy. + return transpose ? output.mT().contiguous() : output; + } else { + return at::_unsafe_view_symint(t1_folded.mv(*t2), output_shape); + } + } else { + // See the !has_out branch for an explanation + TORCH_INTERNAL_ASSERT(!(transpose && t2_is_matrix)); + + // Resize output into the correct shape + at::native::resize_output_symint(out, output_shape); + + // We then reshape the output to the expected shape and call mm/mv + // and transpose back if necessary + auto reshaped_out = t2_is_matrix + ? at::reshape_symint( + out, c10::SymDimVector{folded_dim1, t2->sym_sizes().back()}) + : at::reshape_symint(out, c10::SymDimVector{folded_dim1}); + if (t2_is_matrix) { + at::mm_out(reshaped_out, t1_folded, *t2); + } else { + at::mv_out(reshaped_out, t1_folded, *t2); + } + if (!reshaped_out.is_alias_of(out)) { + out.copy_(reshaped_out); + } + return out; + } + } else { + // dim_tensor1 >= 3 || dim_tensor2 >= 3 + // We track m1 vs m2 separately even though they must match for nicer error messages + const auto tensor1_sizes = tensor1.sym_sizes(); + const auto tensor2_sizes = tensor2.sym_sizes(); + const c10::SymInt n = dim_tensor1 > 1 ? tensor1_sizes[dim_tensor1 - 2] : c10::SymInt(1); + const c10::SymInt m1 = tensor1_sizes[dim_tensor1 - 1]; + const c10::SymInt m2 = dim_tensor2 > 1 ? tensor2_sizes[dim_tensor2 - 2] : tensor2_sizes[0]; + const c10::SymInt p = dim_tensor2 > 1 ? tensor2_sizes[dim_tensor2 - 1] : c10::SymInt(1); + c10::SymDimVector batch_tensor1( + tensor1_sizes.begin(), + tensor1_sizes.begin() + std::max(dim_tensor1 - 2, 0LL)); + c10::SymDimVector batch_tensor2( + tensor2_sizes.begin(), + tensor2_sizes.begin() + std::max(dim_tensor2 - 2, 0LL)); + + // Same optimization for the gradients as that in should_fold + // If we're going to broadcast we force it to go through the should_fold branch + if (dim_tensor1 == 3 && dim_tensor2 == 3 && + TORCH_GUARD_OR_TRUE(batch_tensor1[0].sym_ne(batch_tensor2[0]))) { + if (TORCH_GUARD_OR_FALSE(batch_tensor1[0].sym_eq(1)) && + (tensor1.requires_grad() || isTensorSubclassLike(tensor1))) { + return _matmul_impl(out, tensor1.squeeze(0), tensor2); + } + if (TORCH_GUARD_OR_FALSE(batch_tensor2[0].sym_eq(1)) && + (tensor2.requires_grad() || isTensorSubclassLike(tensor2))) { + return _matmul_impl(out, tensor1, tensor2.squeeze(0)); + } + } + + auto output_shape = infer_size_symdimvector(batch_tensor1, batch_tensor2); + const c10::SymInt expand_batch_product = c10::multiply_integers(output_shape); + + // flatten expanded batches + const auto tensor1_expand_size = [&output_shape, n, m1]{ + c10::SymDimVector ret(output_shape); + ret.append({n, m1}); + return ret; + }(); + const auto tensor1_expanded = tensor1 + .expand_symint(tensor1_expand_size) + .reshape_symint({expand_batch_product, n, m1}); + // We need to treat the dim_tensor2 == 1 case separately as broadcasting would not convert + // a vector of shape (n,) into a batch of matrices of shape (*, n, 1) + auto vector_rhs = dim_tensor2 == 1; + const auto tensor2_expand_size = [&output_shape, m2, p, vector_rhs]{ + c10::SymDimVector ret(output_shape); + if (vector_rhs) { + ret.push_back(m2); + } else { + ret.append({m2, p}); + } + return ret; + }(); + auto tensor2_expanded = tensor2.expand_symint(tensor2_expand_size); + if (vector_rhs) { + tensor2_expanded = tensor2_expanded + .reshape_symint({expand_batch_product, m2}) + .unsqueeze(2); + } else { + tensor2_expanded = tensor2_expanded.reshape_symint({ + expand_batch_product, + m2, + p, + }); + } + + if (dim_tensor1 > 1) { + output_shape.push_back(n); + } + if (dim_tensor2 > 1) { + output_shape.push_back(p); + } + + if (!has_out) { + if (vector_rhs) { + return at::_unsafe_view_symint( + tensor1_expanded.bmm(tensor2_expanded).squeeze(-1), output_shape); + } else { + return at::_unsafe_view_symint( + tensor1_expanded.bmm(tensor2_expanded), output_shape); + } + } else { + at::native::resize_output_symint(out, output_shape); + auto reshaped_out = at::reshape_symint( + out, c10::SymDimVector{expand_batch_product, n, p}); + at::bmm_out(reshaped_out, tensor1_expanded, tensor2_expanded); + if (vector_rhs) { + reshaped_out = reshaped_out.squeeze(-1); + } + if (!reshaped_out.is_alias_of(out)) { + out.copy_(reshaped_out.view_symint(out.sym_sizes())); + } + return out; + } + } +} + +Tensor matmul(const Tensor & tensor1, const Tensor & tensor2) { + at::Tensor result, unused; + result = at::native::_matmul_impl(unused, tensor1, tensor2); + return result; +} + +Tensor& matmul_out(const Tensor & tensor1, const Tensor & tensor2, Tensor &result) { + at::native::_matmul_impl(result, tensor1, tensor2); + return result; +} + +// torch.linalg.matmul, alias for torch.matmul +Tensor linalg_matmul(const Tensor & tensor1, const Tensor & tensor2) { + return at::matmul(tensor1, tensor2); +} + +Tensor& linalg_matmul_out(const Tensor & tensor1, const Tensor & tensor2, Tensor &result) { + return at::matmul_out(result, tensor1, tensor2); +} + +// torch.linalg.diagonal, alias for torch.diagonal with dim1=-2, dim2=-1 as defaults +Tensor linalg_diagonal(const Tensor& A, int64_t offset, int64_t dim1, int64_t dim2) { + return A.diagonal(offset, dim1, dim2); +} + +// helper methods for matrix_exp +namespace { + +template +using array2d = std::array, ROW>; + +// we consider 6 Taylor expansions of degree +// 1, 2, 4, 8, 12, 18 +constexpr int total_n_degs = 6; + +Tensor operator_1_norm(const Tensor& tensor) { + return std::get<0>(tensor.abs().sum(-2).max(-1)); +} + +// Allocates a buffers of uninitialized or zero values +// of shape [n_copies, a.size()] +Tensor _allocate_buffer(const Tensor& a, int n_copies, bool is_zero = false) { + auto res = at::empty( + {n_copies, a.size(0), a.size(1), a.size(2)}, + a.options().memory_format(at::MemoryFormat::Contiguous) + ); + + if (is_zero) { + res.zero_(); + } + + return res; +} + +// Makes `buffer` to store `num_matrices` number of matrices needed for +// compute the matrix exponentials of different orders, i.e. +// first `num_matrices` matrices from the list l := {I, A, A^2, A^3, A^6} +// in a contiguous block of memory such that +// buffer[0, ...] = l[0], // I +// buffer[1, ...] = l[1], // A +// ... +// buffer[num_matrices - 1, ...] = l[num_matries - 1] +void _fill_matrix_powers(Tensor& buffer, const Tensor& a, int num_matrices) { + auto a_sizes_minus_last = a.sizes().vec(); + a_sizes_minus_last.pop_back(); + // fill I + buffer.select(0, 0).copy_( + at::diag_embed( + at::ones({1}, buffer.options()) + .expand(a_sizes_minus_last) + ) + ); + + // fill a + buffer.select(0, 1).copy_(a); + + // fill a^2 + if (2 <= num_matrices - 1) { + // out for a^2 + auto view_out = buffer.select(0, 2); + _matmul_impl( + view_out, + buffer.select(0, 1), + buffer.select(0, 1) + ); + } + + // fill a^3 + if (3 <= num_matrices - 1) { + // out for a^3 + auto view_out = buffer.select(0, 3); + _matmul_impl( + view_out, + buffer.select(0, 1), + buffer.select(0, 2) + ); + } + + // fill a^6 + if (4 <= num_matrices - 1) { + // out for a^6 + auto view_out = buffer.select(0, 4); + _matmul_impl( + view_out, + buffer.select(0, 3), + buffer.select(0, 3) + ); + } +} + +inline Tensor _move_memory_if_cuda_input( + const Tensor& mem, + const Tensor& in +) { + return (in.device().type() == at::kCUDA) + ? mem.to(at::device_of(in).value()) + : mem; +} + +// convert a 1D blob to a 2D Tensor of size [1, blob.size()] +// such that blob.device() == in.device()) +// designed to be used with _compute_linear_combination +template +inline Tensor _blob_to_Tensor( + std::initializer_list blob, + const Tensor& in +) { + // we convert to void* expecitly because begin() returns + // a pointer to a constant. + // Blob is assumed to be a 1D array, that is why + // we also insert a fake dimension so that the result could directly + // be used in _compute_linear_combination + auto tensor = at::from_blob((void*)blob.begin(), blob.size(), + c10::toRealValueType(in.scalar_type())).unsqueeze(0); + return _move_memory_if_cuda_input(tensor, in); +} + +template +inline Tensor _linear_combination( + const Tensor& t, + std::initializer_list blob) { + // _blob_to_Tensor converts blob to a 2D tensor for _compute_linear_combination. + // If this tensor is of shape (1, *), the result of _compute_linear_combination + // is going to be of shape (1, *t.shape) so we squeeze(0) so that + // for any t with t.dim() >= 1: t.dim() == _compute_linear_combination(t, ...).dim(). + return at::native::_compute_linear_combination( + t, _blob_to_Tensor(blob, t)) + .squeeze(0); +} + +// I + A +Tensor compute_T1(const Tensor& A) { + // 2 for {I, A} + auto As = _allocate_buffer(A, 2); + _fill_matrix_powers(As, A, 2); + return As.sum(0); +} + +// I + A + A^2 / 2 +Tensor compute_T2(const Tensor& A) { + auto As = _allocate_buffer(A, 3); + // 3 for {I, A, A^2} + _fill_matrix_powers(As, A, 3); + As.select(0, 2).div_(2.0); + return As.sum(0); +} + +// I + A + A^2 * (I / 2 + A / 6 + A^2 / 24) +template +Tensor compute_T4(const Tensor& A) { + auto As = _allocate_buffer(A, 4); + // 3 for {I, A, A^2} + _fill_matrix_powers(As, A, 3); + + // output for A^2 * (I / 2 + A / 6 + A^2 / 24) + auto view_out = As.select(0, 3); + _matmul_impl( + view_out, + // contains A^2 + As.select(0, 2), + // computes (I / 2 + A / 6 + A^2 / 24) + _linear_combination( + As.narrow(0, 0, 3), + {1 / 2.0, 1 / 6.0, 1 / 24.0} + ) + ); + + // I + A + A^2 * (I / 2 + A / 6 + A^2 / 24) + return _linear_combination( + As, {1.0, 1.0, 0.0, 1.0} + ); +} + +template +Tensor compute_T8(const Tensor& A) { + constexpr scalar_t sqrt_177 = 0.1330413469565007072504e+2; + constexpr scalar_t x3 = 2. / 3.; + constexpr scalar_t x1 = x3 * ((1. + sqrt_177) / 88.); + constexpr scalar_t x2 = x3 * ((1. + sqrt_177) / 352.); + constexpr scalar_t x4 = (-271. + 29. * sqrt_177) / (315. * x3); + constexpr scalar_t x5 = (-11. + 11. * sqrt_177) / (1260. * x3); + constexpr scalar_t x6 = (-99. + 11. * sqrt_177) / (5040. * x3); + constexpr scalar_t x7 = (89. - sqrt_177) / (5040. * x3); + constexpr scalar_t y2 = (857. - 58. * sqrt_177) / 630.; + + auto As = _allocate_buffer(A, 5); + // 3 for {I, A, A^2} + _fill_matrix_powers(As, A, 3); + + // output for A4 + auto view_out = As.select(0, 3); + // A4 = A2 * (x1 * A + x2 * A2) + _matmul_impl( + view_out, + // As.select(0, 2) = A^2 + As.select(0, 2), + _linear_combination( + // extract {A, A^2} from As + As.narrow(0, 1, 2), + {x1, x2} + ) + ); + + // output for A8 + view_out = As.select(0, 4); + // A8 = (x3 * A2 + A4) * (x4 * I + x5 * A + x6 * A2 + x7 * A4) + _matmul_impl( + view_out, + // x3 * A2 + A4 + _linear_combination( + As.narrow(0, 2, 2), + {x3, 1.0} + ), + _linear_combination( + As.narrow(0, 0, 4), + {x4, x5, x6, x7} + ) + ); + + // return I + A + y2 * A2 + A8; + return _linear_combination( + As, {1.0, 1.0, y2, 0.0, 1.0} + ); +} + +template +Tensor compute_T12(const Tensor& A) { + constexpr int num_prods = 4; + array2d b = {{ + { + 9.0198e-16, + 0.46932117595418237389, + -0.20099424927047284052, + -0.04623946134063071740 + }, + { + 5.31597895759871264183, + 1.19926790417132231573, + 0.01179296240992997031, + 0.01108844528519167989 + }, + { + 0.18188869982170434744, + 0.05502798439925399070, + 0.09351590770535414968, + 0.00610700528898058230 + }, + { + -2.0861320e-13, + -0.13181061013830184015, + -0.02027855540589259079, + -0.00675951846863086359 + } + }}; + + // gather coefficients `b` from above into a tensor, + // and move them to device `device_of(A)` + auto bs = at::from_blob( + reinterpret_cast(&b), + {num_prods, num_prods}, + {num_prods, 1}, + c10::toRealValueType(A.scalar_type()) + ); + bs = _move_memory_if_cuda_input(bs, A); + + auto As = _allocate_buffer(A, num_prods); + _fill_matrix_powers(As, A, num_prods); + + auto Bs = at::native::_compute_linear_combination(As, bs); + + // output for A6 + auto view_out = As.select(0, 0); + // compute A6 + Bs.select(0, 2).add_(_matmul_impl( + view_out, + Bs.select(0, 3), + Bs.select(0, 3) + )); + + return Bs.select(0, 0).add_(_matmul_impl( + view_out, + Bs.select(0, 1).add_(Bs.select(0, 2)), + Bs.select(0, 2) + )); +} + +template +Tensor compute_T18(const Tensor& A) { + constexpr int num_prods = 5; + array2d b = {{ + { + 0., + -1.00365581030144618291e-01, + -8.02924648241156932449e-03, + -8.92138498045729985177e-04, + 0. + }, + { + 0., + 3.97849749499645077844e-01, + 1.36783778460411720168e+00, + 4.98289622525382669416e-01, + -6.37898194594723280150e-04 + }, + { + -1.09676396052962061844e+01, + 1.68015813878906206114e+00, + 5.71779846478865511061e-02, + -6.98210122488052056106e-03, + 3.34975017086070470649e-05 + }, + { + -9.04316832390810593223e-02, + -6.76404519071381882256e-02, + 6.75961301770459654925e-02, + 2.95552570429315521194e-02, + -1.39180257516060693404e-05 + }, + { + 0., + 0., + -9.23364619367118555360e-02, + -1.69364939002081722752e-02, + -1.40086798182036094347e-05 + } + }}; + + // gather coefficients `b` from above into a tensor, + // and move them to device `device_of(A)` + auto bs = at::from_blob( + reinterpret_cast(&b), + {num_prods, num_prods}, + {num_prods, 1}, + c10::toRealValueType(A.scalar_type()) + ); + bs = _move_memory_if_cuda_input(bs, A); + + auto As = _allocate_buffer(A, num_prods); + _fill_matrix_powers(As, A, num_prods); + + auto Bs = at::native::_compute_linear_combination(As, bs); + + // tmp buffer for this matrix product + auto view_out = As.select(0, 0); + // compute A9 + Bs.select(0, 3).add_(_matmul_impl( + view_out, + Bs.select(0, 0), + Bs.select(0, 4)) + ); + + return Bs.select(0, 1).add_(_matmul_impl( + view_out, + Bs.select(0, 2).add_(Bs.select(0, 3)), + Bs.select(0, 3) + )); +} + +template +Tensor compute_T18_scale_square( + const Tensor& a, + const Tensor& norm, + scalar_t theta +) { + // Scale + // We eventually need to do the matrix multiplication to calculate the result. + // For example, if we have `norm` equal to [27, 6, 6, 0.05], we will end up to + // get `s` as [4, 1, 1, 0], so we can use it to get the result by calculating + // matrix[0]^(2^4), matrix[1]^(2^1) and matrix[2]^(2^1) one by one to get the + // result, such "one by one calculation" will be quite slow. + const auto s = (at::ceil(at::log2(norm / theta))).clamp(/*min=*/0); + const auto pow2s = at::pow(2, -s); + const auto a_scaled = a * pow2s.view({-1, 1, 1}); + auto mexp_scaled = at::native::compute_T18(a_scaled); + + // Sort: + // Consider inputs are square matrix, so if we first power `matrix 0,1,2`, then + // the remain thing will only be multiply `matrix 0` by (2^4 - 1) times, which + // gives us an opportunity to calculate the matrix multiplication in a batch. + // The first thing we need to do is sort tensor `s`, which will be helpful to + // do the matrix multiplication by range. + // With above example, `sorted_s` is [0, 1, 1, 4], we also will need the index + // info, so we can use it to compose the result back. + auto [sorted_s, sorted_s_inds] = at::sort(s, /*dim=*/0); + sorted_s = sorted_s.to(at::kLong); + // Then we call `unique_consecutive` and we will use it to split `sorted_s`, + // with above example, `split_counts` is [1, 2, 1]. + auto split_counts = std::get<2>(at::unique_consecutive(sorted_s, true, /*return_counts=*/true)); + // We also need to know the index of the last element of each split, so we can + // know how many times we need to do the multiplication for each split matrix. + // Notice that, we will not need to calculate the actual pows, because we will + // use the cumulative matrix multiplication. + // With about example, `mul_times` will be [0, 1, 3]. + auto split_edges = at::cumsum(split_counts, /*dim=*/0) - 1; + auto unique_s = sorted_s.index_select(0, split_edges).clamp(/*min=*/0); + auto mul_times = at::diff(unique_s, 1, -1, /*prepend=*/unique_s.new_zeros({1})); + + // Square + auto section_values = at::cat({split_counts, mul_times}, 0).to(at::kCPU); + + TORCH_INTERNAL_ASSERT(section_values.is_contiguous()); + const auto section_numel = section_values.numel() / 2; + auto scs = section_values. template data_ptr(); + auto pts = &scs[section_numel]; + + // We now will do the matrix multiplication in a batch, with above example: + // 1. Multiply all matrices by 0 (`mul_times[0]`) times, then do `slice` + // to get the remain matrices by acc[1:] (`split_counts[0]`), + // 2. Multiply remain matrices by 1 times and slice to acc[2:] + // 3. Multiply remain matrices by 3 times and slice to acc[1:] + // All processed matrices will be stored in `output_pieces`. + std::vector output_pieces; + output_pieces.reserve(section_numel); + auto acc = mexp_scaled.index_select(0, sorted_s_inds); + for (int64_t i = 0; i < section_numel; ++i) { + for (int64_t j = 0; j < pts[i]; j++) { + // To avoid AMP autocasting caused by at::matmul + auto acc_out = at::empty_like(acc); + acc = at::matmul_out(acc_out, acc, acc); + } + output_pieces.push_back(acc.slice(0, 0, scs[i])); + acc = acc.slice(0, scs[i]); + } + + // Compose the result back + auto output = at::cat(output_pieces, 0); + return output.index_select(0, at::argsort(sorted_s_inds)); +} + +template +Tensor mexp_impl( + const Tensor& a, + std::array thetas, + bool compute_highest_degree_approx = false +) { + const auto norm = operator_1_norm(a); + const auto batch_size = a.size(0); + if (batch_size > 1) { + compute_highest_degree_approx = true; + } + + if (!compute_highest_degree_approx) { + // To prevent undefined behavior which outputs "normal" result from a matrix + // contains NaN values, we put NaN values in `res`, so if input has NaN values, + // its computation will be skipped to return the NaN contained `res` directly. + auto res = at::full_like(a, std::numeric_limits::quiet_NaN(), {}, + at::MemoryFormat::Contiguous); + // `norm_cpu` is used to decide which Tensors require which approximation + // based on their norm. This decision takes place on CPU. + // It requires moving data back and forth between devices when `a` is on CUDA, + // but at the cost of only one single CPU-CUDA synchronization (instead of 6), + // and better performance overall (benchmarked). + const auto norm_cpu = (a.device().type() == at::kCUDA) + ? norm.to(at::kCPU) : norm; + + constexpr std::array< + Tensor(*)(const Tensor&), + total_n_degs - 1> + compute_Ts = { + compute_T1, compute_T2, compute_T4, + compute_T8, compute_T12 + }; + + for (int i = 0; i < total_n_degs - 1; ++i) { + auto norm_lower_bound = (i == 0) ? static_cast(-1) : thetas[i - 1]; + auto norm_upper_bound = thetas[i]; + // nonzero returns a 2D tensor, hence squeeze(-1) to make it 1D + auto idx_curr_norm_interval = ( + (norm_lower_bound < norm_cpu) * (norm_cpu <= norm_upper_bound) + ).nonzero().squeeze(-1); + + if (idx_curr_norm_interval.numel()) { + auto idx_to_device = _move_memory_if_cuda_input( + idx_curr_norm_interval, a + ); + auto sub_a = at::index_select(a, 0, idx_to_device); + res.index_put_({idx_to_device}, compute_Ts[i](sub_a)); + } + } + + // nonzero returns a 2D tensor, hence squeeze(-1) to make it 1D + auto idx_large_norm = (norm_cpu >= thetas[total_n_degs - 2]) + .nonzero().squeeze(-1); + + if (idx_large_norm.numel()) { + auto idx_to_device = _move_memory_if_cuda_input( + idx_large_norm, a + ); + auto a_large_norm = at::index_select(a, 0, idx_to_device); + auto large_norm_subset = at::index_select(norm, 0, idx_to_device); + auto mexp_out = compute_T18_scale_square( + a_large_norm, + large_norm_subset, + thetas[total_n_degs - 1] + ); + res.index_put_({idx_large_norm}, mexp_out); + } + return res; + } + + return compute_T18_scale_square( + a, norm, + thetas[total_n_degs - 1] + ); +} + +// matrix exponential +Tensor mexp(const Tensor& a, bool compute_highest_degree_approx = false) { + // squash batch dimensions to one dimension for simplicity + const auto a_3d = a.view({-1, a.size(-2), a.size(-1)}); + + if (a.scalar_type() == at::ScalarType::Float + || a.scalar_type() == at::ScalarType::ComplexFloat) { + constexpr std::array thetas_float = { + 1.192092800768788e-07, // deg 1 + 5.978858893805233e-04, // deg 2 + 5.116619363445086e-02, // deg 4 + 5.800524627688768e-01, // deg 8 + 1.461661507209034e+00, // deg 12 + 3.010066362817634e+00 // deg 18 + }; + + return mexp_impl(a_3d, thetas_float, compute_highest_degree_approx) + .view(a.sizes()); + } + else { // if Double or ComplexDouble + constexpr std::array thetas_double = { + 2.220446049250313e-16, // deg 1 + 2.580956802971767e-08, // deg 2 + 3.397168839976962e-04, // deg 4 + 4.991228871115323e-02, // deg 8 + 2.996158913811580e-01, // deg 12 + 1.090863719290036e+00 // deg 18 + }; + + return mexp_impl(a_3d, thetas_double, compute_highest_degree_approx) + .view(a.sizes()); + } +} + +// TODO This should be deprecated in favor of linalg_matrix_exp_differential +// in FunctionsManual.cpp +template +Tensor backward_analytic_function_of_a_matrix( + const Tensor& self, const Tensor& grad, + const func_t& function_of_a_matrix + ) { + auto self_transposed = self.mH(); + auto self_transposed_sizes = self_transposed.sizes().vec(); + self_transposed_sizes[self.dim() - 2] <<= 1; + self_transposed_sizes[self.dim() - 1] <<= 1; + + auto n = self_transposed.size(-1); + auto meta_grad = at::zeros(self_transposed_sizes, grad.options()); + meta_grad.narrow(-2, 0, n).narrow(-1, 0, n).copy_(self_transposed); + meta_grad.narrow(-2, n, n).narrow(-1, n, n).copy_(self_transposed); + meta_grad.narrow(-2, 0, n).narrow(-1, n, n).copy_(grad); + + auto grad_input = function_of_a_matrix(meta_grad) + .narrow(-2, 0, n).narrow(-1, n, n); + return grad_input; +} +} // end anon namespace + +// Computes the matrix exponential for a given batch of squared matrices. +// The implementation is based on: +// +// Bader, P.; Blanes, S.; Casas, F. +// Computing the Matrix Exponential with an Optimized Taylor Polynomial Approximation. +// Mathematics 2019, 7, 1174. +// +Tensor linalg_matrix_exp(const Tensor& a) { + squareCheckInputs(a, "linalg.matrix_exp"); + checkFloatingOrComplex(a, "linalg.matrix_exp"); + + NoTF32Guard disable_tf32; + + // Trivial cases + const auto n = a.size(-1); + if (n == 0) { + return a.clone(); + } else if (n == 1) { + return a.exp(); + } else { + return at::native::mexp(a); + } +} + +// Alias +Tensor matrix_exp(const Tensor& a) { + return at::linalg_matrix_exp(a); +} + +// Principal square root of a symmetric/Hermitian positive-definite matrix. +// Computed from the eigendecomposition A = Q diag(lambda) Q^H as +// A^{1/2} = Q diag(sqrt(lambda)) Q^H. Only the lower triangle of `a` is read +// (via linalg_eigh, UPLO="L"); `a` is assumed Hermitian. The custom backward in +// FunctionsManual.cpp (linalg_matrix_sqrth_differential) uses the Daleckii-Krein +// formula, whose denominator sqrt(lambda_i) + sqrt(lambda_j) stays well-defined +// even at degenerate eigenvalues. +Tensor linalg_matrix_sqrth(const Tensor& a) { + squareCheckInputs(a, "linalg.matrix_sqrth"); + checkFloatingOrComplex( + a, "linalg.matrix_sqrth", /*allow_low_precision_dtypes=*/false); + + NoTF32Guard disable_tf32; + + if (a.sym_size(-1) == 0) { + return a.clone(); + } + auto [eigvals, eigvecs] = at::linalg_eigh(a); + + // PSD input may still show small eigenvalues due to roundoff. + // The clamp_min zeroes them. + auto sqrt_eigvals = eigvals.clamp_min(0).sqrt(); + auto result = at::matmul(eigvecs * sqrt_eigvals.unsqueeze(-2), eigvecs.mH()); + // The reconstruction is Hermitian up to roundoff; symmetrize to enforce it. + return 0.5 * (result + result.mH()); +} + +// TODO This should be deprecated in favor of linalg_matrix_exp_differential +// in FunctionsManual.cpp +Tensor matrix_exp_backward(const Tensor& self, const Tensor& grad) { + squareCheckInputs(self, "matrix_exp_backward"); + NoTF32Guard disable_tf32; + return backward_analytic_function_of_a_matrix( + self, grad, + [](const Tensor& a) { + return a.matrix_exp(); + } + ); +} + +TORCH_IMPL_FUNC(linalg_vector_norm_out)(const Tensor& self, const Scalar& scalar_ord, OptionalIntArrayRef opt_dim, bool keepdim, std::optional opt_dtype, const Tensor& result) { + // Casting a large integer to a double will just introduce an error for + // values larger than 10^53 (same for negative numbers), so that's fine. + auto ord = scalar_ord.toDouble(); + auto dim = opt_dim.value_or(IntArrayRef{}); + auto size = self.sizes(); + auto ndim = self.dim(); + + auto opt_dim_ = dim.vec(); + maybe_wrap_dims(opt_dim_, ndim); + + using Int = IntArrayRef::value_type; + std::vector all_dim(ndim); + std::iota(all_dim.begin(), all_dim.end(), 0); + + bool is_all_reduce = !opt_dim.has_value() || opt_dim.value().empty(); + auto reduce_dim = is_all_reduce ? all_dim : opt_dim_; + + bool is_reduce_over_1D_vector = true; + for (auto i : reduce_dim) { + if (size[i] != 1){ + is_reduce_over_1D_vector = false; + break; + } + } + + if (is_reduce_over_1D_vector) { + Tensor self_; + if (opt_dtype.has_value()) { + self_ = self.to(*opt_dtype); + } else { + self_ = self; + } + if (ord != 0.0) { + keepdim ? at::abs_outf(self_, const_cast(result)) : at::abs_outf(self_.squeeze(reduce_dim), const_cast(result)); + } else { + keepdim ? at::ne_outf(self_, 0, const_cast(result)) : at::ne_outf(self_.squeeze(reduce_dim), 0, const_cast(result)); + } + return; + } + + // No need to handle opt_dtype explicitly as it is already encoded in the dtype of result + + // https://github.com/pytorch/pytorch/issues/52648 + // Reductions always use `std::abs` to compute the absolute value. In the backward of this + // function, we need to locate the index that was selected as the largest value. To do so + // we do self.abs() == result to locate the index of the largest element. + // Now, self.abs() may dispatch to a vectorized implementation which gives slightly different + // results to the std::abs(std::complex) implementation. + // As such, to be able to compute the correct index in the backward, we need to use self.abs() + // both in the forward and in the backward + Tensor self_; + if (self.is_cpu() && self.is_complex() && std::abs(ord) == INFINITY) { + if (opt_dtype.has_value()) { + self_ = self.to(*opt_dtype).abs(); + } else { + self_ = self.abs(); + } + } else { + self_ = self; + } + + auto iter = make_reduction("vector_norm", const_cast(result), self_, dim, keepdim, result.scalar_type()); + norm_stub(iter.device_type(), iter, ord); +} + +// linalg__powsum: computes sum(|x|^ord) - the "power sum" without the final root +// This is useful for distributed computing where we want to reduce partial +// power sums across shards before taking the final root. +Tensor linalg__powsum( + const Tensor& self, + const Scalar& scalar_ord, + OptionalIntArrayRef opt_dim, + bool keepdim, + std::optional opt_dtype) { + auto ord = scalar_ord.toDouble(); + auto dim = opt_dim.value_or(IntArrayRef{}); + auto size = self.sizes(); + auto ndim = self.dim(); + + auto opt_dim_ = dim.vec(); + maybe_wrap_dims(opt_dim_, ndim); + + using Int = IntArrayRef::value_type; + std::vector all_dim(ndim); + std::iota(all_dim.begin(), all_dim.end(), 0); + + bool is_all_reduce = !opt_dim.has_value() || opt_dim.value().empty(); + auto reduce_dim = is_all_reduce ? all_dim : opt_dim_; + + // Compute output dtype (same logic as vector_norm) + auto compute_dtype = at::native::get_dtype_from_self(self, opt_dtype, /*promote_integers=*/true); + + // Create output tensor with the correct shape + auto result = create_reduction_result(self, opt_dim, keepdim, toRealValueType(compute_dtype)); + + if (result.numel() == 0) { + result.zero_(); + return result; + } + + // Check if reducing over dimensions that all have size 1 + bool is_reduce_over_1D_vector = true; + for (auto i : reduce_dim) { + if (size[i] != 1) { + is_reduce_over_1D_vector = false; + break; + } + } + + // Handle dtype conversion only when reducing over 1D + // (otherwise the kernel handles it via the result dtype) + Tensor self_; + if (is_reduce_over_1D_vector && opt_dtype.has_value()) { + self_ = self.to(*opt_dtype); + } else { + self_ = self; + } + + auto iter = make_reduction("powsum", result, self_, dim, keepdim, result.scalar_type()); + powsum_stub(iter.device_type(), iter, ord); + return result; +} + +// linalg__powsum_slow: fallback implementation for backends without optimized kernels +// Computes sum(|x|^ord) using basic ops +Tensor linalg__powsum_slow( + const Tensor& self, + const Scalar& scalar_ord, + OptionalIntArrayRef opt_dim, + bool keepdim, + std::optional opt_dtype) { + // Handle dtype conversion + Tensor self_; + if (opt_dtype.has_value()) { + self_ = self.to(*opt_dtype); + } else { + self_ = at::native::get_dtype_from_self(self, opt_dtype, /*promote_integers=*/true) != self.scalar_type() + ? self.to(at::native::get_dtype_from_self(self, opt_dtype, /*promote_integers=*/true)) + : self; + } + + // Compute |x|^ord and sum + auto abs_pow = at::pow(at::abs(self_), scalar_ord); + return at::sum(abs_pow, opt_dim, keepdim, toRealValueType(abs_pow.scalar_type())); +} + +static void _linalg_matrix_norm_checks(const Tensor& A, std::vector& dim, std::optional opt_dtype, bool low_precision) { + // A + at::native::checkIsMatrix(A, "linalg.matrix_norm"); + at::native::checkFloatingOrComplex(A, "linalg.matrix_norm", /*low_precision*/low_precision); + + // dim + TORCH_CHECK(dim.size() == 2, "linalg.matrix_norm: dim must be a 2-tuple. Got ", dim); + // wrap first to identify weird scenarios like A.ndim = 2, dim = (1, -1) + // dim is modified in place while wrapping it + maybe_wrap_dims(dim, A.dim()); + TORCH_CHECK(dim[0] != dim[1], "linalg.matrix_norm: dims must be different. Got (", dim[0], ", ", dim[1], ")"); + + // dtype + at::detail::check_linalg_norm_dtype(opt_dtype, A.scalar_type(), "linalg.matrix_norm"); +} + +Tensor linalg_matrix_norm( + const Tensor& A, + const Scalar& scalar_ord, + IntArrayRef dim, + bool keepdim, + std::optional opt_dtype) { + // Check ord first as it will be used in the dtype check of A + TORCH_CHECK(!at::isComplexType(scalar_ord.type()), "linalg.matrix_norm: Expected a non-complex scalar as the order of norm."); + auto ord = scalar_ord.toDouble(); + auto abs_ord = std::abs(ord); + TORCH_CHECK(abs_ord == 2. || abs_ord == 1. || abs_ord == INFINITY, "linalg.matrix_norm: Order ", ord, " not supported."); + + auto dim_ = dim.vec(); + // Check A, dim, and dtype + _linalg_matrix_norm_checks(A, dim_, opt_dtype, /*low_precision*/abs_ord != 2.); + + auto max_min_wrapper = [ord, keepdim](const Tensor &A, int64_t dim) { + if (A.size(dim) == 0 && ord > 0) { + auto new_shape(DimVector(A.sizes())); + auto dim_ = maybe_wrap_dim(dim, A.dim()); + if (keepdim) { + new_shape[dim_] = 1; + } else { + new_shape.erase(std::begin(new_shape) + dim_); + } + return at::zeros(new_shape, A.options()); + } else { + return ord > 0 ? A.amax(dim, keepdim) : A.amin(dim, keepdim); + } + }; + if (abs_ord == 2.) { + // Move dims to the end + auto permutation = create_dim_backshift_permutation(dim_[0], dim_[1], A.dim()); + + auto A_ = opt_dtype.has_value() ? A.to(*opt_dtype) : A; + auto result = max_min_wrapper(at::linalg_svdvals(A_.permute(permutation)), -1); + if (keepdim) { + auto permutation_reverse = create_reverse_permutation(std::move(permutation)); + result = result.unsqueeze(-1).permute(permutation_reverse); + } + return result; + } else { // 1, -1, inf, -inf + // The infty norm is like the 1 norm on the transposed matrix + if (abs_ord == INFINITY) { + std::swap(dim_[0], dim_[1]); + } + + // If the first reduction removes one dim from the front (dim_[0] < dim_[1]), after this + // reduction dim_[1] will be off by one + if (!keepdim && (dim_[0] < dim_[1])) { + dim_[1]--; + } + return max_min_wrapper(at::linalg_vector_norm(A, 1., {dim_[0]}, keepdim, opt_dtype), dim_[1]); + } +} + +Tensor& linalg_matrix_norm_out( + const Tensor& A, + const Scalar& ord, + IntArrayRef dim, + bool keepdim, + std::optional opt_dtype, + Tensor& result) { + checkSameDevice("linalg.matrix_norm", A, result); + auto out = at::linalg_matrix_norm(A, ord, dim, keepdim, opt_dtype); + TORCH_CHECK(out.scalar_type() == result.scalar_type(), + "linalg.matrix_norm expected out tensor dtype ", out.scalar_type(), + " but got: ", result.scalar_type()); + at::native::resize_output(result, out.sizes()); + result.copy_(out); + return result; +} + +// fro / nuc +Tensor linalg_matrix_norm( + const Tensor& A, + std::string_view ord, + IntArrayRef dim, + bool keepdim, + std::optional opt_dtype) { + // Check ord first as it will be used in the dtype check of A + TORCH_CHECK(ord == "fro" || ord == "nuc", "linalg.matrix_norm: Order ", ord, " not supported."); + + auto dim_ = dim.vec(); + // Check A, dim, and dtype + _linalg_matrix_norm_checks(A, dim_, opt_dtype, /*low_precision*/ord != "nuc"); + + if (ord == "fro") { + return at::linalg_vector_norm(A, 2, dim_, keepdim, opt_dtype); + } else { // nuc + auto A_ = opt_dtype.has_value() ? A.to(*opt_dtype) : A; + + // Move dims to the end + auto permutation = create_dim_backshift_permutation(dim_[0], dim_[1], A_.dim()); + auto result = at::linalg_svdvals(A_.permute(permutation)).sum(-1, keepdim); + if (keepdim) { + auto permutation_reverse = create_reverse_permutation(std::move(permutation)); + result = result.unsqueeze(-1).permute(permutation_reverse); + } + return result; + } +} + +Tensor& linalg_matrix_norm_out( + const Tensor& A, + std::string_view ord, + IntArrayRef dim, + bool keepdim, + std::optional opt_dtype, + Tensor& result) { + checkSameDevice("linalg.matrix_norm", A, result); + auto out = at::linalg_matrix_norm(A, ord, dim, keepdim, opt_dtype); + TORCH_CHECK(out.scalar_type() == result.scalar_type(), + "linalg.matrix_norm expected out tensor dtype ", out.scalar_type(), + " but got: ", result.scalar_type()); + at::native::resize_output(result, out.sizes()); + result.copy_(out); + return result; +} + +// Numerical or None norms +Tensor linalg_norm(const Tensor& X, const std::optional& opt_ord, OptionalIntArrayRef opt_dim, bool keepdim, std::optional opt_dtype) { + if (opt_dim.has_value()) { + TORCH_CHECK(opt_dim->size() == 1 || opt_dim ->size() == 2, "linalg.norm: If ", + "dim is specified, it must be of length 1 or 2. Got ", *opt_dim); + } else { + if (opt_ord.has_value()) { + TORCH_CHECK(X.dim() == 1 || X.dim() == 2, "linalg.norm: If ", + "dim is not specified but ord is, the input must be 1D or 2D. Got ", X.dim(), "D."); + } + } + + // If ord=None, we'll always use the 2-norm or frob norm (which are the same) so we go through + // vector_norm + if (opt_ord.has_value() && + ((opt_dim.has_value() && opt_dim->size() == 2) || + (!opt_dim.has_value() && X.dim() == 2))) { + using Int = IntArrayRef::value_type; + auto dim = opt_dim.has_value() ? opt_dim.value().vec() : std::vector{0, 1}; + return at::linalg_matrix_norm(X, *opt_ord, dim, keepdim, opt_dtype); + } else { + auto scalar_ord = opt_ord.value_or(Scalar(2.)); + return at::linalg_vector_norm(X, scalar_ord, opt_dim, keepdim, opt_dtype); + } +} + +Tensor& linalg_norm_out(const Tensor& X, const std::optional& opt_ord, OptionalIntArrayRef opt_dim, bool keepdim, std::optional opt_dtype, Tensor& result) { + checkSameDevice("linalg.norm", X, result); + auto out = at::linalg_norm(X, opt_ord, opt_dim, keepdim, opt_dtype); + TORCH_CHECK(out.scalar_type() == result.scalar_type(), + "linalg.norm expected out tensor dtype ", out.scalar_type(), + " but got: ", result.scalar_type()); + at::native::resize_output(result, out.sizes()); + result.copy_(out); + return result; +} + +// Frobenius and nuclear norms +Tensor linalg_norm(const Tensor& X, std::string_view ord, OptionalIntArrayRef opt_dim, bool keepdim, std::optional opt_dtype) { + if (opt_dim.has_value()) { + TORCH_CHECK(opt_dim->size() == 1 || opt_dim ->size() == 2, "linalg.norm: If ", + "dim is specified, it must be of length 1 or 2. Got ", *opt_dim); + } else { + TORCH_CHECK(X.dim() == 1 || X.dim() == 2, "linalg.norm: If ", + "dim is not specified but ord is, the input must be 1D or 2D. Got ", X.dim(), "D."); + } + using Int = IntArrayRef::value_type; + auto dim = opt_dim.has_value() ? opt_dim.value().vec() : std::vector{0, 1}; + return at::linalg_matrix_norm(X, ord, dim, keepdim, opt_dtype); +} + +Tensor& linalg_norm_out(const Tensor& X, std::string_view ord, OptionalIntArrayRef opt_dim, bool keepdim, std::optional opt_dtype, Tensor& result) { + checkSameDevice("linalg.norm", X, result); + auto out = at::linalg_norm(X, ord, opt_dim, keepdim, opt_dtype); + TORCH_CHECK(out.scalar_type() == result.scalar_type(), + "linalg.norm expected out tensor dtype ", out.scalar_type(), + " but got: ", result.scalar_type()); + at::native::resize_output(result, out.sizes()); + result.copy_(out); + return result; +} + +//////////////////////////////////////////////////////////////////////////////// +// Frobenius Norm // +//////////////////////////////////////////////////////////////////////////////// + +Tensor frobenius_norm(const Tensor& self, IntArrayRef dim, bool keepdim) { + auto device = self.device(); + if (self.layout() == Layout::Strided && (device == kCPU || device == kCUDA || device == kMeta)) { + TORCH_WARN_ONCE( + "at::frobenius_norm is deprecated and it is just left for JIT compatibility. ", + "It will be removed in a future PyTorch release. Please use ", + "`linalg.vector_norm(A, 2., dim, keepdim)` instead" + ); + } + // This frobenius norm is just wrong, but well + TORCH_CHECK(dim.size() <= 2, + "Expected at most 2 dimensions, but got ", dim.size(), " dimensions instead."); + // Dispatch to at::norm as it is implemented for Sparse and MPS backends + // TODO Make the backends implement vector_norm and matrix_norm + return at::norm(self, 2., dim, keepdim); +} + +Tensor &frobenius_norm_out(const Tensor& self, + IntArrayRef dim, + bool keepdim, + Tensor& result) { + auto device = self.device(); + if (self.layout() == Layout::Strided && (device == kCPU || device == kCUDA || device == kMeta)) { + TORCH_WARN_ONCE( + "at::frobenius_norm is deprecated and it is just left for JIT compatibility. ", + "It will be removed in a future PyTorch release. Please use ", + "`linalg.vector_norm(A, 2., dim, keepdim)` instead" + ); + } + TORCH_CHECK(dim.size() <= 2, + "Expected at most 2 dimensions, but got ", dim.size(), " dimensions instead."); + return at::norm_out(result, self, 2., dim, keepdim); +} + +//////////////////////////////////////////////////////////////////////////////// +// Nuclear Norm // +//////////////////////////////////////////////////////////////////////////////// + +Tensor nuclear_norm(const Tensor& self, bool keepdim) { + return at::native::nuclear_norm(self, IntArrayRef({-2, -1}), keepdim); +} + +Tensor &nuclear_norm_out(const Tensor& self, bool keepdim, Tensor& result) { + auto device = self.device(); + if (self.layout() == Layout::Strided && (device == kCPU || device == kCUDA || device == kMeta)) { + TORCH_WARN_ONCE( + "at::nuclear_norm is deprecated and it is just left for JIT compatibility. ", + "It will be removed in a future PyTorch release. Please use ", + "`linalg.matrix_norm(A, 'nuc', dim, keepdim)` instead" + ); + } + return at::linalg_matrix_norm_out(result, self, "nuc", IntArrayRef({-2, -1}), keepdim); +} + +Tensor nuclear_norm(const Tensor& self, IntArrayRef dim, bool keepdim) { + auto device = self.device(); + if (self.layout() == Layout::Strided && (device == kCPU || device == kCUDA || device == kMeta)) { + TORCH_WARN_ONCE( + "at::nuclear_norm is deprecated and it is just left for JIT compatibility. ", + "It will be removed in a future PyTorch release. Please use ", + "`linalg.matrix_norm(A, 'nuc', dim, keepdim)` instead" + ); + } + return at::linalg_matrix_norm(self, "nuc", dim, keepdim); +} + +Tensor& nuclear_norm_out(const Tensor& self, IntArrayRef dim, bool keepdim, Tensor& result) { + auto device = self.device(); + if (self.layout() == Layout::Strided && (device == kCPU || device == kCUDA || device == kMeta)) { + TORCH_WARN_ONCE( + "at::nuclear_norm is deprecated and it is just left for JIT compatibility. ", + "It will be removed in a future PyTorch release. Please use ", + "`linalg.matrix_norm(A, 'nuc', dim, keepdim)` instead" + ); + } + return at::linalg_matrix_norm_out(result, self, "nuc", dim, keepdim); +} + +//////////////////////////////////////////////////////////////////////////////// +// linalg.cond // +//////////////////////////////////////////////////////////////////////////////// + + +// This function helps to dispatch norm computations depending on 'ord' of variant type +static Tensor _linalg_cond_helper(const Tensor& self, std::variant ord_variant) { + Tensor inverse, info; + std::tie(inverse, info) = at::linalg_inv_ex(self); + info.unsqueeze_(-1).unsqueeze_(-1); + inverse.masked_fill_(info > 0, INFINITY); + + return std::visit([&](auto&& ord) { + Tensor norm_self = at::linalg_matrix_norm(self, ord); + Tensor norm_inverse = at::linalg_matrix_norm(inverse, ord); + Tensor result = norm_self * norm_inverse; + // fix multiplication of zero and infinity for NumPy compatibility + result.nan_to_num_(INFINITY, INFINITY, -INFINITY); + return result; + }, ord_variant); +} + +// Return zero for each matrix in the batch +static Tensor _linalg_cond_empty_matrix(const Tensor& self, c10::ScalarType dtype) { + auto result_shape = IntArrayRef(self.sizes().cbegin(), self.sizes().cend()-2); + TensorOptions options = self.options().dtype(toRealValueType(self.scalar_type())); + return at::zeros(result_shape, options); +} + +static void _linalg_cond_check_ord(std::variant ord_variant) { + if (ord_variant.index() == 0) { + Scalar* ord = std::get_if(&ord_variant); + TORCH_CHECK_VALUE(!at::isComplexType(ord->type()), + "linalg.cond: Expected a non-complex scalar as the order of norm."); + double abs_ord = std::abs(ord->toDouble()); + TORCH_CHECK_VALUE(abs_ord == 2.0 || abs_ord == 1.0 || abs_ord == INFINITY, + "linalg.cond got an invalid norm type: ", ord->toDouble()); + } else if (ord_variant.index() == 1) { + std::string_view* ord = std::get_if(&ord_variant); + TORCH_CHECK_VALUE(*ord == "fro" || *ord == "nuc", + "linalg.cond got an invalid norm type: ", *ord); + } else { + TORCH_CHECK(false, + "linalg.cond: something went wrong while checking the norm type"); + } +} + +// Numerical or None norms +Tensor linalg_cond(const Tensor& self, const std::optional& opt_ord) { + TORCH_CHECK(self.dim() >= 2, "linalg.cond: The input tensor must have at least 2 dimensions."); + + // The default case is using 2-norm + Scalar ord = opt_ord.has_value() ? opt_ord.value() : 2; + + std::variant ord_variant = ord; + _linalg_cond_check_ord(ord_variant); + + // NumPy doesn't define the condition number for 0x0 matrices, we return 0.0 for such input + if (self.sym_numel() == 0) { + auto real_dtype = toRealValueType(typeMetaToScalarType(self.dtype())); + return _linalg_cond_empty_matrix(self, real_dtype); + } + + // If ord == None or ord == ±2 + if (std::abs(ord.toDouble()) == 2.0) { + auto singular_values = at::linalg_svdvals(self); + // singular values are sorted in descending order + auto s_max = at::narrow(singular_values, /*dim=*/-1, /*start=*/0, /*length=*/1); + auto s_min = at::narrow(singular_values, /*dim=*/-1, /*start=*/-1, /*length=*/1); + Tensor result; + if (ord.toDouble() == -2.0) { + result = s_min / s_max; + } else { + result = s_max / s_min; + } + // squeeze the result for NumPy compatibility + return result.squeeze(-1); + } + + // ord == ±1 ord == ±inf + if (ord.isFloatingPoint()) { // ord == ±1 + squareCheckInputs(self, ("linalg.cond(ord=" + std::to_string(ord.to()) + ")").c_str()); + } else { // ord == ±inf + squareCheckInputs(self, ("linalg.cond(ord=" + std::to_string(ord.to()) + ")").c_str()); + } + return _linalg_cond_helper(self, std::move(ord_variant)); +} + +Tensor& linalg_cond_out(const Tensor& self, const std::optional& opt_ord, Tensor& result) { + checkSameDevice("linalg.cond", result, self); + ScalarType real_dtype = toRealValueType(self.scalar_type()); + checkLinalgCompatibleDtype("linalg.cond", result.scalar_type(), real_dtype); + + Tensor result_tmp = at::linalg_cond(self, opt_ord); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +// Frobenius or nuclear norms +Tensor linalg_cond(const Tensor& self, std::string_view ord) { + squareCheckInputs(self, ("linalg.cond(ord=" + std::string(ord) + ")").c_str()); + std::variant ord_variant = ord; + _linalg_cond_check_ord(ord_variant); + + // NumPy doesn't define the condition number for 0x0 matrices, we return 0.0 for such input + if (self.numel() == 0) { + return _linalg_cond_empty_matrix(self, self.scalar_type()); + } + + if (ord == "nuc") { + // calling matrix_norm with "nuc" on inputs with infinities raises an error + // therefore we use the mathematical definition of nuclear norm directly + // instead of going through the matrix_norm + auto singular_values = at::linalg_svdvals(self); + return singular_values.sum(-1) * (singular_values.reciprocal().sum(-1)); + } + + return _linalg_cond_helper(self, std::move(ord_variant)); +} + +// TODO: implement _out variant avoiding copy and using already allocated storage directly +Tensor& linalg_cond_out(const Tensor& self, std::string_view ord, Tensor& result) { + checkSameDevice("linalg.cond", result, self); + ScalarType real_dtype = toRealValueType(self.scalar_type()); + checkLinalgCompatibleDtype("linalg.cond", result.scalar_type(), real_dtype); + + Tensor result_tmp = at::linalg_cond(self, ord); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +Tensor linalg_tensorinv(const Tensor& self, int64_t ind) { + /* + The idea is to reduce the problem to 2D square matrix inversion. + Step 1. Calculate the shape of the result and the shape of the intermediate 2D matrix. + Step 2. Reshape `self` to 2D matrix. + Step 3. Invert the 2D matrix self.to_2D() + There is no quick way to find out whether the matrix is invertible, + so at this stage an error from at::inverse can be thrown. + Note that for CUDA this causes cross-device memory synchronization that can be slow. + Step 4. reshape the result. + */ + TORCH_CHECK(ind > 0, "Expected a strictly positive integer for 'ind', but got ", ind); + + // self[ind:] + std::vector shape_ind_end = self.sym_sizes().slice(ind).vec(); + // self[:ind] + std::vector shape_start_ind = self.sym_sizes().slice(0, ind).vec(); + + c10::SymInt prod_ind_end = c10::multiply_integers(shape_ind_end.cbegin(), shape_ind_end.cend()); + c10::SymInt prod_start_ind = c10::multiply_integers(shape_start_ind.cbegin(), shape_start_ind.cend()); + + // Check whether the self tensor can be reshaped to the 2D square matrix + TORCH_CHECK(prod_ind_end == prod_start_ind, + "Expected self to satisfy the requirement prod(self.shape[ind:]) == prod(self.shape[:ind]), but got ", + prod_ind_end, " != ", prod_start_ind); + + // Concatenate shape_ind_end and shape_start_ind to form the shape of the result + // self[ind:] + self[:ind] + shape_ind_end.insert(shape_ind_end.cend(), shape_start_ind.cbegin(), shape_start_ind.cend()); + + // If the reshaped self is not invertible catch this error + auto [result, info] = at::linalg_inv_ex(self.reshape_symint({prod_ind_end, prod_ind_end}), /*check_errors=*/false); + at::_linalg_check_errors(info, "inv", /*is_matrix*/true); + + return result.reshape_symint(shape_ind_end); +} + +// TODO: implement _out variant avoiding copy and using already allocated storage directly +Tensor& linalg_tensorinv_out(const Tensor& self, int64_t ind, Tensor& result) { + checkSameDevice("tensorinv", result, self); + checkLinalgCompatibleDtype("tensorinv", result, self); + + Tensor result_tmp = at::linalg_tensorinv(self, ind); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +Tensor linalg_tensorsolve(const Tensor& self, const Tensor& other, OptionalIntArrayRef dims) { + /* + The idea is to reduce the problem to 2D matrix solve. + Step 1. (optional) `self` is permuted with `dims` such that dimensions from `dims` are moved to the right. + For example, if we have 4D input with the shape (1, 2, 3, 4) and dims=(0, 2), + then the result of permutation would have the shape (2, 4, 1, 3). + Step 2. reshape `self` to 2D matrix. + Step 3. solve the matrix equation self.to_2D() @ result = other.to_1D() + Step 4. reshape the result. + */ + int64_t ndim = self.dim(); + Tensor self_ = self; + + // move dimensions of `self_` from `dims` to the end + if (dims.has_value()) { + DimVector dest_axes(dims.value().size()); + std::iota(dest_axes.begin(), dest_axes.end(), ndim - dest_axes.size()); + self_ = at::movedim(self_, dims.value(), dest_axes); + } + + // result_shape is self_.sizes[-(an-other.dim):] + std::vector result_shape = self_.sym_sizes().slice(other.dim(), ndim - other.dim()).vec(); + + c10::SymInt result_product = c10::multiply_integers(result_shape.begin(), result_shape.end()); + c10::SymInt other_product = c10::multiply_integers(other.sym_sizes().begin(), other.sym_sizes().end()); + + // Check whether the self tensor can be reshaped to the 2D square matrix + TORCH_CHECK(result_product == other_product, + "Expected self to satisfy the requirement prod(self.shape[other.ndim:]) == prod(self.shape[:other.ndim]), but got ", + result_product, " != ", other_product); + + self_ = self_.reshape_symint({result_product, result_product}); + + // normally `other` would be flattened by at::linalg_solve expects 2D input + Tensor result = at::linalg_solve(self_, other.flatten()); + return result.reshape_symint(result_shape); +} + +Tensor& linalg_tensorsolve_out(const Tensor& self, const Tensor& other, OptionalIntArrayRef dims, Tensor& result) { + checkSameDevice("tensorsolve", result, self); + checkLinalgCompatibleDtype("tensorsolve", result, self); + + Tensor result_tmp = at::linalg_tensorsolve(self, other, dims); + at::native::resize_output(result, result_tmp.sizes()); + result.copy_(result_tmp); + return result; +} + +namespace { +struct KronImpl final { + public: + explicit KronImpl(const Tensor& self, const Tensor& other) { + maxdim = std::max(self.dim(), other.dim()); + int64_t pad_self = maxdim - self.dim(); + int64_t pad_other = maxdim - other.dim(); + a_reshape = c10::SmallVector(2 * maxdim); + b_reshape = c10::SmallVector(2 * maxdim); + result_reshape = c10::SmallVector(maxdim); + for (const auto i : c10::irange(maxdim)) { + a_reshape[2 * i] = (i >= pad_self ? self.sizes()[i - pad_self] : 1); + a_reshape[2 * i + 1] = 1; + b_reshape[2 * i] = 1; + b_reshape[2 * i + 1] = (i >= pad_other ? other.sizes()[i - pad_other] : 1); + result_reshape[i] = a_reshape[2 * i] * b_reshape[2 * i + 1]; + } + self_view = at::_unsafe_view(self, a_reshape); + other_view = at::_unsafe_view(other, b_reshape); + } + + Tensor& kron_out(Tensor& result) const { + TORCH_INTERNAL_ASSERT(result.defined(), "Cannot call kron_out with an undefined result tensor as the out argument. Please allocate a Tensor before calling kron_out with it."); + + c10::SmallVector mul_shape(2 * maxdim); + for (const auto i : c10::irange(maxdim)) { + mul_shape[2 * i] = a_reshape[2 * i]; + mul_shape[2 * i + 1] = b_reshape[2 * i + 1]; + } + at::native::resize_output(result, result_reshape); + auto result_mul = at::_unsafe_view(result, mul_shape); + at::mul_out(result_mul, self_view, other_view); + + return result; + } + + Tensor kron() const { + return at::_unsafe_view(at::mul(self_view, other_view), result_reshape); + } + private: + int64_t maxdim; + Tensor self_view; + Tensor other_view; + c10::SmallVector result_reshape; + c10::SmallVector a_reshape; + c10::SmallVector b_reshape; +}; +} + +/* +Calculates the Kronecker product between two Tensors. +*/ +Tensor& kron_out(const Tensor& self, const Tensor& other, Tensor& result) { + return KronImpl(self, other).kron_out(result); +} + +Tensor kron(const Tensor& self, const Tensor& other) { + return KronImpl(self, other).kron(); +} + +// Weight Only Quantization Gemm +DEFINE_DISPATCH(weight_to_int4pack_stub); +DEFINE_DISPATCH(int4pack_mm_stub); +DEFINE_DISPATCH(int8pack_mm_stub); +DEFINE_DISPATCH(dyn_quant_pack_4bit_weight_stub); +DEFINE_DISPATCH(dyn_quant_matmul_4bit_stub); + +Tensor _convert_weight_to_int4pack_cpu( + const Tensor& in, + int64_t innerKTiles) { + + TORCH_CHECK(in.dim() == 2, + __func__, " : expect weight to be 2D tensor."); + TORCH_CHECK(in.dtype() == at::kInt, + __func__, " : expect weight to be kInt."); + + auto weight = in.contiguous(); + auto N = weight.size(0); + auto K = weight.size(1); + + TORCH_CHECK(N % 16 == 0, + __func__, " : expect N to be dividable by 16"); + TORCH_CHECK(K % 2 == 0, + "_convert_weight_to_int4pack: expect K to be dividable by 2"); + + auto weight_packed = at::empty({N, K / 2}, weight.options().dtype(at::kByte)); + + weight_to_int4pack_stub(kCPU, weight_packed, weight); + return weight_packed; +} + +Tensor _weight_int4pack_mm_cpu( + const Tensor& A, + const Tensor& B, + int64_t qGroupSize, + const Tensor& qScaleAndZeros) { + + auto M = A.size(0); + auto N = B.size(0); + auto K = A.size(1); + + TORCH_CHECK(A.dtype() == kBFloat16 || A.dtype() == kHalf || A.dtype() == kFloat, + __func__, " : expect A to be either 32-bit or 16-bit float tensor."); + TORCH_CHECK(A.is_contiguous(), + __func__, " : expect A to be contiguous."); + TORCH_CHECK(A.dim() == 2, + __func__, " : expect A to be 2D tensor."); + + TORCH_CHECK(B.dtype() == kByte, + __func__, " : expect B to be uint8 tensor."); + TORCH_CHECK(B.is_contiguous(), + __func__, " : expect B to be contiguous."); + TORCH_CHECK(B.size(1) == K / 2, + __func__, " : expect B.size(1) to be K/2, got ", B.size(1)); + + TORCH_CHECK(qGroupSize == 32 || qGroupSize == 64 || qGroupSize == 128 + || qGroupSize == 256, + __func__, ": expect qGroupSize to be 32, 64, 128 or 256, got ", qGroupSize); + TORCH_CHECK(K % qGroupSize == 0, + __func__, ": expect K to be divisible by qGroupSize, got K:", K, ", qGroupSize:", qGroupSize); + + TORCH_CHECK(qScaleAndZeros.dim() == 3 && qScaleAndZeros.size(1) == N + && qScaleAndZeros.size(2) == 2, + __func__, ": expect qScaleAndZeros to be 3d tensor with sizes [:, ", N, ", 2]"); + + auto C = at::empty({M, N}, A.options()); + int4pack_mm_stub(kCPU, C, A, B, qGroupSize, qScaleAndZeros); + + return C; +} + +Tensor _dyn_quant_pack_4bit_weight_cpu( + const Tensor& weights, + const Tensor& scales_zeros, + const std::optional& bias, + const int64_t block_size, + const int64_t in_features, + const int64_t out_features) { + TORCH_CHECK( + weights.dtype() == at::kByte, __func__, " : expect weight to be kByte."); + TORCH_CHECK( + block_size == in_features || + (!(block_size % 32) && !(in_features % block_size)), + __func__, + ": Group size should be multiple of 32, in_features [", + in_features, + "]. Provided ", + block_size); + Tensor packed_weights = + at::empty(weights.sizes(), weights.options().dtype(at::kByte)); + dyn_quant_pack_4bit_weight_stub( + kCPU, + packed_weights, + weights, + scales_zeros, + bias, + out_features, + in_features, + block_size); + return packed_weights; +} + +Tensor _dyn_quant_matmul_4bit_cpu( + const Tensor& inp, + const Tensor& packed_weights, + const int64_t block_size, + const int64_t in_features, + const int64_t out_features) { + auto M = inp.size(0); + TORCH_CHECK( + inp.dtype() == kFloat || (inp.dtype() == kBFloat16 && block_size == in_features), + __func__, + " : expect input to be float32 or bfloat16 tensor."); + TORCH_CHECK( + block_size == in_features || + (!(block_size % 32) && !(in_features % block_size)), + __func__, + ": Group size should be multiple of 32, in_features [", + in_features, + "]. Provided ", + block_size); + auto output = at::empty({M, out_features}, inp.options()); + dyn_quant_matmul_4bit_stub( + kCPU, + output, + inp, + packed_weights, + M, + out_features, + in_features, + block_size); + return output; +} + +Tensor _weight_int8pack_mm_cpu( + const Tensor& A, + const Tensor& B, + const Tensor& scales) { + + auto M = A.size(0); + auto N = B.size(0); + auto K = A.size(1); + + TORCH_CHECK(A.dtype() == kBFloat16 || A.dtype() == kHalf || A.dtype() == kFloat, + __func__, " : expect A to be either 32-bit or 16-bit float tensor."); + TORCH_CHECK(A.dim() == 2, + __func__, " : expect A to be 2D tensor."); + TORCH_CHECK(A.stride(1) == 1, + __func__, " : A must be contiguous on the last dimension."); + TORCH_CHECK(B.dtype() == kChar, + __func__, " : expect B to be int8 tensor."); + TORCH_CHECK(B.is_contiguous(), + __func__, " : expect B to be contiguous."); + TORCH_CHECK(B.size(1) == K, + __func__, " : expect B.size(1) == ", K); + + TORCH_CHECK(scales.dim() == 1 && scales.size(0) == N, + __func__, " : expect scales to be 1d tensor with size ", N); + + auto C = at::empty({M, N}, A.options()); + int8pack_mm_stub(kCPU, C, A, B, scales); + + return C; +} + +Tensor& _int_mm_out_cpu(const Tensor& self, const Tensor& mat2, Tensor& result) { +#ifndef STRIP_ERROR_MESSAGES + static constexpr std::string_view func_name = "int_mm_out_cpu"; +#endif + TORCH_CHECK(self.dim() == 2, func_name, ": Expected self to be of dimension 2 but got ", self.dim()); + TORCH_CHECK(mat2.dim() == 2, func_name, ": Expected mat2 to be of dimension 2 but got ", mat2.dim()); + TORCH_CHECK(self.size(1) == mat2.size(0), func_name, ": self.size(1) needs to match mat2.size(0) but got ", self.size(1), " and ", mat2.size(0)); + TORCH_CHECK(self.dtype() == at::kChar || self.dtype() == at::kByte, + func_name, ": Expected self dtype to be int8 or uint8 but got ", self.dtype()); + TORCH_CHECK(mat2.dtype() == at::kChar, func_name, ": Expected mat2 dtype to be of type int8 but got ", mat2.dtype()); + TORCH_CHECK(result.dtype() == at::kInt, func_name, ": Expected result dtype to be of type kInt but got ", result.dtype()); + TORCH_CHECK(result.size(0) == self.size(0), func_name, ": Expected result.size(0) to be ", self.size(0), " but got ", result.size(0)); + TORCH_CHECK(result.size(1) == mat2.size(1), func_name, ": Expected result.size(1) to be ", mat2.size(1), " but got ", result.size(1)); + TORCH_CHECK(result.dim() == 2, func_name, ": Expected result to be of dimension 2 but got ", result.dim()); + TORCH_CHECK(result.is_contiguous(), func_name, ": Expected result to be contiguous."); + + // Outer or inner dimension is 0 + if (result.numel() == 0 || self.size(1) == 0) { + return result.zero_(); + } + + bool dispatched = false; + if (at::globalContext().userEnabledMkldnn() && at::cpu::is_avx512_vnni_supported()) { + try { + mkldnn_matmul_i8i8i32(self, mat2, result); + dispatched = true; + } catch ([[maybe_unused]] const std::exception& e) { + TORCH_WARN(func_name, " failed, switching to BLAS gemm: ", e.what()); + } + } + if (!dispatched) { + auto b = reinterpret_cast(mat2.data_ptr()); + auto c = reinterpret_cast(result.data_ptr()); + const int64_t m = result.size(0); + const int64_t n = result.size(1); + const int64_t k = self.size(1); + const int64_t lda_0 = self.strides()[0]; + const int64_t lda_1 = self.strides()[1]; + const int64_t ldb_0 = mat2.strides()[0]; + const int64_t ldb_1 = mat2.strides()[1]; + const int64_t ldc = result.strides()[0]; + #define COMPUTE_WITH_A_TYPE(a_type) \ + auto a = reinterpret_cast(self.data_ptr()); \ + at::parallel_for(0, m * n, 1, [&](int64_t start, int64_t end) { \ + for (const auto i : c10::irange(start, end)) { \ + auto row = i / n; \ + auto col = i % n; \ + c[row * ldc + col] = 0; \ + for (const auto k : c10::irange(k)) { \ + c[row * ldc + col] = c[row * ldc + col] + \ + static_cast(a[row * lda_0 + k * lda_1]) * \ + static_cast(b[k * ldb_0 + col * ldb_1]); \ + } \ + } \ + }); + + if (self.scalar_type() == at::kByte) { + COMPUTE_WITH_A_TYPE(uint8_t); + } else { + COMPUTE_WITH_A_TYPE(int8_t); + } + } + return result; +} + +Tensor _int_mm_cpu(const Tensor& self, const Tensor& mat2) { + Tensor result = at::empty({self.size(0), mat2.size(1)}, self.options().dtype(at::kInt)); + return _int_mm_out_cpu(self, mat2, result); +} + +} // namespace native +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebra.h b/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebra.h new file mode 100644 index 0000000000000000000000000000000000000000..5ecef0d72d4790c4f297724ebe01038180ef1612 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebra.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace c10 { +class Scalar; +} + +namespace at { +struct TensorIterator; +} + +namespace at::native { + +using addr_fn = void (*)(TensorIterator &, const Scalar& beta, const Scalar& alpha); +DECLARE_DISPATCH(addr_fn, addr_stub) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebraUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebraUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..6f44b1176087fc9431934ca3d5d3ccc538e57658 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LinearAlgebraUtils.h @@ -0,0 +1,625 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +inline c10::MaybeOwned expect_resolved_conj(const Tensor& tensor) { + if (tensor.is_conj()) { + return c10::MaybeOwned::owned(tensor.resolve_conj()); + } else { + return c10::MaybeOwned::borrowed(tensor); + } +} + +inline DimVector batched_matrix_contiguous_strides( + const IntArrayRef sizes, + const bool f_contig = false) { + // f_contig chooses between the strides of a batch of Fortran (F-contiguous) + // and C-contiguous matrices + auto strides = c10::contiguous_strides(sizes); + auto dim = strides.size(); + + if (f_contig && dim >= 2) { + // Fix the strides of the last two dimensions, so that we return + // C-contiguous batches of F-contiguous matrices. + strides[dim - 1] = std::max(sizes[dim - 2], static_cast(1)); + strides[dim - 2] = 1; + } + return strides; +} + +/* + * Clones a Tensor so that the following conditions hold: + * If we think of a Tensor of having size (B, M, N), where B is any number + * of batch dimensions, then: + * - Each (M, N) matrix is in column major form + * - Let Tensor P have size (B, M, N) and Q have size (B, M', N'). + * Then when laid out in memory, the M by N matrix starting at + * P.data_ptr()[B * M * N] is of the same corresponding batch as the M' by N' + * matrix starting at Q.data_ptr()[B * M' * N']. + */ +inline Tensor cloneBatchedColumnMajor(const Tensor& src) { + // If src is already in batched column major format, then + // this will be efficient (no reordering of the data will occur) + // because the first transpose will make the tensor contiguous, + // and cloning a contiguous tensor is fast. + auto result = src.mT().clone(at::MemoryFormat::Contiguous); + result.transpose_(-2, -1); + return result; +} + +/* + * contig chooses between C-contig (true) and F-contig (false) + */ +inline c10::MaybeOwned borrow_else_clone(const bool cond, const Tensor& borrow, const Tensor& clone, const bool contig) { + return cond ? c10::MaybeOwned::borrowed(borrow) + : c10::MaybeOwned::owned(contig ? clone.clone(MemoryFormat::Contiguous) + : cloneBatchedColumnMajor(clone)); +} + +/* + * This method is designed to be a faster alternative to + * `cloneBatchedColumnMajor` with some additional features, + * namely: + * 1. It uses `copy` instead of `clone` which could be much faster. + * 2. `nrows` parameter used to create inputs with the number of rows larger + * than the original input, which is required for some LAPACK/MAGMA methods. + * 3. `desired_batch_size` is used to create copies with the batch size + * which is either the original batch size of the input, or its larger + * broadcasted shape. + */ +inline Tensor copyBatchedColumnMajor(const Tensor& src, int64_t nrows = -1, + at::OptionalIntArrayRef desired_batch_sizes = std::nullopt) { + nrows = (nrows == -1) ? src.size(-2) : nrows; + auto copy_sizes = desired_batch_sizes.has_value() + ? desired_batch_sizes.value().vec() + : IntArrayRef(src.sizes().data(), src.dim() - 2).vec(); + copy_sizes.insert(copy_sizes.end(), {nrows, src.size(-1)}); + const auto copy_strides = batched_matrix_contiguous_strides(copy_sizes, /*f-contig*/true); + auto copy = at::empty_strided(copy_sizes, copy_strides, src.options()); + copy.narrow(-2, 0, src.size(-2)).copy_(src); + return copy; +} + +/* + * Given batches of matrices with arbitrary batch dim, + * computes the number of batches. + */ +inline int64_t batchCount(const Tensor& batched_matrices) { + int64_t result = 1; + for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) { + result *= batched_matrices.size(i); + } + return result; +} + +// Computes the number of elements of a matrix in a batched matrix tensor +inline int64_t matrixStride(const Tensor& batched_matrices) { + return batched_matrices.size(-1) * batched_matrices.size(-2); +} + +// Validates input shapes for operations on batches of square matrices (inverse, cholesky, symeig, eig) +inline void checkIsMatrix(const Tensor& A, const char* const f_name, const char* const arg_name = "A") { + TORCH_CHECK(A.dim() >= 2, f_name, ": The input tensor ", arg_name, " must have at least 2 dimensions."); +} +inline void squareCheckInputs(const Tensor& self, const char* const f_name, const char* const arg_name = "A") { + checkIsMatrix(self, f_name, arg_name); + TORCH_CHECK(self.sym_size(-1) == self.sym_size(-2), + f_name, + ": ", arg_name, " must be batches of square matrices, " + "but they are ", self.sym_size(-2), " by ", self.sym_size(-1), " matrices"); +} + +inline void checkInputsSolver(const Tensor& A, + const Tensor& B, + const bool left, + const char* const f_name) { + squareCheckInputs(A, f_name, "A"); + checkIsMatrix(B, f_name, "B"); + TORCH_CHECK(left ? A.size(-2) == B.size(-2) : A.size(-1) == B.size(-1), + f_name, ": Incompatible shapes of A and B for the equation ", + left ? "AX = B" : "XA = B", + " (", A.size(-2), "x", A.size(-1), " and ", B.size(-2), "x", B.size(-1), ")"); +} + +inline bool is_row_or_column_contiguous(const Tensor& t) { + // This could be made more general, similar to how it's checked in matmul, which would allow to + // elide the copy with strides such as (6, 12, 1, 3) or (3, 1, 9), but this is quite tricky. + // We choose to be conservative for simplicity + return t.is_contiguous() || t.transpose(-2, -1).is_contiguous(); +} + +inline TransposeType to_transpose_type(const bool contig, const bool conj) { + if (conj) { + if (contig) { TORCH_INTERNAL_ASSERT(false, "Invalid transpose type"); } + else { return TransposeType::ConjTranspose; } + } else { + if (contig) { return TransposeType::NoTranspose; } + else { return TransposeType::Transpose; } + } +} + + +// This function is designed to be used with linear algebra methods that minimize +// L(ax - b) = 0, where L is generally the identity map (`solve`, for example) +// or the L2 norm (`lstsq`). +// It is expected that `a` and `b` are contiguous tensors of column-major matrices +// (so that a.view({-1, a.size(-2), a.size(-1)}) succeeds, same for `b`), +// with the following additional properties: +// +// 1. a.dim() == b.dim() +// 2. a.shape[:-2] broadcasts over b.shape[:-2] +// 3. a.size(i) <= b.size(i) for i=0,..., a.dim() - 3 (only for batch dimensions) +// +// MAGMA/LAPACK modify tensor `a` in-place, and the main goal of this method +// is to be memory efficient, which means that if there exists an index i such that +// a.shape[i] < b.shape[i], 0 <= i <= a.dim() - 3, +// then instead of materializing copies of `a` in the broadcasted shape, we keep +// a buffer copy of `a` along with flags that check whether specific batch dimension +// indices for `a` were already accessed. If they were, we copy the data from the buffer +// into `a`. The number of copies does not exceed +// prod(max(a.shape[:-2], b.shape[:-2]) - a.shape[:-2] + 1) +// and this value is attained by tensors with non-empty batch dimensions. +// +// func_t `f` is a callable that is being supplied with +// scalar_t* a_working_ptr, scalar_t* b_working_ptr, int64_t a_linear_batch_idx. +// a_working_ptr and b_working_ptr can directly be passed to LAPACK/MAGMA routines, +// and a_linear_batch_idx is an index in the 3d representation which corresponds to +// the memory a_working_ptr points to, in other words: +// a_working_ptr == a.view({-1, a.size(-2), a.size(-1)}.select(0, a_linear_batch_idx).data_ptr(); +// a_linear_batch_idx is useful to store metadata related to `a`, such as, for example, +// its rank or singular values (see linalg_lstsq). +template +void batch_iterator_with_broadcasting(const Tensor& a, const Tensor& b, const func_t& f) { + IntArrayRef a_batch_sizes(a.sizes().data(), a.dim() - 2); + IntArrayRef b_batch_sizes(b.sizes().data(), b.dim() - 2); + + auto a_linear_batch_idx = at::arange(batchCount(a)).view(a_batch_sizes); + auto b_linear_batch_idx = at::arange(batchCount(b)).view(b_batch_sizes); + + TensorIterator iter = TensorIteratorConfig() + .set_check_mem_overlap(false) + .check_all_same_dtype(false) + .resize_outputs(false) + .add_output(b_linear_batch_idx) + .add_input(a_linear_batch_idx) + .build(); + + auto m = a.size(-2); + auto n = a.size(-1); + auto a_3d = a.view({batchCount(a), m, n}); + auto b_3d = b.view({batchCount(b), b.size(-2), b.size(-1)}); + + auto a_broadcasts_over_b = (a_batch_sizes != b_batch_sizes); + Tensor a_buffer, a_was_accessed, a_buffer_3d; + std::function check_if_copy_needed_for_a + = [](int64_t /*a_curr_linear_batch_idx*/){}; + if (a_broadcasts_over_b) { + a_buffer = at::empty_strided(a.sizes(), a.strides(), a.options()) + .copy_(a); + a_was_accessed = at::zeros(batchCount(a), at::kBool); + a_buffer_3d = a_buffer.view({batchCount(a), m, n}); + check_if_copy_needed_for_a = [&](int64_t a_curr_linear_batch_idx) { + auto* a_was_accessed_flag = a_was_accessed + .select(0, a_curr_linear_batch_idx) + .data_ptr(); + if (!(*a_was_accessed_flag)) { + *a_was_accessed_flag = true; + } + else { + a_3d.select(0, a_curr_linear_batch_idx) + .copy_(a_buffer_3d.select(0, a_curr_linear_batch_idx)); + } + }; + } + + auto loop = [&](char** data, const int64_t* strides, int64_t nelems) { + auto* b_batch_idx_ptr = data[0]; + auto* a_batch_idx_ptr = data[1]; + + for ([[maybe_unused]] const auto elem : c10::irange(nelems)) { + auto b_curr_linear_batch_idx = + *reinterpret_cast(b_batch_idx_ptr); + auto a_curr_linear_batch_idx = *reinterpret_cast(a_batch_idx_ptr); + + check_if_copy_needed_for_a(a_curr_linear_batch_idx); + + auto* a_working_ptr = a_3d.select(0, a_curr_linear_batch_idx) + .data_ptr(); + auto* b_working_ptr = b_3d.select(0, b_curr_linear_batch_idx) + .data_ptr(); + f(a_working_ptr, b_working_ptr, a_curr_linear_batch_idx); + + b_batch_idx_ptr += strides[0]; + a_batch_idx_ptr += strides[1]; + } + }; + iter.serial_for_each(loop, {0, batchCount(b)}); +} + +// Returns the epsilon value for floating types except half +inline double _get_epsilon(const ScalarType& sc_type) { + switch (sc_type) { + case at::ScalarType::Float: + return static_cast(std::numeric_limits::epsilon()); + case at::ScalarType::Double: + return std::numeric_limits::epsilon(); + default: + TORCH_CHECK(false, "This function doesn't handle types other than float and double"); + } +} + +// Validates input shapes and devices +// for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve) +inline void linearSolveCheckInputs(const Tensor& self, const Tensor& A, const char* name) { + TORCH_CHECK(self.device() == A.device(), + "Expected b and A to be on the same device, but found b on ", + self.device(), " and A on ", A.device(), " instead."); + + TORCH_CHECK(self.scalar_type() == A.scalar_type(), + "Expected b and A to have the same dtype, but found b of type ", + self.scalar_type(), " and A of type ", A.scalar_type(), " instead."); + + TORCH_CHECK(A.size(-1) == A.size(-2), + "A must be batches of square matrices, " + "but they are ", A.size(-2), " by ", A.size(-1), " matrices"); + + TORCH_CHECK(A.size(-1) == self.size(-2), + "Incompatible matrix sizes for ", name, ": each A " + "matrix is ", A.size(-1), " by ", A.size(-1), + " but each b matrix is ", self.size(-2), " by ", self.size(-1)); +} + +inline void checkFloatingOrComplex(const Tensor& t, const char* const f_name, const bool allow_low_precision_dtypes=true) { + auto dtype = t.scalar_type(); + TORCH_CHECK((at::isFloatingType(dtype) || at::isComplexType(dtype)), + f_name, ": Expected a floating point or complex tensor as input. Got ", dtype); + if (!allow_low_precision_dtypes) { + TORCH_CHECK(dtype == kFloat || dtype == kDouble || dtype == kComplexFloat || dtype == kComplexDouble, + f_name, ": Low precision dtypes not supported. Got ", dtype); + } +} + + +// Checks if all the Tensors in a TensorList are of the same dimensions +inline void checkAllSameDim(TensorList tensors, int64_t dim) { + for (auto &t : tensors) { + TORCH_CHECK(t.dim() == dim, "Tensor dimension is ", t.dim(), ", expected ", dim, " instead."); + } +} + +inline std::tuple, std::vector> _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2) { + // broadcast the batch dimensions of arg1 and arg2. + IntArrayRef arg1_batch_sizes(arg1.sizes().data(), arg1.ndimension() - 2); + IntArrayRef arg2_batch_sizes(arg2.sizes().data(), arg2.ndimension() - 2); + std::vector expand_batch_portion = infer_size(arg1_batch_sizes, arg2_batch_sizes); + + std::vector arg1_expand_size({expand_batch_portion}); + arg1_expand_size.insert(arg1_expand_size.end(), { arg1.size(-2), arg1.size(-1) }); + + std::vector arg2_expand_size({expand_batch_portion}); + arg2_expand_size.insert(arg2_expand_size.end(), { arg2.size(-2), arg2.size(-1) }); + return std::make_tuple(std::move(arg1_expand_size), std::move(arg2_expand_size)); +} + +inline std::tuple _linalg_broadcast_batch_dims(const Tensor& arg1, const Tensor& arg2, const char* name) { + // If there's no name we assume we don't want to check the errors + if (name != nullptr) { + linearSolveCheckInputs(arg1, arg2, name); + } + + auto [arg1_expand_size, arg2_expand_size] = at::native::_linalg_broadcast_batch_dims(arg1, arg2); + + auto arg1_broadcasted = arg1_expand_size == arg1.sizes() ? arg1 : arg1.expand(arg1_expand_size); + auto arg2_broadcasted = arg2_expand_size == arg2.sizes() ? arg2 : arg2.expand(arg2_expand_size); + return std::make_tuple(std::move(arg1_broadcasted), std::move(arg2_broadcasted)); +} + +inline std::vector broadcast_batch_size(const Tensor& t1, const Tensor& t2, int64_t n_batch_dims) { + IntArrayRef t1_batch_sizes(t1.sizes().data(), n_batch_dims); + IntArrayRef t2_batch_sizes(t2.sizes().data(), n_batch_dims); + auto broadcasted_batch_sizes = infer_size(t1_batch_sizes, t2_batch_sizes); + return broadcasted_batch_sizes; +} + +// Return a permutation with the given axes moved to the end. +inline Tensor _move_to_end(const Tensor& self, IntArrayRef axes) { + const std::vector a = axes.vec(); + const int64_t ndim = self.ndimension(); + std::vector perm; + perm.reserve(static_cast(std::max(0, ndim))); + + for (const auto i : c10::irange(ndim)) { + auto it = std::find(a.begin(), a.end(), i); + if (it == a.end()) { + perm.push_back(i); + } + } + for (auto i : a) { + perm.push_back(i); + } + + TORCH_CHECK((int64_t)perm.size() == ndim, + "duplicate or invalid axis in 'dim' argument for tensor with ndim==", ndim); + + return self.permute(perm); +} + +// parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced) +inline std::tuple _parse_qr_mode(std::string_view mode) { + bool compute_q; + bool reduced; + if (mode == "reduced") { + compute_q = true; + reduced = true; + } else if (mode == "complete") { + compute_q = true; + reduced = false; + } else if (mode == "r") { + compute_q = false; + reduced = true; // this is actually irrelevant in this mode + } else { + TORCH_CHECK(false, "qr received unrecognized mode '", mode, + "' but expected one of 'reduced' (default), 'r', or 'complete'"); + } + return std::make_tuple(compute_q, reduced); +} + +// Function to compute sizes, strides and the extra columns for the Q matrix in the QR Decomposition +inline std::tuple _compute_geometry_for_Q( + const Tensor& input, + bool reduced) { + int64_t m = input.size(-2), n = input.size(-1); + int64_t n_columns_q; + + // We need to compute the required size of Q based on the `reduced` option + DimVector q_sizes(input.sizes()); + if (!reduced && m > n) { + q_sizes[input.dim() - 1] = m; + n_columns_q = m; + } else { + q_sizes[input.dim() - 1] = n; + n_columns_q = std::min(m, n); + } + auto q_strides = batched_matrix_contiguous_strides(q_sizes, /*f-contig*/true); + return std::make_tuple(std::move(q_sizes), std::move(q_strides), n_columns_q); +} + +inline bool svd_uses_cusolver(const Tensor& A) { + // if cusolver is available, it is used unconditionally + return A.is_cuda() + && at::globalContext().hasCuSOLVER() + && at::globalContext().linalgPreferredBackend() != at::LinalgBackend::Magma; +} + + +// Function used instead of .to so that the original strides are retained +// .to doesn't retain strides and make the output tensor contiguous +inline Tensor same_stride_to(const Tensor& original_tensor, const at::TensorOptions& options) { + auto strided_to = at::empty_strided(original_tensor.sizes(), + original_tensor.strides(), + options); + strided_to.copy_(original_tensor); + return strided_to; +} + +// Creates a dimension permutation array that can be given to `at::permute()`, which will shift +// the two specified dimensions to the end of a tensor, without changing the order of +// the other dimensions. `dim1` will be placed at the very end, and `dim0` will be +// placed just to the left of it. +// +// For instance, given a 4-D tensor, dimensions 1 and 3 can be shifted to the end by +// calling `create_dim_backshift_permutation(1, 3, 4)`. The resulting vector will +// be `vec(0, 2, 1, 3)`. +inline std::vector create_dim_backshift_permutation(int64_t dim0, int64_t dim1, int64_t ndim) { + TORCH_CHECK( + (dim0 != dim1) && (dim0 < ndim) && (dim0 >= 0) && (dim1 < ndim) && (dim1 >= 0), + "duplicate or invalid dimensions"); + std::vector permutation(ndim); + int64_t cur_permuted_dim = 0; + for (const auto dim_ind : c10::irange(ndim)) { + if ((dim_ind != dim0) && (dim_ind != dim1)) { + permutation[cur_permuted_dim++] = dim_ind; + } + } + permutation[cur_permuted_dim++] = dim0; + permutation[cur_permuted_dim] = dim1; + return permutation; +} + +// Creates a dimension permutation array that can be given to `at::permute()`, which +// will reverse a given permutation. +// The reverse permutation array is created by swapping the indices and their +// associated values from the given permutation array. +inline std::vector create_reverse_permutation(std::vector permutation) { + int64_t ndim = permutation.size(); + std::vector reverse_permutation(ndim); + for (const auto dim_ind : c10::irange(ndim)) { + reverse_permutation[permutation[dim_ind]] = dim_ind; + } + return reverse_permutation; +} + +// Compute R-work array size for MAGMA/LAPACK cgesdd/zgesdd +// See https://github.com/Reference-LAPACK/lapack/blob/122506cd8b6ce050a200920c3d4c0b153b150fd8/SRC/cgesdd.f#L186 +inline int64_t computeLRWorkDim(const char jobz, int64_t m, int64_t n) { + auto mn = std::min(m, n); + auto mx = std::max(m, n); + if (jobz == 'N') { +#ifdef __APPLE__ + // According to `vecLib.framework/Headers/clapack.h` Accelerate.framework is based on LAPACK 3.2.1 + return 7 * mn; +#else + // These setting is valid for on LAPACK 3.6+ + return 5 * mn; +#endif + } + if (mx > 10 * mn) { + return 5 * mn * mn + 5 * mn; + } + return std::max(5 * mn * mn + 5 * mn, 2 * mx * mn + 2 * mn * mn + mn); +} + +// This function checks whether the uplo argument input is valid +// Allowed strings are "u", "U", "l", "L" +inline void checkUplo(const std::string_view uplo) { + // To use std::toupper safely with plain chars (or signed chars), the argument should first be converted to unsigned char + char uplo_uppercase = static_cast(std::toupper(static_cast(uplo[0]))); + TORCH_CHECK(uplo.size() == 1 && (uplo_uppercase == 'U' || uplo_uppercase == 'L'), + "Expected UPLO argument to be 'L' or 'U', but got ", uplo); +} + +inline void checkSameDevice(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") { + TORCH_CHECK( + result.device() == input.device(), + fn_name, + ": Expected ", result_name, " and input tensors to be on the same device, but got ", + result_name, " on ", result.device(), " and input on ", input.device()); +} + +// Check the dtype of result and input tensors (for _out variants). +// Most linear algebra functions have the same dtype for input and output +// (either floating or complex type input), so we can check whether input's dtype can be casted to result's dtype. +// According to https://github.com/pytorch/pytorch/wiki/Developer-FAQ#how-does-out-work-in-pytorch +// c10::canCast is used for checking the "safe copy" dtype requirements. +inline void checkLinalgCompatibleDtype(const std::string& fn_name, Tensor result, Tensor input, const std::string& result_name = "result") { + bool can_cast = c10::canCast(input.scalar_type(), result.scalar_type()); + TORCH_CHECK( + can_cast, + fn_name, + ": Expected ", result_name, " to be safely castable from ", input.scalar_type(), " dtype, but got ", + result_name, " with dtype ", result.scalar_type()); +} + +// Alternatively, we can check whether the specific expected output type (result_type) can be safely casted to out tensor dtype (out_type) +inline void checkLinalgCompatibleDtype(const std::string& fn_name, ScalarType out_type, ScalarType result_type, const std::string& out_name = "result") { + bool can_cast = c10::canCast(result_type, out_type); + TORCH_CHECK( + can_cast, + fn_name, + ": Expected ", out_name, " to be safely castable from ", result_type, " dtype, but got ", + out_name, " with dtype ", out_type); +} + +inline void checkNotComplexTolerance(const Tensor& tol, const std::string_view f_name, const std::string_view tol_name) { + TORCH_CHECK(!at::isComplexType(tol.scalar_type()), + f_name, ": ", tol_name, " tensor of complex type is not supported. Got ", tol.scalar_type()); +} + +/* + Two types of 'other' tensors are supported when solving + a system of linear equations matmul(input, x) = other: + * 1-dimensional (1D) tensor or batch of 1D tensors (vector case) + * 2-dimensional (2D) tensor or batch of 2D tensors (matrix case). + The original torch.solve supported only the matrix case, while NumPy works for both cases. + For the batched input we need to be able to distinguish them. + Let input.shape = (batch_dimensions, m, n), then 'other' is of vector type if other.shape == (batch_dimensions, m). + This rule is compatible with NumPy, see https://github.com/numpy/numpy/blob/v1.20.0/numpy/linalg/linalg.py#L384-L389 +*/ +inline bool linalg_solve_is_vector_rhs(const Tensor& input, const Tensor& other) { + auto expected_batched_rhs_shape = SymIntArrayRef(input.sym_sizes().data(), input.dim() - 1); // input.shape[:-1] + bool vector_case = other.dim() == 1 || (input.dim() - 1 == other.dim() && other.sym_sizes().equals(expected_batched_rhs_shape)); + return vector_case; +} + +/* + Computes linear indices for a tensor with original_shape to access its elements like it was a materialized broadcast tensor. +*/ +inline Tensor get_linear_indices(int64_t numel, IntArrayRef original_shape, IntArrayRef broadcast_shape) { + TensorOptions options = at::TensorOptions().dtype(at::kLong).device(at::kCPU); + return at::arange(numel, options).view(original_shape).broadcast_to(broadcast_shape).contiguous(); +} + +class BroadcastLinearIndices { + private: + Tensor linear_indices_; + bool is_broadcasting_; + + public: + BroadcastLinearIndices( + int64_t numel, + IntArrayRef original_shape, + IntArrayRef broadcast_shape) : is_broadcasting_(!original_shape.equals(broadcast_shape)) { + // The assumption is that the broadcast_shape is a materialized broadcast + // shape of the original_shape. We need to compute the linear indices + // compatible with the original_shape to access the elements in the original + // tensor corresponding to the broadcast tensor. + if (is_broadcasting_) { + linear_indices_ = + get_linear_indices(numel, original_shape, broadcast_shape); + } + } + int64_t operator()(int64_t broadcast_linear_index) { + return is_broadcasting_ + ? linear_indices_.data_ptr()[broadcast_linear_index] + : broadcast_linear_index; + } +}; + +inline bool is_blas_compatible_column_major_order(const Tensor& input) { + IntArrayRef input_strides = input.strides(); + IntArrayRef input_sizes = input.sizes(); + auto ndim = input.dim(); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2); + if (ndim > 3) { + return input.transpose(-2, -1).is_contiguous(); + } + auto leading_dimension = input_strides[ndim - 1]; + auto rows = input_sizes[ndim - 2]; + bool batch_stride_compatible = true; + if (ndim == 3) { + auto cols = input_sizes[ndim - 1]; + batch_stride_compatible = + input_strides[ndim - 3] >= leading_dimension * cols; + } + return (input_strides[ndim - 2] == 1) && + (leading_dimension >= std::max(1, rows)) && + batch_stride_compatible; +} + +inline bool is_blas_compatible_row_major_order(const Tensor& input) { + IntArrayRef input_strides = input.strides(); + IntArrayRef input_sizes = input.sizes(); + auto ndim = input.dim(); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(ndim >= 2); + if (ndim > 3) { + return input.is_contiguous(); + } + auto leading_dimension = input_strides[ndim - 2]; + auto cols = input_sizes[ndim - 1]; + bool batch_stride_compatible = true; + if (ndim == 3) { + auto rows = input_sizes[ndim - 2]; + batch_stride_compatible = + input_strides[ndim - 3] >= leading_dimension * rows; + } + return (input_strides[ndim - 1] == 1) && + (leading_dimension >= std::max(1, cols)) && + batch_stride_compatible; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Loss.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Loss.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d1b3d0bd92be3a9e73f5b89227fe70c81cb50c9 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Loss.cpp @@ -0,0 +1,503 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +constexpr float EPSILON = 1e-12; + +namespace { + inline at::Tensor apply_loss_reduction(const at::Tensor& unreduced, int64_t reduction) { + if (reduction == at::Reduction::Mean) { + return unreduced.mean(); + } else if (reduction == at::Reduction::Sum) { + return unreduced.sum(); + } + return unreduced; + } +} + +namespace at::meta { + +TORCH_META_FUNC(smooth_l1_loss) +(const Tensor& input, const Tensor& target, const int64_t reduction, double beta) { + TORCH_CHECK(beta >= 0, "smooth_l1_loss does not support negative values for beta.") + // TODO: Reduce this extra TensorIterator construction for Reduction::Mean & Sum. + // We do another TensorIterator construction in the IMPL for the two cases. + build_borrowing_binary_op(maybe_get_output(), input, target); + if (reduction == Reduction::None) { + return; + } + + TORCH_INTERNAL_ASSERT(reduction == Reduction::Mean || reduction == Reduction::Sum); + maybe_get_output().resize_({}); +} + +TORCH_META_FUNC(mse_loss) +(const Tensor& input, const Tensor& target, const int64_t reduction) { + build_borrowing_binary_op(maybe_get_output(), input, target); + if (reduction == Reduction::None) { + return; + } + + TORCH_INTERNAL_ASSERT(reduction == Reduction::Mean || reduction == Reduction::Sum); + maybe_get_output().resize_({}); +} + +} // namespace at::meta + +namespace at::native { + +DEFINE_DISPATCH(smooth_l1_stub); +DEFINE_DISPATCH(smooth_l1_backward_stub); +DEFINE_DISPATCH(huber_stub); +DEFINE_DISPATCH(huber_backward_stub); +DEFINE_DISPATCH(mse_stub); +DEFINE_DISPATCH(mse_backward_stub); + +TORCH_IMPL_FUNC(smooth_l1_loss_out) +(const Tensor& input, const Tensor& target, int64_t reduction, double beta, const Tensor& result) { + if (reduction != Reduction::None) { + Tensor loss; + auto iter = TensorIterator::borrowing_binary_op(loss, input, target); + smooth_l1_stub(iter.device_type(), iter, beta); + if (reduction == Reduction::Mean) { + at::mean_out(const_cast(result), iter.output(), IntArrayRef{}); + } else { + at::sum_out(const_cast(result), iter.output(), IntArrayRef{}); + } + } else { + smooth_l1_stub(device_type(), *this, beta); + } +} + +TORCH_IMPL_FUNC(mse_loss_out) +(const Tensor& input, const Tensor& target, int64_t reduction, const Tensor& result) { + TORCH_CHECK(input.device() == target.device(), + "Expected all tensors to be on the same device, but found at least two devices, ", + input.device(), " and ", target.device(), "!"); + if (reduction != Reduction::None) { + Tensor loss; + auto iter = TensorIterator::borrowing_binary_op(loss, input, target); + mse_stub(iter.device_type(), iter); + if (reduction == Reduction::Mean) { + at::mean_out(const_cast(result), iter.output(), IntArrayRef{}); + } else { + at::sum_out(const_cast(result), iter.output(), IntArrayRef{}); + } + } else { + mse_stub(device_type(), *this); + } +} + +Tensor cosine_embedding_loss(const Tensor& input1, const Tensor& input2, const Tensor& target, double margin, int64_t reduction) { + auto targ_dim = target.dim(); + TORCH_CHECK( + targ_dim == 1 || targ_dim == 0, + "0D or 1D target tensor expected, multi-target not supported"); + if (targ_dim == 1) { + TORCH_CHECK( + input1.dim() == 2 && input2.dim() == 2, + "1D target tensor expects 2D input tensors, but found inputs with sizes ", + input1.sizes(), + " and ", + input2.sizes(), + "."); + } else { + TORCH_CHECK( + input1.dim() == 1 && input2.dim() == 1, + "0D target tensor expects 1D input tensors, but found inputs with sizes ", + input1.sizes(), + " and ", + input2.sizes(), + "."); + } + + auto prod_sum = (input1 * input2).sum(targ_dim); + auto mag_square1 = (input1 * input1).sum(targ_dim) + EPSILON; + auto mag_square2 = (input2 * input2).sum(targ_dim) + EPSILON; + auto denom = (mag_square1 * mag_square2).sqrt_(); + auto cos = prod_sum / denom; + + auto zeros = at::zeros_like(cos, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + auto pos = 1 - cos; + auto neg = (cos - margin).clamp_min_(0); + auto output_pos = at::where(target == 1, pos, zeros); + auto output_neg = at::where(target == -1, neg, zeros); + auto output = output_pos + output_neg; + return apply_loss_reduction(output, reduction); +} + +Tensor hinge_embedding_loss(const Tensor& self, const Tensor& target, double margin, int64_t reduction) { + auto zeros = at::zeros_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + auto margin_diff = (margin - self); + // For Composite Compliance, + // In Forward AD, if `margin_diff` is a CCT but its tangent isn't, + // using inplace clamp_min doesn't work because we end up writing + // the CCT in-place to the tangent + auto margin_clamp = (margin_diff._fw_grad(/*level*/ 0).defined() && + isTensorSubclassLike(margin_diff)) + ? margin_diff.clamp_min(0) + : margin_diff.clamp_min_(0); + auto output_margin = at::where(target != 1, margin_clamp, zeros); + auto output_self = at::where(target != -1, self, zeros); + auto output = output_margin + output_self; + return apply_loss_reduction(output, reduction); +} + +Tensor triplet_margin_loss(const Tensor& anchor, const Tensor& positive, const Tensor& negative, double margin, + double p, double eps, bool swap, int64_t reduction) { + auto a_dim = anchor.dim(); + auto p_dim = positive.dim(); + auto n_dim = negative.dim(); + TORCH_CHECK( + a_dim == p_dim && p_dim == n_dim, + "The anchor, positive, and negative tensors are expected to have " + "the same number of dimensions, but got: anchor ", a_dim, "D, " + "positive ", p_dim, "D, and negative ", n_dim, "D inputs") + + auto dist_pos = at::pairwise_distance(anchor, positive, p, eps); + auto dist_neg = at::pairwise_distance(anchor, negative, p, eps); + // The distance swap is described in the paper "Learning shallow + // convolutional feature descriptors with triplet losses" by V. Balntas, E. + // Riba et al. If True, and if the positive example is closer to the + // negative example than the anchor is, swaps the positive example and the + // anchor in the loss computation. + if (swap) { + auto dist_swap = at::pairwise_distance(positive, negative, p, eps); + dist_neg = at::min(dist_neg, dist_swap); + } + auto output = at::clamp_min(margin + dist_pos - dist_neg, 0); + return apply_loss_reduction(output, reduction); +} + +Tensor margin_ranking_loss(const Tensor& input1, const Tensor& input2, const Tensor& target, double margin, int64_t reduction) { + auto unclamped_output = (-target * (input1 - input2) + margin); + // For Composite Compliance, + // In Forward AD, if `margin_diff` is a CCT but its tangent isn't, + // using inplace clamp_min doesn't work because we end up writing + // the CCT in-place to the tangent + auto output = (unclamped_output._fw_grad(/*level*/ 0).defined() && + isTensorSubclassLike(unclamped_output)) + ? unclamped_output.clamp_min(0) + : unclamped_output.clamp_min_(0); + return apply_loss_reduction(output, reduction); +} + +Tensor kl_div(const Tensor& input, const Tensor& target, int64_t reduction, bool log_target) { + TORCH_CHECK(!input.is_complex() && !target.is_complex(), + "kl_div: Complex inputs not supported."); + TORCH_CHECK(!at::isIntegralType(input.scalar_type(), /*include_bool*/true) && + !at::isIntegralType(target.scalar_type(), /*include_bool*/true), + "kl_div: Integral inputs not supported."); + Tensor output; + if (log_target) { + output = at::exp(target) * (target - input); + } else { + output = at::xlogy(target, target) - target * input; + } + return apply_loss_reduction(output, reduction); +} + +Tensor binary_cross_entropy_cpu(const Tensor& input, const Tensor& target, const std::optional& weight_opt, int64_t reduction) { + Tensor loss = at::empty_like(input); + return at::native::binary_cross_entropy_out_cpu( + input, target, weight_opt, reduction, loss); +} + +Tensor& binary_cross_entropy_out_cpu(const Tensor& input, const Tensor& target, const std::optional& weight_opt, int64_t reduction, Tensor& loss) { + Tensor loss_squeezed = at::squeeze(loss); + + auto iter = TensorIteratorConfig() + .add_output(loss_squeezed) + .add_owned_const_input(at::squeeze(input)) + .add_owned_const_input(at::squeeze(target)) + .build(); + + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::Half, + ScalarType::BFloat16, + loss.scalar_type(), + "binary_cross_entropy", + [&] { + at::native::cpu_kernel( + iter, [](scalar_t input_val, scalar_t target_val) { + TORCH_CHECK( + (input_val >= 0) && (input_val <= 1), + "all elements of input should be between 0 and 1"); + TORCH_CHECK( + (target_val >= 0) && (target_val <= 1), + "all elements of target should be between 0 and 1"); + + // Binary cross entropy tensor is defined by the equation: + // L = -w (y ln(x) + (1-y) ln(1-x)) + return (target_val - scalar_t(1)) * + std::max(scalar_t(std::log1p(-input_val)), scalar_t(-100)) - + target_val * + std::max(scalar_t(std::log(input_val)), scalar_t(-100)); + }); + }); + + if (weight_opt.has_value() && weight_opt->defined()) { + loss.mul_(*weight_opt); + } + if (reduction != at::Reduction::None) { + Tensor loss_reduced = apply_loss_reduction(loss, reduction); + loss.resize_as_(loss_reduced).copy_(loss_reduced); + } + return loss; +} + +Tensor binary_cross_entropy_backward_cpu(const Tensor& grad, const Tensor& input, const Tensor& target, const std::optional& weight_opt, int64_t reduction) { + Tensor grad_input = at::empty_like(input); + return at::native::binary_cross_entropy_backward_out_cpu( + grad, input, target, weight_opt, reduction, grad_input); +} + +Tensor& binary_cross_entropy_backward_out_cpu(const Tensor& grad, const Tensor& input, const Tensor& target, const std::optional& weight_opt, int64_t reduction, Tensor& grad_input) { + Tensor grad_input_squeezed = at::squeeze(grad_input); + + auto iter = TensorIteratorConfig() + .add_output(grad_input_squeezed) + .add_owned_const_input(at::squeeze(grad)) + .add_owned_const_input(at::squeeze(input)) + .add_owned_const_input(at::squeeze(target)) + .build(); + + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::Half, + ScalarType::BFloat16, + grad_input.scalar_type(), + "binary_cross_entropy_backward", + [&] { + at::native::cpu_kernel( + iter, + [](scalar_t grad_val, scalar_t input_val, scalar_t target_val) { + // The gradient is the partial derivative of BCELoss + // with respect to x + // d(L)/d(x) = -w (y - x) / (x - x^2) + return grad_val * (input_val - target_val) / + (scalar_t(std::max( + (scalar_t(1) - input_val) * input_val, + scalar_t(EPSILON)))); + }); + }); + + if (weight_opt.has_value() && weight_opt->defined()) { + grad_input.mul_(*weight_opt); + } + if (reduction == at::Reduction::Mean) { + grad_input.div_(input.numel()); + } + return grad_input; +} + +Tensor binary_cross_entropy_with_logits(const Tensor& input, const Tensor& target, const std::optional& weight_opt, const std::optional& pos_weight_opt, int64_t reduction) { + auto log_sigmoid_input = at::log_sigmoid(input); + if (pos_weight_opt.has_value() && pos_weight_opt->defined()) { + // pos_weight need to be broadcasted, thus mul(target) is not inplace. + auto log_weight = (*pos_weight_opt- 1).mul(target).add_(1); + log_sigmoid_input.mul_(log_weight); + } + + Tensor loss = (1 - target).mul_(input).sub_(log_sigmoid_input); + + if (weight_opt.has_value() && weight_opt->defined()) { + loss.mul_(*weight_opt); + } + + return apply_loss_reduction(loss, reduction); +} + +Tensor poisson_nll_loss(const Tensor& input, const Tensor& target, const bool log_input, const bool full, const double eps, const int64_t reduction) +{ + Tensor loss; + if (log_input) { + loss = at::exp(input) - target * input; + } else { + loss = input - target * at::log(input + eps); + } + + if (full) { + auto stirling_term = target * at::log(target) - target + 0.5 * at::log(2 * c10::pi * target); + loss += stirling_term.masked_fill(target <= 1, 0); + } + + return apply_loss_reduction(loss, reduction); +} + +Tensor& soft_margin_loss_backward_out(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction, Tensor& grad_input) { + auto norm = reduction == Reduction::Mean ? 1. / input.numel() : 1.; + auto z = at::exp(-target * input); + // inplace version of: grad_input = -norm * target * z / (1. + z) * grad_output; + at::mul_out(grad_input, target, z).mul_(-norm); + z.add_(1); + grad_input.div_(z).mul_(grad_output); + return grad_input; +} + +Tensor soft_margin_loss_backward(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction) { + auto grad_input = at::empty({0}, input.options()); + at::soft_margin_loss_backward_out(grad_input, grad_output, input, target, reduction); + return grad_input; +} + +Tensor& soft_margin_loss_out(const Tensor& input, + const Tensor& target, + int64_t reduction, + Tensor& output) { + // compute inplace variant of: output = at::log1p(at::exp(-input * target)); + at::neg_out(output, input).mul_(target).exp_().log1p_(); + if (reduction != Reduction::None) { + auto tmp = apply_loss_reduction(output, reduction); + output.resize_({}); + output.copy_(tmp); + } + return output; +} + +Tensor soft_margin_loss( + const Tensor& input, + const Tensor& target, + int64_t reduction) { + auto output = at::empty({0}, input.options()); + at::soft_margin_loss_out(output, input, target, reduction); + return output; +} + +Tensor& smooth_l1_loss_backward_out(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction, double beta, Tensor& grad_input) { + auto norm = reduction == Reduction::Mean ? 1. / input.numel() : 1.; + auto iter = at::TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(target) + .add_const_input(grad_output) + .promote_inputs_to_common_dtype(true) + .cast_common_dtype_to_outputs(true) + .enforce_safe_casting_to_output(true) + .build(); + smooth_l1_backward_stub(iter.device_type(), iter, norm, beta); + return grad_input; +} + +Tensor smooth_l1_loss_backward(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction, double beta) { + auto grad_input = at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + return at::smooth_l1_loss_backward_out(grad_input, grad_output, input, target, reduction, beta); +} + +Tensor huber_loss(const Tensor& input, const Tensor& target, int64_t reduction, double delta) { + TORCH_CHECK(delta > 0, "huber_loss does not support non-positive values for delta.") + Tensor loss = at::empty_like(input); + auto iter = TensorIterator::borrowing_binary_op(loss, input, target); + huber_stub(iter.device_type(), iter, delta); + return apply_loss_reduction(loss, reduction); +} + +Tensor& huber_loss_out(const Tensor& input, const Tensor& target, int64_t reduction, double delta, Tensor& result) { + TORCH_CHECK(delta > 0, "huber_loss does not support non-positive values for delta.") + auto iter = TensorIterator::borrowing_binary_op(result, input, target); + huber_stub(iter.device_type(), iter, delta); + if (reduction != Reduction::None) { + auto reduced = apply_loss_reduction(result, reduction); + result.resize_({}); + result.copy_(reduced); + } + return result; +} + +Tensor huber_loss_backward(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction, double delta) { + auto grad_input = at::zeros_like(input, MemoryFormat::Contiguous); + return at::huber_loss_backward_out(grad_input, grad_output, input, target, reduction, delta); +} + +Tensor& huber_loss_backward_out(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction, double delta, Tensor& grad_input) { + auto norm = (reduction == Reduction::Mean) ? (1. / input.numel()) : 1.; + auto iter = at::TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(target) + .add_const_input(grad_output) + .build(); + huber_backward_stub(iter.device_type(), iter, norm, delta); + return grad_input; +} + +Tensor mse_loss_backward(const Tensor& grad_output, const Tensor& input, const Tensor& target, int64_t reduction) { + Tensor grad_input = at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + return at::mse_loss_backward_out(grad_input, grad_output, input, target, reduction); +} + +Tensor& mse_loss_backward_out(const Tensor& grad_output, + const Tensor& input, const Tensor& target, int64_t reduction, Tensor& grad_input) { + auto norm = reduction == Reduction::Mean ? 2. / input.numel() : 2.; + auto iter = at::TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(target) + .add_const_input(grad_output) + .promote_inputs_to_common_dtype(true) + .cast_common_dtype_to_outputs(true) + .enforce_safe_casting_to_output(true) + .build(); + mse_backward_stub(iter.device_type(), iter, norm); + return grad_input; +} + +Tensor l1_loss(const Tensor& input, const Tensor& target, int64_t reduction) { + return apply_loss_reduction((input - target).abs(), reduction); +} +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LossCTC.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LossCTC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bae1e1d5a0b64d13e5917dcc4f59ffa26a805063 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LossCTC.cpp @@ -0,0 +1,595 @@ +// Copyright (c) 2018 MathInf GmbH, Thomas Viehmann +// Licensed under the BSD-3-Clause license +// This is the CPU implementation of the Connectionist Temporal Loss. +// We mostly follow Graves. +// 1. Graves et al.: http://www.cs.toronto.edu/~graves/icml_2006.pdf +// We use the equations from above link, but note that [1] has 1-based indexing and we (of course) use 0-based. +// Graves et al. call the probabilities y, we use log_probs (also calling them inputs) +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include + +namespace at::native { + +namespace { + +// this ad-hoc converts from targets (l in [1]) to augmented targets (l' in [1]) note that no bound-checking is done +template +inline int64_t get_target_prime(target_t* target, int64_t offset, int64_t stride, int64_t idx, int64_t BLANK) { + if (idx % 2 == 0) { + return BLANK; + } else { + return target[offset + stride * (idx / 2)]; + } +} + +template +std::tuple> ctc_loss_allocate_outputs(const Tensor& log_probs, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK) { + // log_probs: input_len x batch_size x num_labels + // targets [int64]: batch_size x target_length OR sum(target_lengths) + + CheckedFrom c = "ctc_loss_allocate_outputs"; + auto log_probs_arg = TensorArg(log_probs, "log_probs", 1); + auto targets_arg = TensorArg(targets, "targets", 2); + checkScalarType(c, targets_arg, target_scalar_type); + checkDim(c, log_probs_arg, 3); + checkDimRange(c, targets_arg, 1, 3); + + int64_t batch_size = log_probs.size(1); + int64_t num_labels = log_probs.size(2); + TORCH_CHECK((0 <= BLANK) && (BLANK < num_labels), "blank must be in label range"); + TORCH_CHECK((int64_t) input_lengths.size() == batch_size, "input_lengths must be of size batch_size"); + TORCH_CHECK((int64_t) target_lengths.size() == batch_size, "target_lengths must be of size batch_size"); + + size_t tg_target_stride = 0; + int64_t max_target_length = 0; + std::vector tg_batch_offsets(batch_size); + if (targets.dim() == 1) { // concatenated targets + int64_t pos = 0; + for (const auto i : c10::irange(batch_size)) { + TORCH_CHECK(target_lengths[i] >= 0, + "Expected target_lengths to have value at least ", 0, ", but got value ", target_lengths[i], + " (while checking arguments for ", c, ")"); + tg_batch_offsets[i] = pos; + pos += target_lengths[i]; + if (max_target_length < target_lengths[i]) + max_target_length = target_lengths[i]; + } + tg_target_stride = targets.stride(0); + checkSize(c, targets_arg, 0, pos); + } + else { // batch x max_target_length + // dim is 2 + int64_t tg_batch_stride = targets.stride(0); + for (const auto i : c10::irange(batch_size)) { + TORCH_CHECK(target_lengths[i] >= 0, + "Expected target_lengths to have value at least ", 0, ", but got value ", target_lengths[i], + " (while checking arguments for ", c, ")"); + tg_batch_offsets[i] = i * tg_batch_stride; + if (max_target_length < target_lengths[i]) + max_target_length = target_lengths[i]; + } + tg_target_stride = targets.stride(1); + checkSize(c, targets_arg, 0, batch_size); + TORCH_CHECK(targets.size(1) >= max_target_length, + "Expected tensor to have size at least ", max_target_length, " at dimension 1, but got size ", targets.size(1), " for ", targets_arg, + " (while checking arguments for ", c, ")"); + } + int64_t max_input_length = log_probs.size(0); + for (const auto b : c10::irange(batch_size)) { + TORCH_CHECK(input_lengths[b] >= 0, + "Expected input_lengths to have value at least ", 0, ", but got value ", input_lengths[b], + " (while checking arguments for ", c, ")"); + TORCH_CHECK(input_lengths[b] <= max_input_length, + "Expected input_lengths to have value at most ", max_input_length, ", but got value ", input_lengths[b], + " (while checking arguments for ", c, ")"); + } + + Tensor log_alpha = at::empty({batch_size, log_probs.size(0), 2*max_target_length+1}, log_probs.options()); + Tensor neg_log_likelihood = at::empty({batch_size}, log_probs.options()); + + return std::make_tuple( + std::move(neg_log_likelihood), + std::move(log_alpha), + tg_target_stride, + std::move(tg_batch_offsets)); +} + +// This kernel is a relatively straightforward implementation of the alpha calculation in the forward backward algorithm (section 4.1). +// A (minor) twist is that we are using log-calculations to enhance numerical stability (log_probs and log_alpha). +// The function returns the loss and the alphas, the alphas are kept for the backward step. The wrapper (ctc_loss below) hides +// the alphas from the user by only returning the loss. +template +std::tuple ctc_loss_cpu_template(const Tensor& log_probs, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK) { + TORCH_CHECK(log_probs.numel() > 0, "log_probs tensor must not be empty"); + // log_probs: input_len x batch_size x num_labels + // targets [int64]: batch_size x target_length OR sum(target_lengths) + constexpr scalar_t neginf = -std::numeric_limits::infinity(); + using target_t = typename std::conditional_t; + + Tensor neg_log_likelihood, log_alpha; + size_t tg_target_stride; + std::vector tg_batch_offsets; + + if (targets.scalar_type() == kLong) { + std::tie(neg_log_likelihood, log_alpha,tg_target_stride, tg_batch_offsets) = + ctc_loss_allocate_outputs( + log_probs, targets, input_lengths, target_lengths, BLANK); + } else { + std::tie(neg_log_likelihood, log_alpha, tg_target_stride, tg_batch_offsets) = + ctc_loss_allocate_outputs( + log_probs, targets, input_lengths, target_lengths, BLANK); + } + + int64_t batch_size = log_probs.size(1); + auto lpp = log_probs.permute({1,0,2}); + auto log_probs_a_global = lpp.accessor(); + auto log_alpha_a_global = log_alpha.accessor(); + auto targets_data = targets.const_data_ptr(); + auto neg_log_likelihood_a = neg_log_likelihood.accessor(); + + // alpha calculation for the first row, the three equations for alpha_1 above eq (6) + // first the default + log_alpha.narrow(1, 0, 1).fill_(neginf); + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + int64_t input_length = input_lengths[b]; + int64_t target_length = target_lengths[b]; + auto log_probs_a = log_probs_a_global[b]; + auto log_alpha_a = log_alpha_a_global[b]; + int64_t tg_batch_offset = tg_batch_offsets[b]; + + if (input_length == 0) { + scalar_t log_likelihood = target_length == 0 ? 0 : neginf; + neg_log_likelihood_a[b] = -log_likelihood; + continue; + } + + // the first two items of alpha_t above eq (6) + log_alpha_a[0][0] = log_probs_a[0][BLANK]; + if (target_length > 0) + log_alpha_a[0][1] = log_probs_a[0][get_target_prime(targets_data, tg_batch_offset, tg_target_stride, 1, BLANK)]; + + // now the loop over the inputs + for (const auto t : c10::irange(1, input_length)) { + for (const auto s : c10::irange(2*target_length+1)) { + auto current_target_prime = get_target_prime(targets_data, tg_batch_offset, tg_target_stride, s, BLANK); + // this loop over s could be parallel/vectorized, too, but the required items are one index apart + // alternatively, one might consider moving s to the outer loop to cache current_target_prime more (but then it needs to be descending) + // for the cuda implementation, that gave a speed boost. + // This is eq (6) and (7), la1,2,3 are the three summands. We keep track of the maximum for the logsumexp calculation. + + scalar_t la1 = log_alpha_a[t-1][s]; + scalar_t lamax = la1; + scalar_t la2, la3; + if (s > 0) { + la2 = log_alpha_a[t-1][s-1]; + if (la2 > lamax) + lamax = la2; + } else { + la2 = neginf; + } + if ((s > 1) && (get_target_prime(targets_data, tg_batch_offset, tg_target_stride, s-2, BLANK) != + current_target_prime)) { + la3 = log_alpha_a[t-1][s-2]; + if (la3 > lamax) + lamax = la3; + } else { + la3 = neginf; + } + if (lamax == neginf) // cannot do neginf-neginf + lamax = 0; + // this is the assignment of eq (6) + log_alpha_a[t][s] = std::log(std::exp(la1-lamax)+std::exp(la2-lamax)+std::exp(la3-lamax))+lamax + log_probs_a[t][current_target_prime]; + } + } + // the likelihood is the sum of the last two alphas, eq (8), the loss is the negative log likelihood + if (target_length == 0) { + // if the target is empty then there is no preceding BLANK state and hence there is no path to merge + neg_log_likelihood_a[b] = -log_alpha_a[input_length-1][0]; + } else { + scalar_t l1 = log_alpha_a[input_length-1][target_length*2]; + scalar_t l2 = log_alpha_a[input_length-1][target_length*2-1]; + scalar_t m = std::max(l1, l2); + m = ((m == neginf) ? 0 : m); + scalar_t log_likelihood = std::log(std::exp(l1-m)+std::exp(l2-m))+m; + neg_log_likelihood_a[b] = -log_likelihood; + } + } + }); + + return std::make_tuple(std::move(neg_log_likelihood), std::move(log_alpha)); +} + +// This is the backward. It consists of two phases: +// a) computing the beta analogous to the alphas in the forward (backward half of the forward-backward algorithm) (eq (10) and (11)) +// b) collecting the per-activation characters for all s and wrapping the gradient (eq (16), the collection is the sum) +template +Tensor ctc_loss_backward_cpu_template(const Tensor& grad_out, const Tensor& log_probs, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, + const Tensor& neg_log_likelihood, const Tensor& log_alpha, int64_t BLANK, bool zero_infinity) { + constexpr scalar_t neginf = -std::numeric_limits::infinity(); + using target_t = typename std::conditional_t; + int64_t max_input_length = log_probs.size(0); + int64_t batch_size = log_probs.size(1); + int64_t num_labels = log_probs.size(2); + Tensor grad = at::full_like(log_probs, neginf, LEGACY_CONTIGUOUS_MEMORY_FORMAT); // at this point, this is log of empty sum + + // The admin bits. We don't do much checking and assume that the forward did. + int64_t tg_target_stride = 0; + int64_t max_target_length = 0; + std::vector tg_batch_offsets(batch_size); + + if (targets.dim() == 1) { // concatenated targets + int64_t pos = 0; + max_target_length = 0; + for (const auto i : c10::irange(batch_size)) { + tg_batch_offsets[i] = pos; + pos += target_lengths[i]; + if (max_target_length < target_lengths[i]) + max_target_length = target_lengths[i]; + } + tg_target_stride = targets.stride(0); + } + else { // batch x max_target_length + // dim is 2 + int64_t tg_batch_stride = targets.stride(0); + for (const auto i : c10::irange(batch_size)) { + tg_batch_offsets[i] = i * tg_batch_stride; + } + tg_target_stride = targets.stride(1); + max_target_length = targets.size(1); + } + + Tensor log_beta = at::empty_like(log_alpha, LEGACY_CONTIGUOUS_MEMORY_FORMAT); // could be optimized to use only 2 rows + auto lpp = log_probs.permute({1,0,2}); + auto log_probs_a_global = lpp.accessor(); + auto log_alpha_a_global = log_alpha.accessor(); + auto log_beta_a_global = log_beta.accessor(); + auto gp = grad.permute({1,0,2}); + auto grad_a_global = gp.accessor(); + auto targets_data = targets.const_data_ptr(); + auto grad_out_a = grad_out.accessor(); + + auto create_fill_iterator = [](const Tensor& tensor, IntArrayRef squash_dims) { + return TensorIteratorConfig() + .set_check_mem_overlap(false) // Fill is idempotent, so overlap is okay + .check_all_same_dtype(false) + .add_output(tensor) + .resize_outputs(false) + .declare_static_shape(tensor.sizes(), squash_dims) + .build(); + }; + const auto fill_iter = create_fill_iterator(grad, /*squash_dims=*/1); + const auto fill_1d_iter = create_fill_iterator(grad, /*squash_dims=*/{0, 1}); + const auto fill_log_beta_1d_iter = create_fill_iterator(log_beta, /*squash_dims=*/{0, 1}); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + TensorIterator fill_iter_local(fill_iter); + TensorIterator fill_1d_iter_local(fill_1d_iter); + TensorIterator fill_log_beta_1d_iter_local(fill_log_beta_1d_iter); + + for (const auto b : c10::irange(start, end)) { + scalar_t nll = neg_log_likelihood.accessor()[b]; + auto grad_a = grad_a_global[b]; + if (zero_infinity && nll == std::numeric_limits::infinity()) { + // grad_batch.zero_(); + fill_iter_local.unsafe_replace_operand(0, grad_a.data()); + fill_stub(kCPU, fill_iter_local, 0); + continue; + } + + auto log_probs_a = log_probs_a_global[b]; + auto log_alpha_a = log_alpha_a_global[b]; + auto log_beta_a = log_beta_a_global[b]; + int64_t input_length = input_lengths[b]; + int64_t target_length = target_lengths[b]; + int64_t tg_batch_offset = tg_batch_offsets[b]; + + // the initialization of beta before eq (10) + // here we do the fill for each batch item separately, as the input lengths will differ, so the t in which + // we start varies + if (input_length > 0) { + // log_beta.select(0, b).select(1, input_length-1).fill_(neginf); + fill_log_beta_1d_iter_local.unsafe_replace_operand( + 0, log_beta_a[input_length - 1].data()); + fill_stub(kCPU, fill_log_beta_1d_iter_local, neginf); + + log_beta_a[input_length-1][2*target_length] = log_probs_a[input_length-1][BLANK]; + grad_a[input_length-1][BLANK] = log_alpha_a[input_length-1][2*target_length] + log_beta_a[input_length-1][2*target_length]; + + if (target_length > 0) { + auto current_target_prime = get_target_prime(targets_data, tg_batch_offset, tg_target_stride, 2*target_length-1, BLANK); + log_beta_a[input_length-1][2*target_length-1] = log_probs_a[input_length-1][current_target_prime]; + + // the first two are a blank and a non-blank, so we know they are different and we don't need to do log+ + grad_a[input_length-1][current_target_prime] = log_alpha_a[input_length-1][2*target_length-1] + log_beta_a[input_length-1][2*target_length-1]; + } + } + + // now loop applying eq (10) / (11) + for (int64_t t=input_length-2; t>=0; t--) { + // this loop over s could be parallel/vectorized and doesn't really need to be descending... + // alternatively, one might consider moving s to the outer loop to cache current_target_prime more (but then it needs to be descending) + // for the cuda implementation, that gave a speed boost. + for (int64_t s=2*target_length; s>=0; s--) { + scalar_t lb1 = log_beta_a[t+1][s]; + scalar_t lbmax = lb1; + scalar_t lb2, lb3; + auto current_target_prime = get_target_prime(targets_data, tg_batch_offset, tg_target_stride, s, BLANK); + if (s < 2*target_length) { + lb2 = log_beta_a[t+1][s+1]; + if (lb2 > lbmax) + lbmax = lb2; + } else { + lb2 = neginf; + } + if ((s < 2*target_length-1) && (get_target_prime(targets_data, tg_batch_offset, tg_target_stride, s+2, BLANK) != + current_target_prime)) { + lb3 = log_beta_a[t+1][s+2]; + if (lb3 > lbmax) + lbmax = lb3; + } else { + lb3 = neginf; + } + if (lbmax == neginf) + lbmax = 0; + + log_beta_a[t][s] = std::log(std::exp(lb1-lbmax)+std::exp(lb2-lbmax)+std::exp(lb3-lbmax))+lbmax + log_probs_a[t][current_target_prime]; + // one might check whether one can vectorize this better when done after the t-loop... + // now that we have beta, we fill in the sum of alpha*beta in eq (16) + // in contrast to the cuda implementation, we only parallelize over the batch, so we don't have a concurrency + // issue (several s can map to the same target character) + // collected[b, t, target'[s]] "log+=" log_alpha[t, s]+log_beta[t, s] + scalar_t log_alpha_beta = log_alpha_a[t][s] + log_beta_a[t][s]; + scalar_t &lcab = grad_a[t][current_target_prime]; + if (lcab == neginf) { + lcab = log_alpha_beta; + } else { + scalar_t max = std::max(lcab, log_alpha_beta); + lcab = std::log(std::exp(lcab-max)+std::exp(log_alpha_beta-max))+max; + } + } + } + + // now grad has the sum of eq (16) + // now we wrap up the calculation by adding in the remaining items of eq (16) + // this could be a great target for further vectorization. + // grad is the output gradient, nll is the loss. Note that the likelihood -nll is the Z of eq (16) + scalar_t gr = grad_out_a[b]; + for (const auto t : c10::irange(input_length)) { // or go for the full thing? + for (const auto c : c10::irange(num_labels)) { + scalar_t& res = grad_a[t][c]; + scalar_t lp = log_probs_a[t][c]; + res = (std::exp(lp)-std::exp(res + nll - lp)) * gr; + } + } + + // zero the remainder + for (auto l : c10::irange(input_length, max_input_length)) { + // grad_batch.select(0, l).zero_(); + fill_1d_iter_local.unsafe_replace_operand(0, grad_a[l].data()); + fill_stub(kCPU, fill_1d_iter_local, 0); + } + } + }); + return grad; +} + +} // namespace + +std::tuple ctc_loss_meta(const Tensor& log_probs, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity) { + (void)zero_infinity; // only used for backwards + return AT_DISPATCH_FLOATING_TYPES( + log_probs.scalar_type(), "ctc_loss_meta", [&] { + Tensor neg_log_likelihood, log_alpha; + if (targets.scalar_type() == kLong) { + std::tie(neg_log_likelihood, log_alpha, std::ignore, std::ignore) = ctc_loss_allocate_outputs( + log_probs, targets, input_lengths, target_lengths, BLANK); + } else { + std::tie(neg_log_likelihood, log_alpha, std::ignore, std::ignore) = ctc_loss_allocate_outputs( + log_probs, targets, input_lengths, target_lengths, BLANK); + } + return std::make_tuple(std::move(neg_log_likelihood), std::move(log_alpha)); + }); +} + +std::tuple ctc_loss_cpu(const Tensor& log_probs, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK, bool zero_infinity) { + (void)zero_infinity; // only used for backwards + return AT_DISPATCH_FLOATING_TYPES(log_probs.scalar_type(), "ctc_loss_cpu", [&] { + if (targets.scalar_type() == kLong) { + return ctc_loss_cpu_template(log_probs, targets, input_lengths, target_lengths, BLANK); + } else { + return ctc_loss_cpu_template(log_probs, targets, input_lengths, target_lengths, BLANK); + } + }); +} + + +std::tuple ctc_loss_tensor(const Tensor& log_probs, const Tensor& targets, const Tensor& input_lengths, const Tensor& target_lengths, int64_t BLANK, bool zero_infinity) { + TORCH_CHECK(isIntegralType(input_lengths.scalar_type(), /*includeBool=*/false), "input_lengths must be integral"); + TORCH_CHECK(isIntegralType(target_lengths.scalar_type(), /*includeBool=*/false), "target_lengths must be integral"); + + Tensor ilc = input_lengths.to(Device(at::kCPU), at::kLong).contiguous(); + Tensor tlc = target_lengths.to(Device(at::kCPU), at::kLong).contiguous(); + IntArrayRef il(ilc.const_data_ptr(), ilc.numel()); + IntArrayRef tl(tlc.const_data_ptr(), tlc.numel()); + + return at::_ctc_loss(log_probs, targets, il, tl, BLANK, zero_infinity); +} + +Tensor ctc_loss_backward_cpu(const Tensor& grad, const Tensor& log_probs, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, + const Tensor& neg_log_likelihood, const Tensor& log_alpha, int64_t BLANK, bool zero_infinity) { + return AT_DISPATCH_FLOATING_TYPES(log_probs.scalar_type(), "ctc_loss_backward_cpu", [&] { + if (targets.scalar_type() == kLong) { + return ctc_loss_backward_cpu_template(grad, log_probs, targets, input_lengths, target_lengths, neg_log_likelihood, log_alpha, BLANK, zero_infinity); + } else { + return ctc_loss_backward_cpu_template(grad, log_probs, targets, input_lengths, target_lengths, neg_log_likelihood, log_alpha, BLANK, zero_infinity); + } + }); +} + +Tensor ctc_loss_backward_tensor( + const Tensor& grad, + const Tensor& log_probs, + const Tensor& targets, + const Tensor& input_lengths, + const Tensor& target_lengths, + const Tensor& neg_log_likelihood, + const Tensor& log_alpha, + int64_t BLANK, + bool zero_infinity) { + TORCH_CHECK( + isIntegralType(input_lengths.scalar_type(), /*includeBool=*/false), + "input_lengths must be integral"); + TORCH_CHECK(isIntegralType(target_lengths.scalar_type(), /*includeBool=*/false), "target_lengths must be integral"); + + Tensor ilc = input_lengths.to(Device(at::kCPU), at::kLong).contiguous(); + Tensor tlc = target_lengths.to(Device(at::kCPU), at::kLong).contiguous(); + IntArrayRef il(ilc.const_data_ptr(), ilc.numel()); + IntArrayRef tl(tlc.const_data_ptr(), tlc.numel()); + return at::_ctc_loss_backward(grad, log_probs, targets, il, tl, neg_log_likelihood, log_alpha, BLANK, zero_infinity); +} + +namespace { + +Tensor get_clamped_target_length( + IntArrayRef target_lengths, + const TensorOptions& options) { + return at::tensor(target_lengths, options).clamp_min(1); +} + +Tensor get_clamped_target_length( + const Tensor & target_lengths, + const TensorOptions& options) { + return target_lengths.clamp_min(1); +} + +// this wrapper function dispatches to the native and cudnn/miopen implementations and hides the alpha/grad from the user (by just returning the loss) +// the gradient is implemented for _cudnn_ctc_loss, miopen_ctc_loss (just in derivatives.yaml) and _ctc_loss and this function has automatic gradients +// it also handles the reduction if desired +template +Tensor ctc_loss_impl(const Tensor& log_probs_, const Tensor& targets, LengthsType input_lengths, LengthsType target_lengths, int64_t BLANK, int64_t reduction, bool zero_infinity) { + auto is_batched = log_probs_.dim() == 3; + Tensor log_probs = is_batched ? log_probs_ : log_probs_.unsqueeze(1); + + Tensor res; + + // cuDNN CTC Loss (returns false on non-CUDA builds) + bool use_cudnn = + (log_probs.device().type() == at::kCUDA) && + at::_use_cudnn_ctc_loss( + log_probs, targets, input_lengths, target_lengths, BLANK); + + // MIOpen CTC Loss (returns false on non-ROCm builds) + bool use_miopen = false; + Tensor targets_cpu; + if (log_probs.device().type() == at::kCUDA) { + targets_cpu = targets.device().type() == at::kCPU + ? targets.to(at::kInt) + : targets.to(Device(at::kCPU), at::kInt); + use_miopen = at::_use_miopen_ctc_loss(log_probs, targets_cpu, input_lengths, target_lengths, BLANK); + } + + if (use_cudnn) { + // non-deterministic ctc loss on cudnn disabled due to inconsistent results + // see: https://github.com/pytorch/pytorch/issues/21680 + res = std::get<0>(at::_cudnn_ctc_loss(log_probs, targets, input_lengths, target_lengths, BLANK, /*deterministic=*/true, zero_infinity)); + } else if (use_miopen) { + // MIOpen CTC Loss only supports deterministic algorithm + res = std::get<0>(at::miopen_ctc_loss(log_probs, targets_cpu, input_lengths, target_lengths, BLANK, /*deterministic=*/true, zero_infinity)); + } else { + // if the targets are on CPU (which you need for cuDNN/MIOpen), move them to + // GPU as a service for the user + res = std::get<0>(at::_ctc_loss( + log_probs, + targets.to(log_probs.device(), kLong), + input_lengths, + target_lengths, + BLANK, + zero_infinity)); + if (zero_infinity) { + res = at::where(res == Scalar(std::numeric_limits::infinity()), at::zeros({}, res.options()), res); + } + } + if (reduction == at::Reduction::Mean) { + auto target_lengths_t = get_clamped_target_length(target_lengths, res.options()); + return (res / target_lengths_t).mean(); + } else if (reduction == at::Reduction::Sum) { + return res.sum(); + } + return is_batched ? std::move(res) : res.squeeze(0); +} + +} // namespace + +Tensor ctc_loss(const Tensor& log_probs_, const Tensor& targets, IntArrayRef input_lengths, IntArrayRef target_lengths, int64_t BLANK, int64_t reduction, bool zero_infinity) { + return ctc_loss_impl(log_probs_, targets, input_lengths, target_lengths, BLANK, reduction, zero_infinity); +} + +// Convenience function accepting Tensors +Tensor ctc_loss(const Tensor& log_probs, const Tensor& targets, const Tensor& input_lengths, const Tensor& target_lengths, int64_t BLANK, int64_t reduction, bool zero_infinity) { + // we don't want to convert to IntArrayRef if we can dispatch to cuDNN/MIOpen (this allows graph-capturable ctc_loss) + // cuDNN CTC Loss (returns false on non-CUDA builds) + bool use_cudnn = + (log_probs.device().type() == at::kCUDA) && + at::_use_cudnn_ctc_loss( + log_probs, targets, input_lengths, target_lengths, BLANK); + // MIOpen CTC Loss (returns false on non-ROCm builds) + bool use_miopen = false; + if (log_probs.device().type() == at::kCUDA) { + Tensor targets_check = targets.device().type() == at::kCPU + ? targets.to(at::kInt) + : targets.to(Device(at::kCPU), at::kInt); + use_miopen = at::_use_miopen_ctc_loss( + log_probs, targets_check, input_lengths, target_lengths, BLANK); + } + bool use_accelerated = use_cudnn || use_miopen; + if (at::areAnyTensorSubclassLike( + {log_probs, targets, input_lengths, target_lengths}) || use_accelerated) { + // Composite Compliant path for TensorSubclasses + return ctc_loss_impl(log_probs, targets, input_lengths, target_lengths, BLANK, reduction, zero_infinity); + } + // Fast path (which accesses data_ptr) and less operator dispatches for + // regular tensors + TORCH_CHECK(isIntegralType(input_lengths.scalar_type(), /*includeBool=*/false), "input_lengths must be integral"); + TORCH_CHECK(isIntegralType(target_lengths.scalar_type(), /*includeBool=*/false), "target_lengths must be integral"); + + Tensor ilc = input_lengths.to(Device(at::kCPU), at::kLong).contiguous(); + Tensor tlc = target_lengths.to(Device(at::kCPU), at::kLong).contiguous(); + IntArrayRef il(ilc.const_data_ptr(), ilc.numel()); + IntArrayRef tl(tlc.const_data_ptr(), tlc.numel()); + return at::native::ctc_loss(log_probs, targets, il, tl, BLANK, reduction, zero_infinity); +} + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LossMulti.h b/western_ai/usa/pytorch/aten/src/ATen/native/LossMulti.h new file mode 100644 index 0000000000000000000000000000000000000000..6a5549f33ecdd8116cd8643c5201739408212c66 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LossMulti.h @@ -0,0 +1,71 @@ +#pragma once +#include +#include +#include +#include + +namespace at::native { + inline void multilabel_margin_loss_shape_check( + int64_t& nframe, + int64_t& dim, + const int64_t& ndims, + const Tensor& input, + const Tensor& target) { + TORCH_CHECK( + (ndims == 2 && input.size(1) != 0) || (ndims == 1 && input.size(0) != 0) || ndims == 0, + "Expected non-empty vector or matrix with optional 0-dim batch size, but got: ", + input.sizes()); + + if (ndims <= 1) { + nframe = 1; + dim = ndims == 0 ? 1 : input.size(0); + TORCH_CHECK( + target.dim() <= 1 && target.numel() == dim, + "inconsistent target size: ", target.sizes(), " for input of size: ", + input.sizes()); + } else { + nframe = input.size(0); + dim = input.size(1); + TORCH_CHECK( + target.dim() == 2 && target.size(0) == nframe && + target.size(1) == dim, + "inconsistent target size: ", target.sizes(), " for input of size: ", + input.sizes()); + } + } + + inline void multi_margin_loss_shape_check( + int64_t& nframe, + int64_t& dim, + const int64_t& ndims, + const Tensor& input, + const Tensor& target, + const std::optional& weight) { + TORCH_CHECK( + (ndims == 2 && input.size(1) != 0) || (ndims == 1 && input.size(0) != 0) || ndims == 0, + "Expected non-empty vector or matrix with optional 0-dim batch size, but got: ", + input.sizes()); + + if (ndims <= 1) { + nframe = 1; + dim = ndims == 0 ? 1 : input.size(0); + } else { + nframe = input.size(0); + dim = input.size(1); + } + + TORCH_CHECK( + target.dim() <= 1 && target.numel() == nframe, + "multi_margin_loss: target tensor should be 1-D with size equal to " + "the number of input samples (batch size). Expected target size [", + nframe, "], but got ", target.sizes(), + ". Input has shape ", input.sizes(), "."); + if (weight && weight->defined()) { + TORCH_CHECK( + weight->dim() <= 1 && weight->numel() == dim, + "inconsistent weight size, expected ", dim, " but got ", + weight->sizes()); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LossMultiLabelMargin.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LossMultiLabelMargin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddcd2a948bc652de777dbf852896a12f92c46649 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LossMultiLabelMargin.cpp @@ -0,0 +1,329 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +template +inline scalar_t multilabel_margin_loss_forward_inner_sum_cpu( + const scalar_t* input_data, + const int64_t* target_data, + scalar_t* is_target_data, + int64_t dim) { + using accscalar_t = at::acc_type; + accscalar_t sum = 0; + for (const auto ddt : c10::irange(dim)) { + int64_t target_idx = target_data[ddt]; + if (target_idx < 0) { + break; + } + is_target_data[target_idx] = 1; + } + for (const auto dt : c10::irange(dim)) { + int64_t target_idx = target_data[dt]; + if (target_idx < 0) { + break; + } + + scalar_t input_target = input_data[target_idx]; + for (const auto d : c10::irange(dim)) { + if (!is_target_data[d]) { + scalar_t z = 1 - input_target + input_data[d]; + if (z > 0) { + sum += z; + } + } + } + } + + return sum; +} + +template +void multilabel_margin_loss_forward_out_frame( + const Tensor& input_contiguous, + const Tensor& target_contiguous, + Tensor& output, + Tensor& is_target, + int64_t reduction, + int64_t nframe, + int64_t dim) { + using accscalar_t = at::acc_type; + const scalar_t* input_data = input_contiguous.const_data_ptr(); + const int64_t* target_data = target_contiguous.const_data_ptr(); + scalar_t* is_target_data = is_target.data_ptr(); + + if (reduction != Reduction::None || output.dim() == 0) { + scalar_t* output_data = output.data_ptr(); + + accscalar_t sum = 0; + + for ([[maybe_unused]] const auto t : c10::irange(nframe)) { + sum += multilabel_margin_loss_forward_inner_sum_cpu( + input_data, target_data, is_target_data, dim); + + input_data += dim; + target_data += dim; + is_target_data += dim; + } + + sum /= dim; + if (reduction == Reduction::Mean) { + sum /= nframe; + } + + *output_data = sum; // write scalar output value + } else { + auto output_acc = output.accessor(); + + for (const auto t : c10::irange(nframe)) { + scalar_t sum = multilabel_margin_loss_forward_inner_sum_cpu( + input_data, target_data, is_target_data, dim); + + sum /= dim; + output_acc[t] = sum; + + input_data += dim; + target_data += dim; + is_target_data += dim; + } + } +} + +void multilabel_margin_loss_forward_out_cpu_template( + const Tensor& input, + const Tensor& target, + Tensor& output, + Tensor& is_target, + int64_t reduction) { +#ifndef STRIP_ERROR_MESSAGES + auto target_arg = TensorArg(target, "target", 2); +#endif + int64_t nframe = 0, dim = 0; + const int64_t ndims = input.dim(); + multilabel_margin_loss_shape_check(nframe, dim, ndims, input, target); + + // special case target.dim() <= 1: produce scalar output for scalar inputs + // even if reduction == Reduction::None + if (reduction != Reduction::None || target.dim() <= 1) { + output.resize_({}); + } else { + output.resize_({nframe}); + } + + is_target.resize_as_(target); + TORCH_CHECK(is_target.is_contiguous(), "is_target must be contiguous"); + is_target.zero_(); + + if (input.numel() == 0) { + return; + } + + TORCH_CHECK( + target.min().item() >= -1, target_arg, " is out of range"); + TORCH_CHECK( + target.max().item() < dim, target_arg, " is out of range"); + + auto input_contiguous = input.contiguous(); + auto target_contiguous = target.contiguous(); + + AT_DISPATCH_FLOATING_TYPES( + input.scalar_type(), "multilabel_margin_loss_forward_out_frame", [&] { + multilabel_margin_loss_forward_out_frame( + input_contiguous, target_contiguous, output, is_target, reduction, nframe, dim); + }); +} + +template +void multilabel_margin_loss_backward_out_frame( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input_contiguous, + const Tensor& target_contiguous, + int64_t reduction, + const Tensor& is_target_contiguous, + int64_t nframe, + int64_t dim) { +#ifndef STRIP_ERROR_MESSAGES + auto is_target_arg = TensorArg(is_target_contiguous, "is_target", 5); +#endif + + TORCH_CHECK( + is_target_contiguous.min().item() >= 0, is_target_arg, " is out of range"); + TORCH_CHECK( + is_target_contiguous.max().item() <= 1, is_target_arg, " is out of range"); + + const scalar_t* input_data = input_contiguous.const_data_ptr(); + const int64_t* target_data = target_contiguous.const_data_ptr(); + const scalar_t* is_target_data = is_target_contiguous.const_data_ptr(); + scalar_t g = static_cast( + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + reduction == Reduction::Mean ? 1. / (nframe * dim) : 1. / dim); + + scalar_t* grad_input_row_data = grad_input.mutable_data_ptr(); + for ([[maybe_unused]] const auto t : c10::irange(nframe)) { + for (const auto dt : c10::irange(dim)) { + int64_t target_idx = target_data[dt]; + if (target_idx < 0) { + break; + } + + scalar_t input_target = input_data[target_idx]; + for (const auto d : c10::irange(dim)) { + if (!is_target_data[d]) { + scalar_t z = 1 - input_target + input_data[d]; + if (z > 0) { + grad_input_row_data[target_idx] -= g; + grad_input_row_data[d] += g; + } + } + } + } + input_data += dim; + target_data += dim; + is_target_data += dim; + grad_input_row_data += dim; + } + + scalar_t* grad_input_data = grad_input.mutable_data_ptr(); + if (reduction != Reduction::None || grad_output.dim() == 0) { + assert( + reduction != Reduction::None || grad_output.dim() > 0 || nframe == 1); + const auto d = *grad_output.const_data_ptr(); + for (int64_t t = 0; t < nframe * dim; t++) { + grad_input_data[t] *= d; + } + } else { + check_dim_size(grad_output, 1, 0, nframe); + auto grad_output_acc = grad_output.accessor(); + for (const auto t : c10::irange(nframe)) { + for (const auto d : c10::irange(dim)) { + grad_input_data[t * dim + d] *= grad_output_acc[t]; + } + } + } +} + +void multilabel_margin_loss_backward_out_cpu_template( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + int64_t reduction, + const Tensor& is_target) { + int64_t nframe = 0, dim = 0; + CheckedFrom c = "multilabel_margin_loss_backward_cpu_template"; + auto target_arg = TensorArg(target, "target", 3); + auto is_target_arg = TensorArg(is_target, "is_target", 5); + const int64_t ndims = input.dim(); + + multilabel_margin_loss_shape_check(nframe, dim, ndims, input, target); + checkSameSize(c, target_arg, is_target_arg); + + grad_input.resize_as_(input); + if (grad_input.numel() == 0) { + return; + } + + TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous"); + grad_input.zero_(); + + TORCH_CHECK( + target.min().item() >= -1, target_arg, " is out of range"); + TORCH_CHECK( + target.max().item() < dim, target_arg, " is out of range"); + + auto input_contiguous = input.contiguous(); + auto target_contiguous = target.contiguous(); + auto is_target_contiguous = is_target.contiguous(); + + AT_DISPATCH_FLOATING_TYPES( + input.scalar_type(), "multilabel_margin_loss_backward_out_frame", [&] { + multilabel_margin_loss_backward_out_frame( + grad_input, + grad_output, + input_contiguous, + target_contiguous, + reduction, + is_target_contiguous, + nframe, + dim); + }); +} + +} // namespace + +std::tuple multilabel_margin_loss_forward_out_cpu(const Tensor& self, + const Tensor& target, + int64_t reduction, + Tensor& output, + Tensor& is_target) { + multilabel_margin_loss_forward_out_cpu_template( + self, target, output, is_target, reduction); + return std::tuple(output, is_target); +} + +std::tuple multilabel_margin_loss_forward_cpu( + const Tensor& self, + const Tensor& target, + int64_t reduction) { + auto output = at::empty({0}, self.options()); + auto is_target = at::empty({0}, self.options()); + at::native::multilabel_margin_loss_forward_out_cpu( + self, target, reduction, output, is_target); + return std::make_tuple(std::move(output), std::move(is_target)); +} + +Tensor& multilabel_margin_loss_backward_cpu_out(const Tensor& grad_output, + const Tensor& self, + const Tensor& target, + int64_t reduction, + const Tensor& is_target, + Tensor& grad_input) { + multilabel_margin_loss_backward_out_cpu_template( + grad_input, grad_output, self, target, reduction, is_target); + return grad_input; +} + +Tensor multilabel_margin_loss_backward_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& target, + int64_t reduction, + const Tensor& is_target) { + auto grad_input = at::zeros_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + at::native::multilabel_margin_loss_backward_cpu_out( + grad_output, self, target, reduction, is_target, grad_input); + return grad_input; +} + +Tensor & multilabel_margin_loss_out(const Tensor & self, const Tensor & target, int64_t reduction, Tensor & output) { + Tensor is_target = at::empty({0}, self.options()); + return std::get<0>(at::multilabel_margin_loss_forward_out(output, is_target, self, target, reduction)); +} + +Tensor multilabel_margin_loss(const Tensor & self, const Tensor & target, int64_t reduction) { + return std::get<0>(at::multilabel_margin_loss_forward(self, target, reduction)); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LossMultiMargin.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LossMultiMargin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f61fc07fd28a3d89fab238b1851b9cc2bfb2f5d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LossMultiMargin.cpp @@ -0,0 +1,334 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +template +inline scalar_t multi_margin_inner_sum_cpu( + const scalar_t* input_data, + const scalar_t* weight_data, + const int p, + const scalar_t margin, + const int64_t dim, + const int64_t target_idx) { + const scalar_t input_target = input_data[target_idx]; + scalar_t sum = 0; + for (const auto d : c10::irange(dim)) { + if (d == target_idx) { + continue; + } + + const scalar_t z = margin - input_target + input_data[d]; + if (z > 0) { + scalar_t h = (p == 1) ? z : z * z; + if (weight_data != nullptr) { + h *= weight_data[target_idx]; + } + sum += h; + } + } + + sum /= dim; + return sum; +} + +inline int64_t target_index_checked( + const int64_t* target_data, + const int64_t index, + const int64_t dim) { + const int64_t idx = target_data[index]; + TORCH_CHECK(idx >= 0 && idx < dim, "target out of range"); + return idx; +} + +template +inline void multi_margin_loss_cpu_kernel( + Tensor& output, + const scalar_t* input_data, + const int64_t* target_data, + const int p, + scalar_t margin, + const scalar_t* weight_data, + const int64_t nframe, + const int64_t dim, + const int64_t reduction) { + using accscalar_t = at::acc_type; + + // dim() != 0 check is for 1d input which produces a scalar output (that + // cannot be handled by TensorAccessor) + if (reduction == Reduction::None && output.dim() > 0) { + auto output_acc = output.accessor(); + for (const auto t : c10::irange(nframe)) { + const auto idx = target_index_checked(target_data, t, dim); + auto sum = multi_margin_inner_sum_cpu( + input_data, weight_data, p, margin, dim, idx); + output_acc[t] = sum; + input_data += dim; + } + } else { + accscalar_t sum = 0; + auto output_acc = output.data_ptr(); + for (const auto t : c10::irange(nframe)) { + const auto idx = target_index_checked(target_data, t, dim); + sum += multi_margin_inner_sum_cpu( + input_data, weight_data, p, margin, dim, idx); + input_data += dim; + } + if (reduction == Reduction::Mean) { + sum /= nframe; + } + output_acc[0] = sum; + } +} + +void multi_margin_loss_out_cpu_template( + Tensor& output, + const Tensor& input, + const Tensor& target, + int p, + const Scalar& margin, + const std::optional& weight, + int64_t reduction) { + int64_t nframe = 0, dim = 0; + const auto ndims = input.dim(); + + TORCH_CHECK(p == 1 || p == 2, "only p == 1 and p == 2 supported"); + + multi_margin_loss_shape_check(nframe, dim, ndims, input, target, weight); + + // produce a scalar output for 1d input + if (reduction == Reduction::None && target.dim() > 0) { + output.resize_({nframe}); + } else { + output.resize_({}); + } + if (input.numel() == 0) { + return; + } + + auto input_contiguous = input.contiguous(); + auto target_contiguous = target.contiguous(); + Tensor weight_contiguous; + if (weight && weight->defined()) { + weight_contiguous = weight->contiguous(); + } + + AT_DISPATCH_FLOATING_TYPES( + input.scalar_type(), "multi_margin_loss_cpu_kernel", [&] { + auto input_data = input_contiguous.const_data_ptr(); + auto target_data = target_contiguous.const_data_ptr(); + auto weight_data = + weight_contiguous.defined() ? weight_contiguous.const_data_ptr() : nullptr; + multi_margin_loss_cpu_kernel( + output, + input_data, + target_data, + p, + margin.to(), + weight_data, + nframe, + dim, + reduction); + }); +} + +template +void multi_margin_loss_backward_cpu_kernel( + scalar_t* grad_input_data, + const Tensor& grad_output, + const scalar_t* input_data, + const int64_t* target_data, + int p, + scalar_t margin, + scalar_t g, + const scalar_t* weight_data, + int64_t nframe, + int64_t dim, + int64_t reduction) { + scalar_t* grad_input_row_data = grad_input_data; + for (const auto t : c10::irange(nframe)) { + int64_t target_idx = target_index_checked(target_data, t, dim); + scalar_t input_target = input_data[target_idx]; + scalar_t grad_input_target = 0; + for (const auto d : c10::irange(dim)) { + scalar_t z = margin - input_target + input_data[d]; + if (d == target_idx) { + continue; + } + + if (z > 0) { + scalar_t h = (p == 1) ? g : 2 * g * z; + if (weight_data != nullptr) { + h *= weight_data[target_idx]; + } + grad_input_target -= h; + grad_input_row_data[d] = h; + } else { + grad_input_row_data[d] = 0; + } + } + grad_input_row_data[target_idx] = grad_input_target; + + input_data += dim; + grad_input_row_data += dim; + } + + if (reduction != Reduction::None || grad_output.dim() == 0) { + assert( + reduction != Reduction::None || grad_output.dim() > 0 || + nframe == 1); // check 1d scalar fallback-case + const auto d = *grad_output.const_data_ptr(); + for (int64_t t = 0; t < nframe * dim; t++) { + grad_input_data[t] *= d; + } + } else { + auto grad_output_acc = grad_output.accessor(); + for (const auto t : c10::irange(nframe)) { + for (const auto d : c10::irange(dim)) { + grad_input_data[t * dim + d] *= grad_output_acc[t]; + } + } + } +} + +void multi_margin_loss_backward_out_cpu_template( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + int p, + const Scalar& margin, + const Tensor& weight, + int64_t reduction) { + int64_t nframe = 0, dim = 0; + const auto ndims = input.dim(); + + TORCH_CHECK(p == 1 || p == 2, "only p == 1 and p == 2 supported"); + + multi_margin_loss_shape_check(nframe, dim, ndims, input, target, weight); + grad_input.resize_as_(input); + TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous"); + + if (input.numel() == 0) { + return; + } + + auto input_contiguous = input.contiguous(); + auto target_contiguous = target.contiguous(); + auto weight_contiguous = weight.contiguous(); + AT_DISPATCH_FLOATING_TYPES( + input.scalar_type(), "multi_margin_loss_backward_cpu_kernel", [&] { + auto grad_input_data = grad_input.mutable_data_ptr(); + auto input_data = input_contiguous.const_data_ptr(); + auto target_data = target_contiguous.const_data_ptr(); + auto weight_data = weight_contiguous.defined() + ? weight_contiguous.const_data_ptr() + : nullptr; + scalar_t g = reduction == Reduction::Mean + ? static_cast(1. / (nframe * dim)) + : static_cast(1. / dim); + multi_margin_loss_backward_cpu_kernel( + grad_input_data, + grad_output, + input_data, + target_data, + p, + margin.to(), + g, + weight_data, + nframe, + dim, + reduction); + }); +} + +} // namespace + +Tensor multi_margin_loss_cpu( + const Tensor& input, + const Tensor& target, + const Scalar& p, + const Scalar& margin, + const std::optional& weight, + int64_t reduction) { + auto output = at::empty({0}, input.options()); + multi_margin_loss_out_cpu_template( + output, input, target, p.toInt(), margin, weight, reduction); + return output; +} + +Tensor& multi_margin_loss_cpu_out(const Tensor& input, + const Tensor& target, + const Scalar& p, + const Scalar& margin, + const std::optional& weight, + int64_t reduction, + Tensor& output) { + multi_margin_loss_out_cpu_template( + output, input, target, p.toInt(), margin, weight, reduction); + return output; +} + +Tensor multi_margin_loss_cpu_backward( + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + const Scalar& p, + const Scalar& margin, const std::optional& weight_opt, + int64_t reduction) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + + auto grad_input = at::empty({0}, input.options()); + multi_margin_loss_backward_out_cpu_template( + grad_input, + grad_output, + input, + target, + p.toInt(), + margin, + weight, + reduction); + return grad_input; +} + +Tensor& multi_margin_loss_cpu_backward_out(const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + const Scalar& p, + const Scalar& margin, const std::optional& weight_opt, + int64_t reduction, + Tensor& grad_input) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + + multi_margin_loss_backward_out_cpu_template( + grad_input, + grad_output, + input, + target, + p.toInt(), + margin, + weight, + reduction); + return grad_input; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LossNLL.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LossNLL.cpp new file mode 100644 index 0000000000000000000000000000000000000000..604769c519f4d17f795cfb13800dffe6dfc33c5e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LossNLL.cpp @@ -0,0 +1,756 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include + +#include + +namespace at::meta { +TORCH_META_FUNC(nll_loss_forward) +(const Tensor& self, + const Tensor& target, + const OptionalTensorRef weight_opt, + int64_t reduction, + int64_t ignore_index) { + const Tensor& weight = weight_opt.getTensorRef(); + + TORCH_CHECK( + self.dim() > 0 && self.dim() <= 2, "input tensor should be 1D or 2D"); + TORCH_CHECK( + target.dim() <= 1, + "0D or 1D target tensor expected, multi-target not supported"); + TORCH_CHECK( + target.scalar_type() == kLong || target.scalar_type() == kByte, + "expected target dtype to be Long or Byte, but got ", + target.scalar_type()); + if (self.dim() == 1 && target.dim() == 1) { + TORCH_CHECK_VALUE( + target.size(0) == 1, + "For 1D input, 1D target must have size 1, but got target size: ", + target.size(0)); + } + TORCH_CHECK( + self.dim() == 1 || (self.size(0) == target.size(0)), + "size mismatch (got input: ", + self.sizes(), + ", target: ", + target.sizes(), + ")") + + const auto n_classes = self.size(-1); + + TORCH_CHECK( + !weight.defined() || (weight.dim() == 1 && weight.numel() == n_classes), + "weight tensor should be defined either for all ", + n_classes, + " classes or no classes" + " but got weight tensor of shape: ", + weight.sizes()); + + const auto n_dims = self.dim(); + const auto batch_size = self.size(0); + + if (reduction == Reduction::None && n_dims == 2) { + set_output_raw_strided(0, {batch_size}, {}, self.options()); + } else { + // produce scalar output when reducing or input is 1d + set_output_raw_strided(0, {}, {}, self.options()); + } + + set_output_raw_strided(1, {}, {}, self.options()); +} + +TORCH_META_FUNC(nll_loss_backward) +(const Tensor& grad_output, + const Tensor& self, + const Tensor& target, + OptionalTensorRef weight_opt, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight) { + TORCH_CHECK( + self.dim() > 0 && self.dim() <= 2, "input tensor should be 1D or 2D"); + TORCH_CHECK( + target.dim() <= 1, + "0D or 1D target tensor expected, multi-target not supported"); + + auto no_batch_dim = self.dim() == 1 && target.dim() == 0; + TORCH_CHECK( + no_batch_dim || (self.size(0) == target.size(0)), + "size mismatch (got input: ", + self.sizes(), + ", target: ", + target.sizes(), + ")") + TORCH_CHECK( + total_weight.numel() == 1, + "expected total_weight to be a single element tensor, got: ", + total_weight.sizes(), + " (", + total_weight.numel(), + " elements)"); + + const auto& weight = weight_opt.getTensorRef(); + + TORCH_CHECK( + !weight.defined() || weight.numel() == self.size(-1), + "weight tensor should be defined either for all or no classes"); + + const auto n_dims = self.dim(); + + if (reduction == Reduction::None && n_dims == 2) { + const auto batch_size = self.size(0); + check_dim_size(grad_output, 1, 0, batch_size); + } else { + TORCH_CHECK( + grad_output.dim() <= 1 && grad_output.numel() == 1, + "Expected a single element grad_output tensor, but got: ", + grad_output.sizes()); + } + + set_output_raw_strided(0, self.sizes(), {}, self.options().memory_format(LEGACY_CONTIGUOUS_MEMORY_FORMAT)); +} +} // namespace at::meta + +namespace at::native { + +namespace { + +// Returns a contiguous tensor if the source tensor +// is defined. Otherwise returns the undefined +// source tensor unmodified. +inline Tensor optional_contiguous(const Tensor& source) { + return source.defined() ? source.contiguous() : source; +} + +// Returns the address of the first element of a tensor +// or nullptr if the tensor is undefined. +template +inline scalar_t* optional_data(const Tensor& source) { + if constexpr (std::is_const_v) { + return source.defined() ? source.const_data_ptr() : nullptr; + } else { + return source.defined() ? source.data_ptr() : nullptr; + } +} + +template +void nll_loss_out_frame( + const Tensor& output, + const Tensor& total_weight, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index) { + const auto n_dims = input.dim(); + const auto n_classes = input.size(-1); + + scalar_t* total_weight_data = total_weight.data_ptr(); + *total_weight_data = 0; + + auto weight_contiguous = optional_contiguous(weight); + const scalar_t* weight_data = optional_data(weight_contiguous); + + if (reduction == Reduction::None && n_dims == 2) { + const auto batch_size = input.size(0); + at::native::resize_output(output, {batch_size}); + + auto input_acc = input.accessor(); + auto target_acc = target.accessor(); + auto output_acc = output.accessor(); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + const auto cur_target = target_acc[i]; + + if (cur_target == ignore_index) { + output_acc[i] = 0; + continue; + } + + TORCH_CHECK_INDEX( + cur_target >= 0 && cur_target < n_classes, + "Target ", + cur_target, + " is out of bounds."); + + scalar_t cur_weight = weight_data != nullptr ? weight_data[cur_target] + : static_cast(1); + output_acc[i] = -input_acc[i][cur_target] * cur_weight; + } + }); + + return; + } + + // produce scalar outputs for the reduction case + at::native::resize_output(output, {}); + + if (target.numel() == 0) { + // Here target (and input) have zero elements + // Mean reduction on empty tensors produces NaN. See the discussion in + // https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162 + if (reduction == Reduction::Mean) { + output.fill_(std::numeric_limits::quiet_NaN()); + } else { + output.zero_(); + } + total_weight.zero_(); + return; + } + + auto input_contiguous = input.contiguous(); + auto target_contiguous = target.contiguous(); + + const scalar_t* input_data = input_contiguous.const_data_ptr(); + const target_t* target_data = target_contiguous.const_data_ptr(); + + const int64_t ndim = input.dim(); + const int64_t batch_size = ndim == 1 ? 1 : input.size(0); + + constexpr int64_t cascade_sum_num_levels = 8; + const int64_t level_power = + std::max(static_cast(4), utils::CeilLog2(batch_size) / cascade_sum_num_levels); + const int64_t level_step = (1 << level_power); + const int64_t level_mask = level_step - 1; + + int64_t num_ignored = 0; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + scalar_t weight_partial_sums[cascade_sum_num_levels] = {0}; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + scalar_t loss_partial_sums[cascade_sum_num_levels] = {0}; + for (const auto b : c10::irange(batch_size)) { + const int64_t cur_target = target_data[b]; + if (cur_target == ignore_index) { + ++num_ignored; + continue; + } + + TORCH_CHECK_INDEX( + cur_target >= 0 && cur_target < n_classes, + "Target ", + cur_target, + " is out of bounds."); + + const auto data = input_data[b * n_classes + cur_target]; + if (weight_data) { + const scalar_t weight_val = weight_data[cur_target]; + loss_partial_sums[0] -= data * weight_val; + weight_partial_sums[0] += weight_val; + } else { + loss_partial_sums[0] -= data; + } + + for (int64_t j = 0; j + 1 < cascade_sum_num_levels; ++j) { + const auto mask = (level_mask << (j * level_power)); + if (C10_LIKELY((b & mask) != 0)) { + break; + } + + weight_partial_sums[j + 1] += weight_partial_sums[j]; + loss_partial_sums[j + 1] += loss_partial_sums[j]; + + weight_partial_sums[j] = 0; + loss_partial_sums[j] = 0; + } + } + + const scalar_t total_weight_val = !weight_data ? + static_cast(batch_size - num_ignored) : + std::accumulate(std::begin(weight_partial_sums), + std::end(weight_partial_sums), + scalar_t{0}); + + scalar_t output_val = std::accumulate(std::begin(loss_partial_sums), + std::end(loss_partial_sums), + scalar_t{0}); + + if (reduction == Reduction::Mean) { + output_val /= total_weight_val; + } + + // write result to output tensors + *output.data_ptr() = output_val; + *total_weight_data = total_weight_val; +} + +void nll_loss_forward_out_cpu_template( + const Tensor& output, + const Tensor& total_weight, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index) { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, + ScalarType::Half, + input.scalar_type(), + "nll_loss_out_frame", + [&] { + if (target.scalar_type() == kByte) { + nll_loss_out_frame( + output, + total_weight, + input, + target, + weight, + reduction, + ignore_index); + } else { + // assumed to be int64 + nll_loss_out_frame( + output, + total_weight, + input, + target, + weight, + reduction, + ignore_index); + } + }); +} + +template +void nll_loss_backward_out_frame( + const Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight) { + const auto n_dims = input.dim(); + const auto n_classes = input.size(-1); + + auto target_ = target; + if (target.dim() == 0) { + target_ = target.unsqueeze(0); + } + auto target_acc = target_.accessor(); + + auto weight_contiguous = optional_contiguous(weight); + const scalar_t* weight_data = optional_data(weight_contiguous); + + if (reduction == Reduction::None && n_dims == 2) { + const auto batch_size = input.size(0); + auto grad_input_acc = grad_input.accessor(); + auto grad_output_acc = grad_output.accessor(); + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + auto cur_target = target_acc[i]; + if (cur_target == ignore_index) { + continue; + } + const scalar_t w = + weight_data ? weight_data[cur_target] : static_cast(1); + grad_input_acc[i][cur_target] = -w * grad_output_acc[i]; + } + }); + return; + } + + const scalar_t total_weight_value = *total_weight.const_data_ptr(); + + const scalar_t grad_output_value = *grad_output.const_data_ptr(); + + if (input.dim() == 1) { + auto grad_input_acc = grad_input.accessor(); + + const auto t = target_acc[0]; + if (t != ignore_index) { + TORCH_CHECK_INDEX(t >= 0 && t < n_classes, "Target ", t, " is out of bounds."); + const auto grad = -(reduction == Reduction::Mean ? grad_output_value / total_weight_value + : grad_output_value); + grad_input_acc[t] = weight_data != nullptr ? weight_data[t] * grad + : grad; + } + } else if (input.dim() == 2) { + auto grad_input_acc = grad_input.accessor(); + const auto grad = -(reduction == Reduction::Mean ? grad_output_value / total_weight_value + : grad_output_value); + + const auto batch_size = input.size(0); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + const auto t = target_acc[i]; + if (t != ignore_index) { + TORCH_CHECK_INDEX(t >= 0 && t < n_classes, "Target ", t, " is out of bounds."); + grad_input_acc[i][t] = weight_data != nullptr ? weight_data[t] * grad + : grad; + } + } + }); + } +} + +void nll_loss_backward_out_cpu_template( + const Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight) { + grad_input.zero_(); + + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, + ScalarType::Half, + input.scalar_type(), + "nll_loss_backward_out_frame", + [&] { + if (target.scalar_type() == kByte) { + nll_loss_backward_out_frame( + grad_input, + grad_output, + input, + target, + weight, + reduction, + ignore_index, + total_weight); + } else { + // assumed to be uint64 + nll_loss_backward_out_frame( + grad_input, + grad_output, + input, + target, + weight, + reduction, + ignore_index, + total_weight); + } + }); +} + +} // namespace + +TORCH_IMPL_FUNC(nll_loss_forward_out_cpu) +(const Tensor& self, + const Tensor& target, + const OptionalTensorRef weight_opt, + int64_t reduction, + int64_t ignore_index, + const Tensor& output, + const Tensor& total_weight) { + const Tensor& weight = weight_opt.getTensorRef(); + nll_loss_forward_out_cpu_template( + output, total_weight, self, target, weight, reduction, ignore_index); +} + +TORCH_IMPL_FUNC(nll_loss_backward_out_cpu) +(const Tensor& grad_output, + const Tensor& self, + const Tensor& target, + OptionalTensorRef weight_opt, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight, + const Tensor& grad_input +) { + const Tensor& weight = weight_opt.getTensorRef(); + nll_loss_backward_out_cpu_template( + grad_input, + grad_output, + self, + target, + weight, + reduction, + ignore_index, + total_weight); +} + +static Tensor cross_entropy_loss_prob_target( + const Tensor& self, + const Tensor& target_, + const Tensor& weight, + int64_t reduction, + double label_smoothing) { + const auto class_dim = self.dim() == 1 ? 0 : 1; + const auto n_classes = self.sym_size(class_dim); + TORCH_CHECK( + !weight.defined() || (weight.dim() == 1 && weight.sym_numel() == n_classes), + "cross_entropy: weight tensor should be defined either for all ", + n_classes, + " classes or no classes" + " but got weight tensor of shape: ", + weight.sym_sizes()); + + auto input = at::log_softmax(self, class_dim, self.scalar_type()); + Tensor target; + + if (label_smoothing > 0.0) { + TORCH_CHECK(label_smoothing <= 1.0, "label_smoothing must be between 0.0 and 1.0. Got: ", label_smoothing); + target = target_ * (1 - label_smoothing) + label_smoothing / n_classes; + } else { + target = target_; + } + + if (weight.defined()) { + // Expand weight to the correct number of dims for broadcasting with input / target + Tensor weight_ = weight; + if (input.dim() > 1) { + auto weight_broadcast_shape = SmallBuffer(input.dim()); + std::fill(weight_broadcast_shape.begin(), weight_broadcast_shape.end(), 1); + weight_broadcast_shape[1] = weight.size(0); + weight_ = weight.view(weight_broadcast_shape); + } + + switch (reduction) { + case Reduction::Mean: + if (input.sym_numel()==0){ + return -(input * target * weight_).sum().fill_(std::numeric_limits::quiet_NaN()); + } else { + return -(input * target * weight_).sum() / (input.sym_numel() / n_classes); + } + case Reduction::Sum: + return -(input * target * weight_).sum(); + case Reduction::None: + return -(input * target * weight_).sum(class_dim); + default: + TORCH_CHECK(false, "Invalid reduction type encountered in cross_entropy: ", reduction); + } + } else { + switch (reduction) { + case Reduction::Mean: + if (input.sym_numel()==0){ + return -(input * target).sum().fill_(std::numeric_limits::quiet_NaN()); + } else { + return -(input * target).sum() / (input.sym_numel() / n_classes); + } + case Reduction::Sum: + return -(input * target).sum(); + case Reduction::None: + return -(input * target).sum(class_dim); + default: + TORCH_CHECK(false, "Invalid reduction type encountered in cross_entropy: ", reduction); + } + } +} + +static Tensor cross_entropy_loss_label_smoothing( + const Tensor& self, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + c10::SymInt ignore_index, + double label_smoothing) { + auto class_dim = self.dim() == 1 ? 0 : 1; + auto input = at::log_softmax(self, class_dim, self.scalar_type()); + auto nllloss = at::nll_loss_nd_symint(input, target, weight, reduction, ignore_index); + + auto n_classes = input.sym_size(class_dim); + + Tensor smooth_loss; + if (weight.defined()) { + // Expand weight to the correct number of dims for broadcasting with input / target + auto weight_broadcast_shape = SmallBuffer(input.dim()); + std::fill(weight_broadcast_shape.begin(), weight_broadcast_shape.end(), 1); + weight_broadcast_shape[class_dim] = weight.size(0); + Tensor weight_ = weight.view(weight_broadcast_shape); + + smooth_loss = -(input * weight_).sum(class_dim); + } else { + smooth_loss = -input.sum(class_dim); + } + + auto ignore_mask = target == std::move(ignore_index); + smooth_loss.masked_fill_(ignore_mask, 0.0); + + Tensor ret; + switch (reduction) { + case Reduction::Mean: + if (weight.defined()) { + if (isTensorSubclassLike(weight)){ + // we will collect weights from 0 index which is always valid + // and mask them out if they are ignored + auto filtered_target = target.masked_fill(ignore_mask, 0); + auto tgt_weights = weight.gather(0, filtered_target.flatten()); + auto weight_sum = + tgt_weights.masked_fill_(ignore_mask.flatten(), 0).sum(); + ret = smooth_loss.sum() / weight_sum; + } else { + // TODO: This code can path can be removed if #61309 is resolved + // loss is normalized by the weights to be consistent with + // nll_loss_nd + ret = smooth_loss.sum() / + weight.gather(0, target.masked_select(~ignore_mask).flatten()) + .sum(); + } + } else { + auto true_mask = ~ignore_mask; + ret = smooth_loss.sum()/ true_mask.sum(); + } + break; + case Reduction::Sum: + ret = smooth_loss.sum(); + break; + case Reduction::None: + ret = smooth_loss; + break; + default: + TORCH_CHECK(false, "Invalid reduction type encountered in cross_entropy: ", reduction); + } + return (1 - label_smoothing) * nllloss + ret * (label_smoothing / n_classes); +} + +Tensor cross_entropy_loss_symint( + const Tensor& self, + const Tensor& target, + const std::optional& weight, + int64_t reduction, + c10::SymInt ignore_index, + double label_smoothing) { + Tensor ret; + if (self.sym_sizes() == target.sym_sizes()) { + // Assume soft targets when input and target shapes are the same + TORCH_CHECK(at::isFloatingType(target.scalar_type()), + "Expected floating point type for target with class probabilities, got ", target.scalar_type()); + TORCH_CHECK(ignore_index < 0, "ignore_index is not supported for floating point target"); + + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight); + const Tensor& weight_ = *weight_maybe_owned; + ret = cross_entropy_loss_prob_target(self, target, weight_, reduction, label_smoothing); + } else if (label_smoothing > 0.0) { + TORCH_CHECK(label_smoothing <= 1.0, "label_smoothing must be between 0.0 and 1.0. Got: ", label_smoothing); + + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight); + const Tensor& weight_ = *weight_maybe_owned; + ret = cross_entropy_loss_label_smoothing(self, target, weight_, reduction, std::move(ignore_index), label_smoothing); + } else { + auto class_dim = self.dim() == 1 ? 0 : 1; + ret = at::nll_loss_nd_symint( + at::log_softmax(self, class_dim, self.scalar_type()), + target, + weight, + reduction, + std::move(ignore_index)); + } + return ret; +} + +Tensor & nll_loss_out(const Tensor & self, const Tensor & target, const std::optional& weight_opt, int64_t reduction, int64_t ignore_index, Tensor & output) { + Tensor total_weight = at::empty({0}, self.options()); + return std::get<0>(at::nll_loss_forward_out(output, total_weight, self, target, weight_opt, reduction, ignore_index)); +} + +Tensor nll_loss_symint(const Tensor & self, const Tensor & target, const std::optional& weight_opt, int64_t reduction, c10::SymInt ignore_index) { + return std::get<0>(at::nll_loss_forward_symint(self, target, weight_opt, reduction, std::move(ignore_index))); +} + +Tensor nll_loss_nd_symint( + const Tensor& self, + const Tensor& target, + const std::optional& weight, + int64_t reduction, + c10::SymInt ignore_index) { + if (self.dim() < 1) { + TORCH_CHECK_VALUE( + false, "Expected 1 or more dimensions (got ", self.dim(), ")"); + } + + if (self.dim() != 1) { + auto sizes_match = self.sym_sizes()[0].sym_eq(target.sym_sizes()[0]); + if (TORCH_GUARD_OR_FALSE(sizes_match.sym_not())) { + // Statically known mismatch - raise ValueError for eager mode + TORCH_CHECK_VALUE( + false, + "Expected input batch_size (", + self.sym_sizes()[0], + ") to match target batch_size (", + target.sym_sizes()[0], + ")."); + } + // For unbacked symbolic shapes, emit runtime check. + TORCH_SYM_CHECK( + sizes_match, + "Expected input batch_size (", + self.sym_sizes()[0], + ") to match target batch_size (", + target.sym_sizes()[0], + ")."); + } + + Tensor ret; + Tensor input_ = self; + Tensor target_ = target; + if (input_.dim() == 1 || input_.dim() == 2) { + ret = at::nll_loss_symint(input_, target_, weight, reduction, std::move(ignore_index)); + } else if (input_.dim() == 4) { + ret = at::nll_loss2d_symint(input_, target_, weight, reduction, std::move(ignore_index)); + } else { + // dim == 3 or dim > 4 + auto n = input_.sym_sizes()[0]; + auto c = input_.sym_sizes()[1]; + auto out_size = input_.sym_sizes().slice(2).vec(); + out_size.insert(out_size.begin(), n); + if (target_.sym_sizes().slice(1) != input_.sym_sizes().slice(2)) { + TORCH_CHECK( + false, + "Expected target size ", + SymIntArrayRef(out_size), + ", got ", + target_.sym_sizes()); + } + input_ = input_.contiguous(); + target_ = target_.contiguous(); + // support empty batches, see #15870 + if (input_.sym_numel() > 0) { + input_ = input_.view_symint({n, std::move(c), 1, -1}); + } else { + input_ = input_.view_symint({n, std::move(c), 0, 0}); + } + if (target_.sym_numel() > 0) { + target_ = target_.view_symint({std::move(n), 1, -1}); + } else { + target_ = target_.view_symint({std::move(n), 0, 0}); + } + if (reduction != Reduction::None) { + ret = at::nll_loss2d_symint(input_, target_, weight, reduction, std::move(ignore_index)); + } else { + auto out = + at::nll_loss2d_symint(input_, target_, weight, reduction, std::move(ignore_index)); + ret = out.view_symint(out_size); + } + } + return ret; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/LossNLL2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/LossNLL2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1708beebe914a74f984d0d7b78c8acc15ce97e0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/LossNLL2d.cpp @@ -0,0 +1,490 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace at::native { + +namespace { + +// Returns a contiguous tensor if the source tensor +// is defined. Otherwise returns the undefined +// source tensor unmodified. +inline Tensor optional_contiguous(const Tensor& source) { + return source.defined() ? source.contiguous() : source; +} + +// Returns the address of the first element of a tensor +// or nullptr if the tensor is undefined. +template +inline scalar_t* optional_data(const Tensor& source) { + if constexpr (std::is_const_v) { + return source.defined() ? source.const_data_ptr() : nullptr; + } else { + return source.defined() ? source.data_ptr() : nullptr; + } +} + +inline void check_inputs_nll_loss2d( + const Tensor& input, + const Tensor& target, + const Tensor& weight) { + TORCH_CHECK( + target.dim() == 3, + "only batches of spatial targets supported (3D tensors)" + " but got targets of dimension: ", + target.dim()); + TORCH_CHECK( + input.dim() == 4, + "only batches of spatial inputs supported (4D tensors), " + "but got input of dimension: ", + input.dim()); + TORCH_CHECK( + target.scalar_type() == kLong || target.scalar_type() == kByte, + "expected target dtype to be Long or Byte, but got ", + target.scalar_type()); + TORCH_CHECK( + !weight.defined() || weight.numel() == input.size(1), + "weight tensor should be defined either for all or no classes"); + + const int64_t input0 = input.size(0); + const int64_t input2 = input.size(2); + const int64_t input3 = input.size(3); + const int64_t target0 = target.size(0); + const int64_t target1 = target.size(1); + const int64_t target2 = target.size(2); + TORCH_CHECK( + input0 == target0 && input2 == target1 && input3 == target2, + "size mismatch (got input: ", + input.sizes(), + " , target: ", + target.sizes()); +} + +inline void check_gradout_shape_nll_loss2d( + const Tensor& grad_output, + const Tensor& target) { + TORCH_CHECK( + grad_output.dim() == 3, + "grad_output must have same dimension as target (3) but got dimension: ", + grad_output.sizes()); + + const int64_t grad_output0 = grad_output.size(0); + const int64_t grad_output1 = grad_output.size(1); + const int64_t grad_output2 = grad_output.size(2); + const int64_t target0 = target.size(0); + const int64_t target1 = target.size(1); + const int64_t target2 = target.size(2); + TORCH_CHECK( + grad_output0 == target0 && grad_output1 == target1 && + grad_output2 == target2, + "size mismatch (got grad_output: ", + grad_output.sizes(), + " target: ", + target.sizes()); +} + + +template +void nll_loss2d_forward_out_frame( + Tensor& output, + Tensor& total_weight, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index) { + const int64_t n_classes = input.size(1); + + scalar_t* total_weight_data = total_weight.data_ptr(); + *total_weight_data = 0; + + auto weight_contiguous = optional_contiguous(weight); + const scalar_t* weight_data = optional_data(weight_contiguous); + + if (reduction == Reduction::None) { + const int64_t batch_size = input.size(0); + const int64_t H = input.size(2); + const int64_t W = input.size(3); + + at::native::resize_output(output, {batch_size, H, W}); + auto input_acc = input.accessor(); + auto output_acc = output.accessor(); + auto target_acc = target.accessor(); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + for (const auto h : c10::irange(H)) { + for (const auto w : c10::irange(W)) { + const int64_t cur_target = target_acc[b][h][w]; + + if (cur_target == ignore_index) { + output_acc[b][h][w] = static_cast(0); + continue; + } + + TORCH_CHECK_INDEX( + cur_target >= 0 && cur_target < n_classes, + "Target ", + cur_target, + " is out of bounds."); + + // load optional weight value + const scalar_t cur_weight = weight_data != nullptr + ? weight_data[cur_target] + : static_cast(1); + output_acc[b][h][w] = -input_acc[b][cur_target][h][w] * cur_weight; + } + } + } + }); + + return; + } + + // produce scalar outputs for the reduction case + at::native::resize_output(output, {}); + + if (target.numel() == 0) { + // Here target (and input) have zero elements + // Mean reduction on empty tensors produces NaN. See the discussion in + // https://github.com/pytorch/pytorch/pull/64572#issuecomment-926504162 + if (reduction == Reduction::Mean) { + output.fill_(std::numeric_limits::quiet_NaN()); + } else { + output.zero_(); + } + total_weight.zero_(); + return; + } + + auto input_contiguous = input.contiguous(); + auto target_contiguous = target.contiguous(); + + const scalar_t* input_data = input_contiguous.const_data_ptr(); + const int64_t* target_data = target_contiguous.const_data_ptr(); + + const int64_t batch_size = input.size(0); + const int64_t map_size = input.size(2) * input.size(3); + const int64_t sample_size = map_size * n_classes; + const int64_t numiter = batch_size * map_size; + + constexpr int64_t cascade_sum_num_levels = 8; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + scalar_t weight_partial_sums[cascade_sum_num_levels] = {0}; + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + scalar_t loss_partial_sums[cascade_sum_num_levels] = {0}; + const int64_t level_power = + std::max(static_cast(4), utils::CeilLog2(numiter) / cascade_sum_num_levels); + const int64_t level_step = (1 << level_power); + const int64_t level_mask = level_step - 1; + + int64_t num_ignored = 0; + for (const auto b : c10::irange(batch_size)) { + for (const auto elem : c10::irange(map_size)) { + const int64_t cur_target = target_data[b * map_size + elem]; + if (cur_target == ignore_index) { + ++num_ignored; + continue; + } + + TORCH_CHECK_INDEX( + cur_target >= 0 && cur_target < n_classes, + "Target ", + cur_target, + " is out of bounds."); + + const auto data = input_data[b * sample_size + cur_target * map_size + elem]; + if (weight_data) { + const scalar_t weight_val = weight_data[cur_target]; + loss_partial_sums[0] -= data * weight_val; + weight_partial_sums[0] += weight_val; + } else { + loss_partial_sums[0] -= data; + } + + const int64_t linear_idx = b * map_size + elem; + for (int64_t j = 0; j + 1 < cascade_sum_num_levels; ++j) { + const auto mask = (level_mask << (j * level_power)); + if (C10_LIKELY((linear_idx & mask) != 0)) { + break; + } + + weight_partial_sums[j + 1] += weight_partial_sums[j]; + loss_partial_sums[j + 1] += loss_partial_sums[j]; + + weight_partial_sums[j] = 0; + loss_partial_sums[j] = 0; + } + } + } + + + const scalar_t total_weight_val = !weight_data ? + static_cast(numiter - num_ignored) : + std::accumulate(std::begin(weight_partial_sums), + std::end(weight_partial_sums), + scalar_t{0}); + + scalar_t output_val = std::accumulate(std::begin(loss_partial_sums), + std::end(loss_partial_sums), + scalar_t{0}); + + if (reduction == Reduction::Mean) { + output_val /= total_weight_val; + } + + *total_weight_data = total_weight_val; + *output.data_ptr() = output_val; +} + +void nll_loss2d_forward_out_cpu_template( + Tensor& output, + Tensor& total_weight, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index) { + check_inputs_nll_loss2d(input, target, weight); + total_weight.resize_({}); + + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, + ScalarType::Half, + input.scalar_type(), + "nll_loss2d_forward_out_frame", + [&] { + nll_loss2d_forward_out_frame( + output, + total_weight, + input, + target, + weight, + reduction, + ignore_index); + }); +} + +template +void nll_loss2d_backward_out_frame( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight) { + auto weight_contiguous = optional_contiguous(weight); + const scalar_t* weight_data = optional_data(weight_contiguous); + + if (reduction == at::Reduction::None) { + check_gradout_shape_nll_loss2d(grad_output, target); + + const int64_t batch_size = input.size(0); + const int64_t H = input.size(2); + const int64_t W = input.size(3); + + auto grad_input_acc = grad_input.accessor(); + auto grad_output_acc = grad_output.accessor(); + auto target_acc = target.accessor(); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + for (const auto h : c10::irange(H)) { + for (const auto w : c10::irange(W)) { + const int64_t cur_target = target_acc[b][h][w]; + if (cur_target == ignore_index) { + continue; + } + const scalar_t value = + -(weight_data ? weight_data[cur_target] + : static_cast(1)); + const scalar_t grad_output_value = grad_output_acc[b][h][w]; + grad_input_acc[b][cur_target][h][w] = value * grad_output_value; + } + } + } + }); + + return; + } + + const scalar_t total_weight_value = *total_weight.const_data_ptr(); + + TORCH_CHECK( + grad_output.dim() <= 1 && grad_output.numel() == 1, + "Expected a single element grad_output tensor, but got: ", + grad_output.sizes()); + + const scalar_t grad_output_value = *grad_output.const_data_ptr(); + + const auto target_contiguous = target.contiguous(); + const int64_t* target_data = target_contiguous.const_data_ptr(); + + scalar_t* grad_input_data = grad_input.mutable_data_ptr(); + + const int64_t batch_size = input.size(0); + const int64_t n_classes = input.size(1); + const int64_t map_size = input.size(2) * input.size(3); + const int64_t sample_size = map_size * n_classes; + + const auto grad = -(reduction == Reduction::Mean ? grad_output_value / total_weight_value + : grad_output_value); + + at::parallel_for(0, batch_size, 0, [&](int64_t start, int64_t end) { + for (const auto b : c10::irange(start, end)) { + for (const auto elem : c10::irange(map_size)) { + const int64_t t = target_data[b * map_size + elem]; + + if (t != ignore_index) { + TORCH_CHECK_INDEX(t >= 0 && t < n_classes, "Target ", t, " is out of bounds."); + + const int64_t index = b * sample_size + t * map_size + elem; + grad_input_data[index] = weight_data != nullptr ? weight_data[t] * grad + : grad; + } + } + } + }); +} + +void nll_loss2d_backward_out_cpu_template( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& input, + const Tensor& target, + const Tensor& weight, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight) { + check_inputs_nll_loss2d(input, target, weight); + grad_input.resize_as_(input); + grad_input.zero_(); + TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous"); + TORCH_CHECK( + total_weight.numel() == 1, + "expected total_weight to be a single element tensor, got: ", + total_weight.sizes(), + " (", + total_weight.numel(), + " elements)"); + + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, + ScalarType::Half, + input.scalar_type(), + "nll_loss2d_backward_out_frame", + [&] { + nll_loss2d_backward_out_frame( + grad_input, + grad_output, + input, + target, + weight, + reduction, + ignore_index, + total_weight); + }); +} + +} // namespace + +std::tuple nll_loss2d_forward_out_cpu(const Tensor& self, + const Tensor& target, const std::optional& weight_opt, + int64_t reduction, + int64_t ignore_index, + Tensor& output, + Tensor& total_weight) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + + nll_loss2d_forward_out_cpu_template( + output, total_weight, self, target, weight, reduction, ignore_index); + return std::tuple(output, total_weight); +} + +std::tuple nll_loss2d_forward_cpu( + const Tensor& self, + const Tensor& target, const std::optional& weight_opt, + int64_t reduction, + int64_t ignore_index) { + auto output = at::empty({0}, self.options()); + auto total_weight = at::empty({0}, self.options()); + at::native::nll_loss2d_forward_out_cpu( + self, target, weight_opt, reduction, ignore_index, output, total_weight); + return std::make_tuple(std::move(output), std::move(total_weight)); +} + +Tensor& nll_loss2d_backward_out_cpu(const Tensor& grad_output, + const Tensor& self, + const Tensor& target, const std::optional& weight_opt, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight, + Tensor& grad_input) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned weight_maybe_owned = at::borrow_from_optional_tensor(weight_opt); + const Tensor& weight = *weight_maybe_owned; + + nll_loss2d_backward_out_cpu_template( + grad_input, + grad_output, + self, + target, + weight, + reduction, + ignore_index, + total_weight); + return grad_input; +} + +Tensor nll_loss2d_backward_cpu( + const Tensor& grad_output, + const Tensor& self, + const Tensor& target, const std::optional& weight_opt, + int64_t reduction, + int64_t ignore_index, + const Tensor& total_weight) { + auto grad_input = at::zeros_like(self); + at::native::nll_loss2d_backward_out_cpu( + grad_output, + self, + target, + weight_opt, + reduction, + ignore_index, + total_weight, + grad_input); + return grad_input; +} + +Tensor & nll_loss2d_out(const Tensor & self, const Tensor & target, const std::optional& weight_opt, int64_t reduction, int64_t ignore_index, Tensor & output) { + Tensor total_weight = at::empty({0}, self.options()); + return std::get<0>(at::nll_loss2d_forward_out(output, total_weight, self, target, weight_opt, reduction, ignore_index)); +} + +Tensor nll_loss2d_symint(const Tensor & self, const Tensor & target, const std::optional& weight_opt, int64_t reduction, c10::SymInt ignore_index) { + return std::get<0>(at::nll_loss2d_forward_symint(self, target, weight_opt, reduction, std::move(ignore_index))); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Math.h b/western_ai/usa/pytorch/aten/src/ATen/native/Math.h new file mode 100644 index 0000000000000000000000000000000000000000..d76ab06bab1e2d5628ca54874bb995c303f2453d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Math.h @@ -0,0 +1,3927 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +C10_CLANG_DIAGNOSTIC_PUSH() +#if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion") +C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion") +#endif + +/* The next function is taken from https://github.com/antelopeusersgroup/antelope_contrib/blob/master/lib/location/libgenloc/erfinv.c. +Below is the copyright. +Output was modified to be inf or -inf when input is 1 or -1. */ + + +/* + Copyright (c) 2014 Indiana University + All rights reserved. + + Written by Prof. Gary L. Pavlis, Dept. of Geol. Sci., + Indiana University, Bloomington, IN + + This software is licensed under the New BSD license: + + Redistribution and use in source and binary forms, + with or without modification, are permitted provided + that the following conditions are met: + + Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + + Redistributions in binary form must reproduce the + above copyright notice, this list of conditions and + the following disclaimer in the documentation and/or + other materials provided with the distribution. + + Neither the name of Indiana University nor + the names of its contributors may be used to endorse + or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER + IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. +*/ + +namespace { +/* + * This function is derived from the implementation of the i0e function in the + * Cephes Math Library. See note [3-Clause BSD License for the Cephes Math + * Library]. + * + * Computes an approximation of the exponentially scaled zeroth order modified + * Bessel function of the first kind. The approximation is actually two + * (sub)approximations, both using a Chebyshev polynomial expansion. One + * approximates the function over [0, 8], and the other over (8, infinity). This + * function takes the absolute value of all inputs to convert them into the + * domain of the approximation. + */ +jiterator_also_stringify_as(jiterator_code( + template + JITERATOR_HOST_DEVICE T chbevl(T x, const T array[], const int len) { + T b0, b1, b2 = 0; + + b0 = array[0]; + b1 = 0; + + for (int i = 1; i < len; ++i) { + b2 = b1; + b1 = b0; + b0 = x * b1 - b2 + array[i]; + } + + return T{0.5} * (b0 - b2); + } + + template + JITERATOR_HOST_DEVICE T calc_i0e(T _x) { + T x = std::fabs(_x); + + if (x <= T{8.0}) { + static const T coefficients[] = { + -4.41534164647933937950E-18, 3.33079451882223809783E-17, + -2.43127984654795469359E-16, 1.71539128555513303061E-15, + -1.16853328779934516808E-14, 7.67618549860493561688E-14, + -4.85644678311192946090E-13, 2.95505266312963983461E-12, + -1.72682629144155570723E-11, 9.67580903537323691224E-11, + -5.18979560163526290666E-10, 2.65982372468238665035E-9, + -1.30002500998624804212E-8, 6.04699502254191894932E-8, + -2.67079385394061173391E-7, 1.11738753912010371815E-6, + -4.41673835845875056359E-6, 1.64484480707288970893E-5, + -5.75419501008210370398E-5, 1.88502885095841655729E-4, + -5.76375574538582365885E-4, 1.63947561694133579842E-3, + -4.32430999505057594430E-3, 1.05464603945949983183E-2, + -2.37374148058994688156E-2, 4.93052842396707084878E-2, + -9.49010970480476444210E-2, 1.71620901522208775349E-1, + -3.04682672343198398683E-1, 6.76795274409476084995E-1}; + + T y = (x / T{2.0}) - T{2.0}; + return chbevl(y, coefficients, int{30}); + } + + // x > 8 + static const T coefficients[] = { + -7.23318048787475395456E-18, -4.83050448594418207126E-18, + 4.46562142029675999901E-17, 3.46122286769746109310E-17, + -2.82762398051658348494E-16, -3.42548561967721913462E-16, + 1.77256013305652638360E-15, 3.81168066935262242075E-15, + -9.55484669882830764870E-15, -4.15056934728722208663E-14, + 1.54008621752140982691E-14, 3.85277838274214270114E-13, + 7.18012445138366623367E-13, -1.79417853150680611778E-12, + -1.32158118404477131188E-11, -3.14991652796324136454E-11, + 1.18891471078464383424E-11, 4.94060238822496958910E-10, + 3.39623202570838634515E-9, 2.26666899049817806459E-8, + 2.04891858946906374183E-7, 2.89137052083475648297E-6, + 6.88975834691682398426E-5, 3.36911647825569408990E-3, + 8.04490411014108831608E-1}; + + return chbevl(T{32.0} / x - T{2.0}, coefficients, int{25}) / std::sqrt(x); + }), + i0e_string) // i0e_string +} + +#define CENTRAL_RANGE 0.7 + +template +inline typename std::enable_if_t, T> +calc_erfinv(T y) { +/* Function to calculate inverse error function. Rational approximation +is used to generate an initial approximation, which is then improved to +full accuracy by two steps of Newton's method. Code is a direct +translation of the erfinv m file in matlab version 2.0. +Author: Gary L. Pavlis, Indiana University +Date: February 1996 +*/ + T x, z, num, dem; /*working variables */ + /* coefficients in rational expansion */ + T a[4] = { T(0.886226899), T(-1.645349621), T(0.914624893), T(-0.140543331) }; + T b[4] = { T(-2.118377725), T(1.442710462), T(-0.329097515), T(0.012229801) }; + T c[4] = { T(-1.970840454), T(-1.624906493), T(3.429567803), T(1.641345311) }; + T d[2] = { T(3.543889200), T(1.637067800) }; + T y_abs = std::abs(y); + if(y_abs > 1.0) return std::numeric_limits::quiet_NaN(); +#ifdef _WIN32 + // error C2039: '_copysign': is not a member of 'std' + if(y_abs == 1.0) return copysign(std::numeric_limits::infinity(), y); +#else + if(y_abs == 1.0) return std::copysign(std::numeric_limits::infinity(), y); +#endif + if(y_abs <= static_cast(CENTRAL_RANGE)) { + z = y * y; + num = (((a[3]*z + a[2])*z + a[1])*z + a[0]); + dem = ((((b[3]*z + b[2])*z + b[1])*z +b[0]) * z + static_cast(1.0)); + x = y * num / dem; + } + else{ + z = std::sqrt(-std::log((static_cast(1.0)-y_abs)/static_cast(2.0))); + num = ((c[3]*z + c[2])*z + c[1]) * z + c[0]; + dem = (d[1]*z + d[0])*z + static_cast(1.0); +#ifdef _WIN32 + // error C2039: '_copysign': is not a member of 'std' + x = copysign(num, y) / dem; +#else + x = std::copysign(num, y) / dem; +#endif + } + /* Two steps of Newton-Raphson correction */ + x = x - (std::erf(x) - y) / ((static_cast(2.0)*c10::frac_1_sqrt_pi)*std::exp(-x*x)); + x = x - (std::erf(x) - y) / ((static_cast(2.0)*c10::frac_1_sqrt_pi)*std::exp(-x*x)); + + return x; +} + +#undef CENTRAL_RANGE + +/* + * Note [3-Clause BSD License for the Cephes Math Library] + * Code derived from implementations in the Cephes Math Library should mention its derivation and reference + * this note (ex. 'This function is derived from the implementation of X in the Cephes Math Library. See note + * [3-Clause BSD License for the Cephes Math Library]. The license is: + * Copyright (c) 2018, Steven Moshier + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL Steven Moshier BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * This function is derived from the implementation of the zeta function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + */ +template +C10_HOST_DEVICE inline scalar_t zeta(scalar_t x, scalar_t q) __ubsan_ignore_float_divide_by_zero__ { + using acc_t = at::acc_type; + const acc_t MACHEP = acc_t{1.11022302462515654042E-16}; + constexpr acc_t zero = acc_t{0.0}; + constexpr acc_t half = acc_t{0.5}; + constexpr acc_t one = acc_t{1.0}; + static const acc_t A[] = { + 12.0, + -720.0, + 30240.0, + -1209600.0, + 47900160.0, + -1.8924375803183791606e9, /*1.307674368e12/691*/ + 7.47242496e10, + -2.950130727918164224e12, /*1.067062284288e16/3617*/ + 1.1646782814350067249e14, /*5.109094217170944e18/43867*/ + -4.5979787224074726105e15, /*8.028576626982912e20/174611*/ + 1.8152105401943546773e17, /*1.5511210043330985984e23/854513*/ + -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091*/ + }; + + acc_t a, b, k, s, t, w; + if (x == one) { + return std::numeric_limits::infinity(); + } + + if (x < one) { + return std::numeric_limits::quiet_NaN(); + } + + if (q <= zero) { + if (q == std::floor(q)) { + return std::numeric_limits::infinity(); + } + if (x != std::floor(x)) { + return std::numeric_limits::quiet_NaN(); + } + } + + s = std::pow(q, -x); + a = q; + int i = 0; + b = zero; + while ((i < 9) || (a <= acc_t{9.0})) { + i += 1; + a += one; + b = ::pow(a, -x); + s += b; + if ((-MACHEP * s < b) && (b < MACHEP * s)) { + return static_cast(s); + } + }; + + w = a; + s += b * w / (x - one); + s -= half * b; + a = one; + k = zero; + for (i = 0; i < 12; i++) { + a *= x + k; + b /= w; + t = a * b / A[i]; + s = s + t; + t = ::fabs(t / s); + if (t < MACHEP) { + return static_cast(s); + } + k += one; + a *= x + k; + b /= w; + k += one; + } + return static_cast(s); +} + +/* + * This function is derived from the implementation of the digamma function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + * + * Evaluates polynomial of degree N: + * + * 2 N + * y = C + C x + C x +...+ C x + * 0 1 2 N + * + * Coefficients are stored in reverse order: + * + * coef[0] = C , ..., coef[N] = C . + * N 0 + */ +template +C10_HOST_DEVICE inline T polevl(const T x, const T A[], size_t len) { + T result = 0; + for (size_t i = 0; i <= len; i++) { + result = result * x + A[i]; + } + return result; +} + +inline double trigamma(double x) __ubsan_ignore_float_divide_by_zero__ { + double sign = +1; + double result = 0; + if (x < 0.5) { + sign = -1; + const double sin_pi_x = sin(c10::pi * x); + result -= (c10::pi * c10::pi) / (sin_pi_x * sin_pi_x); + x = 1 - x; + } + for (int i = 0; i < 6; ++i) { + result += 1 / (x * x); + x += 1; + } + const double ixx = 1 / (x*x); + result += (1 + 1 / (2*x) + ixx * (1./6 - ixx * (1./30 - ixx * (1./42)))) / x; + return sign * result; +} + +inline float trigamma(float x) __ubsan_ignore_float_divide_by_zero__ { + float sign = +1; + float result = 0; + if (x < 0.5f) { + sign = -1; + const float sin_pi_x = sinf(c10::pi * x); + result -= (c10::pi * c10::pi) / (sin_pi_x * sin_pi_x); + x = 1 - x; + } + for (int i = 0; i < 6; ++i) { + result += 1 / (x * x); + x += 1; + } + const float ixx = 1 / (x*x); + result += (1 + 1 / (2*x) + ixx * (1.f/6 - ixx * (1.f/30 - ixx * (1.f/42)))) / x; + return sign * result; +} + +/* + * This function is derived from the implementation of the digamma function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + */ +inline double calc_digamma(double x) { + // [C++ Standard Reference: Gamma Function] https://en.cppreference.com/w/cpp/numeric/math/tgamma + static double PSI_10 = 2.25175258906672110764; + if (x == 0) { + // As per C++ standard for gamma related functions and SciPy, + // If the argument is ±0, ±∞ is returned + return std::copysign(INFINITY, -x); + } + + bool x_is_integer = x == trunc(x); + if (x < 0) { + if (x_is_integer) { + // As per C++ standard for gamma related functions and SciPy, + // If the argument is a negative integer, NaN is returned + return std::numeric_limits::quiet_NaN(); + } + // Extracts the fractional part of x as r, since tan(pi * r) is more numerically + // accurate than tan(pi * x). While these operations are mathematically equivalent + // since both x and r are in radians and tan() has a periodicity of pi, in practice + // the computation of pi * x is a source of error (when |x| > 1). + double q, r; + r = std::modf(x, &q); + return calc_digamma(1 - x) - c10::pi / tan(c10::pi * r); + } + + // Push x to be >= 10 + double result = 0; + while (x < 10) { + result -= 1 / x; + x += 1; + } + if (x == 10) { + return result + PSI_10; + } + + // Compute asymptotic digamma + static const double A[] = { + 8.33333333333333333333E-2, + -2.10927960927960927961E-2, + 7.57575757575757575758E-3, + -4.16666666666666666667E-3, + 3.96825396825396825397E-3, + -8.33333333333333333333E-3, + 8.33333333333333333333E-2, + }; + + double y = 0; + if (x < 1.0e17) { + double z = 1.0 / (x * x); + y = z * polevl(z, A, 6); + } + return result + log(x) - (0.5 / x) - y; +} + +/* + * This function is derived from the implementation of the digamma function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + */ +inline float calc_digamma(float x) { + // See [C++ Standard Reference: Gamma Function] + static float PSI_10 = 2.25175258906672110764f; + if (x == 0) { + // As per C++ standard for gamma related functions and SciPy, + // If the argument is ±0, ±∞ is returned + return std::copysign(INFINITY, -x); + } + + bool x_is_integer = x == truncf(x); + if (x < 0) { + if (x_is_integer) { + // As per C++ standard for gamma related functions and SciPy, + // If the argument is a negative integer, NaN is returned + return std::numeric_limits::quiet_NaN(); + } + // Extracts the fractional part of x as r, since tan(pi * r) is more numerically + // accurate than tan(pi * x). While these operations are mathematically equivalent + // since both x and r are in radians and tan() has a periodicity of pi, in practice + // the computation of pi * x is a source of error (when |x| > 1). + double q, r; + r = std::modf(x, &q); + float pi_over_tan_pi_x = (float)(c10::pi / tan(c10::pi * r)); + return calc_digamma(1 - x) - pi_over_tan_pi_x; + } + + // Push x to be >= 10 + float result = 0; + while (x < 10) { + result -= 1 / x; + x += 1; + } + if (x == 10) { + return result + PSI_10; + } + + // Compute asymptotic digamma + static const float A[] = { + 8.33333333333333333333E-2f, + -2.10927960927960927961E-2f, + 7.57575757575757575758E-3f, + -4.16666666666666666667E-3f, + 3.96825396825396825397E-3f, + -8.33333333333333333333E-3f, + 8.33333333333333333333E-2f, + }; + + float y = 0; + if (x < 1.0e17f) { + float z = 1 / (x * x); + y = z * polevl(z, A, 6); + } + return result + logf(x) - (0.5f / x) - y; +} + +inline c10::BFloat16 calc_digamma(c10::BFloat16 a) { + return calc_digamma(static_cast(a)); +} + +inline c10::Half calc_digamma(c10::Half a) { + return calc_digamma(static_cast(a)); +} + +template +inline C10_HOST_DEVICE scalar_t calc_polygamma(scalar_t x, int n) { + // already blocked if n <= 1 + const auto one = scalar_t{1}; + return ((n % 2) ? one : -one) * + std::exp(std::lgamma(static_cast(n) + one)) * + zeta(static_cast(n + 1), x); +} + +// regularized lower incomplete gamma +// the regularized lower, upper incomplete gamma, as well as their +// helper functions follow SciPy's implementation + +/* References + * [igam1] "The Digital Library of Mathematical Functions", dlmf.nist.gov + * [igam2] Maddock et al., "Incomplete Gamma Functions", + * https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/sf_gamma/igamma.html + */ + +/* + * This implementation of the regularized incomplete gamma functions and + * their helper functions are derived from the implementation of SciPy's + * gammainc, Cephes's igam and igamc, and Boost's Lanczos approximations. + * See NOTICE for the licenses. + */ +template +scalar_t ratevl(scalar_t x, const scalar_t num[], int64_t M, + const scalar_t denom[], int64_t N) { + // evaluating rational function, i.e., the ratio of two polynomials + // the coefficients for numerator are given by `num` while coeffs for + // denumerator are given by `denom` + + int64_t i, dir; + scalar_t y, num_ans, denom_ans; + scalar_t absx = std::fabs(x); + const scalar_t *p; + + if (absx > 1) { + /* Evaluate as a polynomial in 1/x. */ + dir = -1; + p = num + M; + y = 1 / x; + } + else { + dir = 1; + p = num; + y = x; + } + + /* Evaluate the numerator */ + num_ans = *p; + p += dir; + for (i = 1; i <= M; i++) { + num_ans = num_ans * y + *p; + p += dir; + } + /* Evaluate the denominator */ + if (absx > 1) { + p = denom + N; + } + else { + p = denom; + } + + denom_ans = *p; + p += dir; + for (i = 1; i <= N; i++) { + denom_ans = denom_ans * y + *p; + p += dir; + } + if (absx > 1) { + i = N - M; + return std::pow(x, i) * num_ans / denom_ans; + } + else { + return num_ans / denom_ans; + } +} + +// SciPy's lanczos implementation is taken from Boost +/* (C) Copyright John Maddock 2006. + * Use, modification and distribution are subject to the + * Boost Software License, Version 1.0. See + * https://www.boost.org/LICENSE_1_0.txt or see NOTICE. + */ +template +static scalar_t lanczos_sum_expg_scaled(scalar_t x) { + // lanczos approximation + static constexpr scalar_t lanczos_sum_expg_scaled_num[13] = { + 0.006061842346248906525783753964555936883222, + 0.5098416655656676188125178644804694509993, + 19.51992788247617482847860966235652136208, + 449.9445569063168119446858607650988409623, + 6955.999602515376140356310115515198987526, + 75999.29304014542649875303443598909137092, + 601859.6171681098786670226533699352302507, + 3481712.15498064590882071018964774556468, + 14605578.08768506808414169982791359218571, + 43338889.32467613834773723740590533316085, + 86363131.28813859145546927288977868422342, + 103794043.1163445451906271053616070238554, + 56906521.91347156388090791033559122686859 + }; + static constexpr scalar_t lanczos_sum_expg_scaled_denom[13] = { + 1., + 66., + 1925., + 32670., + 357423., + 2637558., + 13339535., + 45995730., + 105258076., + 150917976., + 120543840., + 39916800., + 0. + }; + return ratevl(x, lanczos_sum_expg_scaled_num, + sizeof(lanczos_sum_expg_scaled_num) / sizeof(lanczos_sum_expg_scaled_num[0]) - 1, + lanczos_sum_expg_scaled_denom, + sizeof(lanczos_sum_expg_scaled_denom) / sizeof(lanczos_sum_expg_scaled_denom[0]) - 1); +} + +template +static scalar_t _igam_helper_fac(scalar_t a, scalar_t x) { + // compute x^a * exp(-a) / gamma(a) + // corrected from (15) and (16) in [igam2] by replacing exp(x - a) with + // exp(a - x). + + scalar_t ax, fac, res, num, numfac; + static scalar_t MAXLOG = std::is_same_v ? + 7.09782712893383996843E2 : 88.72283905206835; + static scalar_t EXP1 = 2.718281828459045; + static scalar_t lanczos_g = 6.024680040776729583740234375; + + if (std::fabs(a - x) > 0.4 * std::fabs(a)) { + ax = a * std::log(x) - x - std::lgamma(a); + if (ax < -MAXLOG) { + return 0.0; + } + return std::exp(ax); + } + + fac = a + lanczos_g - 0.5; + res = std::sqrt(fac / EXP1) / lanczos_sum_expg_scaled(a); + + if ((a < 200) && (x < 200)) { + res *= std::exp(a - x) * std::pow(x / fac, a); + } + else { + num = x - a - lanczos_g + 0.5; + numfac = num / fac; + res *= std::exp(a * (std::log1p(numfac) - numfac) + x * (0.5 - lanczos_g) / fac); + } + return res; +} + +template +static scalar_t _igam_helper_series(scalar_t a, scalar_t x) { + // Compute igam using DLMF 8.11.4. [igam1] + static scalar_t MACHEP = std::is_same_v ? + 1.11022302462515654042E-16 : 5.9604644775390625E-8; + static int MAXITER = 2000; + + int i; + scalar_t ans, ax, c, r; + + ax = _igam_helper_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* power series */ + r = a; + c = 1.0; + ans = 1.0; + + for (i = 0; i < MAXITER; i++) { + r += 1.0; + c *= x / r; + ans += c; + if (c <= MACHEP * ans) { + break; + } + } + return (ans * ax / a); +} + +template +static scalar_t _igamc_helper_series(scalar_t a, scalar_t x) { + // Compute igamc using DLMF 8.7.3 [igam1]. This is related to the series in + // _igam_helper_series but extra care is taken to avoid cancellation. + + int n; + scalar_t fac = 1; + scalar_t sum = 0; + scalar_t term, logx; + static scalar_t MAXITER = 2000; + static scalar_t MACHEP = std::is_same_v ? + 1.11022302462515654042E-16 : 5.9604644775390625E-8; + + for (n = 1; n < MAXITER; n++) { + fac *= -x / n; + term = fac / (a + n); + sum += term; + if (std::fabs(term) <= MACHEP * std::fabs(sum)) { + break; + } + } + + logx = std::log(x); + term = -std::expm1(a * logx - std::lgamma(1+a)); + return term - std::exp(a * logx - std::lgamma(a)) * sum; +} + +template +static scalar_t _igam_helper_asymptotic_series(scalar_t a, scalar_t x, bool igam) { + // Compute igam/igamc using DLMF 8.12.3/8.12.4 [igam1] + static constexpr scalar_t d[25][25] = + {{-3.3333333333333333e-1, 8.3333333333333333e-2, -1.4814814814814815e-2, + 1.1574074074074074e-3, 3.527336860670194e-4, -1.7875514403292181e-4, + 3.9192631785224378e-5, -2.1854485106799922e-6, -1.85406221071516e-6, + 8.296711340953086e-7, -1.7665952736826079e-7, 6.7078535434014986e-9, + 1.0261809784240308e-8, -4.3820360184533532e-9, 9.1476995822367902e-10, + -2.551419399494625e-11, -5.8307721325504251e-11, 2.4361948020667416e-11, + -5.0276692801141756e-12, 1.1004392031956135e-13, 3.3717632624009854e-13, + -1.3923887224181621e-13, 2.8534893807047443e-14, -5.1391118342425726e-16, + -1.9752288294349443e-15}, + {-1.8518518518518519e-3, -3.4722222222222222e-3, 2.6455026455026455e-3, + -9.9022633744855967e-4, 2.0576131687242798e-4, -4.0187757201646091e-7, + -1.8098550334489978e-5, 7.6491609160811101e-6, -1.6120900894563446e-6, + 4.6471278028074343e-9, 1.378633446915721e-7, -5.752545603517705e-8, + 1.1951628599778147e-8, -1.7543241719747648e-11, -1.0091543710600413e-9, + 4.1627929918425826e-10, -8.5639070264929806e-11, 6.0672151016047586e-14, + 7.1624989648114854e-12, -2.9331866437714371e-12, 5.9966963656836887e-13, + -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14, + -4.13125571381061e-15}, + {4.1335978835978836e-3, -2.6813271604938272e-3, 7.7160493827160494e-4, + 2.0093878600823045e-6, -1.0736653226365161e-4, 5.2923448829120125e-5, + -1.2760635188618728e-5, 3.4235787340961381e-8, 1.3721957309062933e-6, + -6.298992138380055e-7, 1.4280614206064242e-7, -2.0477098421990866e-10, + -1.4092529910867521e-8, 6.228974084922022e-9, -1.3670488396617113e-9, + 9.4283561590146782e-13, 1.2872252400089318e-10, -5.5645956134363321e-11, + 1.1975935546366981e-11, -4.1689782251838635e-15, -1.0940640427884594e-12, + 4.6622399463901357e-13, -9.905105763906906e-14, 1.8931876768373515e-17, + 8.8592218725911273e-15}, + {6.4943415637860082e-4, 2.2947209362139918e-4, -4.6918949439525571e-4, + 2.6772063206283885e-4, -7.5618016718839764e-5, -2.3965051138672967e-7, + 1.1082654115347302e-5, -5.6749528269915966e-6, 1.4230900732435884e-6, + -2.7861080291528142e-11, -1.6958404091930277e-7, 8.0994649053880824e-8, + -1.9111168485973654e-8, 2.3928620439808118e-12, 2.0620131815488798e-9, + -9.4604966618551322e-10, 2.1541049775774908e-10, -1.388823336813903e-14, + -2.1894761681963939e-11, 9.7909989511716851e-12, -2.1782191880180962e-12, + 6.2088195734079014e-17, 2.126978363279737e-13, -9.3446887915174333e-14, + 2.0453671226782849e-14}, + {-8.618882909167117e-4, 7.8403922172006663e-4, -2.9907248030319018e-4, + -1.4638452578843418e-6, 6.6414982154651222e-5, -3.9683650471794347e-5, + 1.1375726970678419e-5, 2.5074972262375328e-10, -1.6954149536558306e-6, + 8.9075075322053097e-7, -2.2929348340008049e-7, 2.956794137544049e-11, + 2.8865829742708784e-8, -1.4189739437803219e-8, 3.4463580499464897e-9, + -2.3024517174528067e-13, -3.9409233028046405e-10, 1.8602338968504502e-10, + -4.356323005056618e-11, 1.2786001016296231e-15, 4.6792750266579195e-12, + -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18, + -5.0453320690800944e-14}, + {-3.3679855336635815e-4, -6.9728137583658578e-5, 2.7727532449593921e-4, + -1.9932570516188848e-4, 6.7977804779372078e-5, 1.419062920643967e-7, + -1.3594048189768693e-5, 8.0184702563342015e-6, -2.2914811765080952e-6, + -3.252473551298454e-10, 3.4652846491085265e-7, -1.8447187191171343e-7, + 4.8240967037894181e-8, -1.7989466721743515e-14, -6.3061945000135234e-9, + 3.1624176287745679e-9, -7.8409242536974293e-10, 5.1926791652540407e-15, + 9.3589442423067836e-11, -4.5134262161632782e-11, 1.0799129993116827e-11, + -3.661886712685252e-17, -1.210902069055155e-12, 5.6807435849905643e-13, + -1.3249659916340829e-13}, + {5.3130793646399222e-4, -5.9216643735369388e-4, 2.7087820967180448e-4, + 7.9023532326603279e-7, -8.1539693675619688e-5, 5.6116827531062497e-5, + -1.8329116582843376e-5, -3.0796134506033048e-9, 3.4651553688036091e-6, + -2.0291327396058604e-6, 5.7887928631490037e-7, 2.338630673826657e-13, + -8.8286007463304835e-8, 4.7435958880408128e-8, -1.2545415020710382e-8, + 8.6496488580102925e-14, 1.6846058979264063e-9, -8.5754928235775947e-10, + 2.1598224929232125e-10, -7.6132305204761539e-16, -2.6639822008536144e-11, + 1.3065700536611057e-11, -3.1799163902367977e-12, 4.7109761213674315e-18, + 3.6902800842763467e-13}, + {3.4436760689237767e-4, 5.1717909082605922e-5, -3.3493161081142236e-4, + 2.812695154763237e-4, -1.0976582244684731e-4, -1.2741009095484485e-7, + 2.7744451511563644e-5, -1.8263488805711333e-5, 5.7876949497350524e-6, + 4.9387589339362704e-10, -1.0595367014026043e-6, 6.1667143761104075e-7, + -1.7562973359060462e-7, -1.2974473287015439e-12, 2.695423606288966e-8, + -1.4578352908731271e-8, 3.887645959386175e-9, -3.8810022510194121e-17, + -5.3279941738772867e-10, 2.7437977643314845e-10, -6.9957960920705679e-11, + 2.5899863874868481e-17, 8.8566890996696381e-12, -4.403168815871311e-12, + 1.0865561947091654e-12}, + {-6.5262391859530942e-4, 8.3949872067208728e-4, -4.3829709854172101e-4, + -6.969091458420552e-7, 1.6644846642067548e-4, -1.2783517679769219e-4, + 4.6299532636913043e-5, 4.5579098679227077e-9, -1.0595271125805195e-5, + 6.7833429048651666e-6, -2.1075476666258804e-6, -1.7213731432817145e-11, + 3.7735877416110979e-7, -2.1867506700122867e-7, 6.2202288040189269e-8, + 6.5977038267330006e-16, -9.5903864974256858e-9, 5.2132144922808078e-9, + -1.3991589583935709e-9, 5.382058999060575e-16, 1.9484714275467745e-10, + -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18, + -3.3721464474854592e-12}, + {-5.9676129019274625e-4, -7.2048954160200106e-5, 6.7823088376673284e-4, + -6.4014752602627585e-4, 2.7750107634328704e-4, 1.8197008380465151e-7, + -8.4795071170685032e-5, 6.105192082501531e-5, -2.1073920183404862e-5, + -8.8585890141255994e-10, 4.5284535953805377e-6, -2.8427815022504408e-6, + 8.7082341778646412e-7, 3.6886101871706965e-12, -1.5344695190702061e-7, + 8.862466778790695e-8, -2.5184812301826817e-8, -1.0225912098215092e-14, + 3.8969470758154777e-9, -2.1267304792235635e-9, 5.7370135528051385e-10, + -1.887749850169741e-19, -8.0931538694657866e-11, 4.2382723283449199e-11, + -1.1002224534207726e-11}, + {1.3324454494800656e-3, -1.9144384985654775e-3, 1.1089369134596637e-3, + 9.932404122642299e-7, -5.0874501293093199e-4, 4.2735056665392884e-4, + -1.6858853767910799e-4, -8.1301893922784998e-9, 4.5284402370562147e-5, + -3.127053674781734e-5, 1.044986828530338e-5, 4.8435226265680926e-11, + -2.1482565873456258e-6, 1.329369701097492e-6, -4.0295693092101029e-7, + -1.7567877666323291e-13, 7.0145043163668257e-8, -4.040787734999483e-8, + 1.1474026743371963e-8, 3.9642746853563325e-18, -1.7804938269892714e-9, + 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18, + 3.7647749553543836e-11}, + {1.579727660730835e-3, 1.6251626278391582e-4, -2.0633421035543276e-3, + 2.1389686185689098e-3, -1.0108559391263003e-3, -3.9912705529919201e-7, + 3.6235025084764691e-4, -2.8143901463712154e-4, 1.0449513336495887e-4, + 2.1211418491830297e-9, -2.5779417251947842e-5, 1.7281818956040463e-5, + -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6, + -6.8693396379526735e-7, 2.0653236975414887e-7, 4.6714772409838506e-14, + -3.5609886164949055e-8, 2.0470855345905963e-8, -5.8091738633283358e-9, + -1.332821287582869e-16, 9.0354604391335133e-10, -4.9598782517330834e-10, + 1.3481607129399749e-10}, + {-4.0725121195140166e-3, 6.4033628338080698e-3, -4.0410161081676618e-3, + -2.183732802866233e-6, 2.1740441801254639e-3, -1.9700440518418892e-3, + 8.3595469747962458e-4, 1.9445447567109655e-8, -2.5779387120421696e-4, + 1.9009987368139304e-4, -6.7696499937438965e-5, -1.4440629666426572e-10, + 1.5712512518742269e-5, -1.0304008744776893e-5, 3.304517767401387e-6, + 7.9829760242325709e-13, -6.4097794149313004e-7, 3.8894624761300056e-7, + -1.1618347644948869e-7, -2.816808630596451e-15, 1.9878012911297093e-8, + -1.1407719956357511e-8, 3.2355857064185555e-9, 4.1759468293455945e-20, + -5.0423112718105824e-10}, + {-5.9475779383993003e-3, -5.4016476789260452e-4, 8.7910413550767898e-3, + -9.8576315587856125e-3, 5.0134695031021538e-3, 1.2807521786221875e-6, + -2.0626019342754683e-3, 1.7109128573523058e-3, -6.7695312714133799e-4, + -6.9011545676562133e-9, 1.8855128143995902e-4, -1.3395215663491969e-4, + 4.6263183033528039e-5, 4.0034230613321351e-11, -1.0255652921494033e-5, + 6.612086372797651e-6, -2.0913022027253008e-6, -2.0951775649603837e-13, + 3.9756029041993247e-7, -2.3956211978815887e-7, 7.1182883382145864e-8, + 8.925574873053455e-16, -1.2101547235064676e-8, 6.9350618248334386e-9, + -1.9661464453856102e-9}, + {1.7402027787522711e-2, -2.9527880945699121e-2, 2.0045875571402799e-2, + 7.0289515966903407e-6, -1.2375421071343148e-2, 1.1976293444235254e-2, + -5.4156038466518525e-3, -6.3290893396418616e-8, 1.8855118129005065e-3, + -1.473473274825001e-3, 5.5515810097708387e-4, 5.2406834412550662e-10, + -1.4357913535784836e-4, 9.9181293224943297e-5, -3.3460834749478311e-5, + -3.5755837291098993e-12, 7.1560851960630076e-6, -4.5516802628155526e-6, + 1.4236576649271475e-6, 1.8803149082089664e-14, -2.6623403898929211e-7, + 1.5950642189595716e-7, -4.7187514673841102e-8, -6.5107872958755177e-17, + 7.9795091026746235e-9}, + {3.0249124160905891e-2, 2.4817436002649977e-3, -4.9939134373457022e-2, + 5.9915643009307869e-2, -3.2483207601623391e-2, -5.7212968652103441e-6, + 1.5085251778569354e-2, -1.3261324005088445e-2, 5.5515262632426148e-3, + 3.0263182257030016e-8, -1.7229548406756723e-3, 1.2893570099929637e-3, + -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4, + -7.7378565221244477e-5, 2.5625836246985201e-5, 1.0766165333192814e-12, + -5.3246809282422621e-6, 3.349634863064464e-6, -1.0381253128684018e-6, + -5.608909920621128e-15, 1.9150821930676591e-7, -1.1418365800203486e-7, + 3.3654425209171788e-8}, + {-9.9051020880159045e-2, 1.7954011706123486e-1, -1.2989606383463778e-1, + -3.1478872752284357e-5, 9.0510635276848131e-2, -9.2828824411184397e-2, + 4.4412112839877808e-2, 2.7779236316835888e-7, -1.7229543805449697e-2, + 1.4182925050891573e-2, -5.6214161633747336e-3, -2.39598509186381e-9, + 1.6029634366079908e-3, -1.1606784674435773e-3, 4.1001337768153873e-4, + 1.8365800754090661e-11, -9.5844256563655903e-5, 6.3643062337764708e-5, + -2.076250624489065e-5, -1.1806020912804483e-13, 4.2131808239120649e-6, + -2.6262241337012467e-6, 8.0770620494930662e-7, 6.0125912123632725e-16, + -1.4729737374018841e-7}, + {-1.9994542198219728e-1, -1.5056113040026424e-2, 3.6470239469348489e-1, + -4.6435192311733545e-1, 2.6640934719197893e-1, 3.4038266027147191e-5, + -1.3784338709329624e-1, 1.276467178337056e-1, -5.6213828755200985e-2, + -1.753150885483011e-7, 1.9235592956768113e-2, -1.5088821281095315e-2, + 5.7401854451350123e-3, 1.0622382710310225e-9, -1.5335082692563998e-3, + 1.0819320643228214e-3, -3.7372510193945659e-4, -6.6170909729031985e-12, + 8.4263617380909628e-5, -5.5150706827483479e-5, 1.7769536448348069e-5, + 3.8827923210205533e-14, -3.53513697488768e-6, 2.1865832130045269e-6, + -6.6812849447625594e-7}, + {7.2438608504029431e-1, -1.3918010932653375, 1.0654143352413968, + 1.876173868950258e-4, -8.2705501176152696e-1, 8.9352433347828414e-1, + -4.4971003995291339e-1, -1.6107401567546652e-6, 1.9235590165271091e-1, + -1.6597702160042609e-1, 6.8882222681814333e-2, 1.3910091724608687e-8, + -2.146911561508663e-2, 1.6228980898865892e-2, -5.9796016172584256e-3, + -1.1287469112826745e-10, 1.5167451119784857e-3, -1.0478634293553899e-3, + 3.5539072889126421e-4, 8.1704322111801517e-13, -7.7773013442452395e-5, + 5.0291413897007722e-5, -1.6035083867000518e-5, 1.2469354315487605e-14, + 3.1369106244517615e-6}, + {1.6668949727276811, 1.165462765994632e-1, -3.3288393225018906, + 4.4692325482864037, -2.6977693045875807, -2.600667859891061e-4, + 1.5389017615694539, -1.4937962361134612, 6.8881964633233148e-1, + 1.3077482004552385e-6, -2.5762963325596288e-1, 2.1097676102125449e-1, + -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2, + -1.7813678334552311e-2, 6.3970330388900056e-3, 4.9430807090480523e-11, + -1.5554602758465635e-3, 1.0561196919903214e-3, -3.5277184460472902e-4, + 9.3002334645022459e-14, 7.5285855026557172e-5, -4.8186515569156351e-5, + 1.5227271505597605e-5}, + {-6.6188298861372935, 1.3397985455142589e+1, -1.0789350606845146e+1, + -1.4352254537875018e-3, 9.2333694596189809, -1.0456552819547769e+1, + 5.5105526029033471, 1.2024439690716742e-5, -2.5762961164755816, + 2.3207442745387179, -1.0045728797216284, -1.0207833290021914e-7, + 3.3975092171169466e-1, -2.6720517450757468e-1, 1.0235252851562706e-1, + 8.4329730484871625e-10, -2.7998284958442595e-2, 2.0066274144976813e-2, + -7.0554368915086242e-3, 1.9402238183698188e-12, 1.6562888105449611e-3, + -1.1082898580743683e-3, 3.654545161310169e-4, -5.1290032026971794e-11, + -7.6340103696869031e-5}, + {-1.7112706061976095e+1, -1.1208044642899116, 3.7131966511885444e+1, + -5.2298271025348962e+1, 3.3058589696624618e+1, 2.4791298976200222e-3, + -2.061089403411526e+1, 2.088672775145582e+1, -1.0045703956517752e+1, + -1.2238783449063012e-5, 4.0770134274221141, -3.473667358470195, + 1.4329352617312006, 7.1359914411879712e-8, -4.4797257159115612e-1, + 3.4112666080644461e-1, -1.2699786326594923e-1, -2.8953677269081528e-10, + 3.3125776278259863e-2, -2.3274087021036101e-2, 8.0399993503648882e-3, + -1.177805216235265e-9, -1.8321624891071668e-3, 1.2108282933588665e-3, + -3.9479941246822517e-4}, + {7.389033153567425e+1, -1.5680141270402273e+2, 1.322177542759164e+2, + 1.3692876877324546e-2, -1.2366496885920151e+2, 1.4620689391062729e+2, + -8.0365587724865346e+1, -1.1259851148881298e-4, 4.0770132196179938e+1, + -3.8210340013273034e+1, 1.719522294277362e+1, 9.3519707955168356e-7, + -6.2716159907747034, 5.1168999071852637, -2.0319658112299095, + -4.9507215582761543e-9, 5.9626397294332597e-1, -4.4220765337238094e-1, + 1.6079998700166273e-1, -2.4733786203223402e-8, -4.0307574759979762e-2, + 2.7849050747097869e-2, -9.4751858992054221e-3, 6.419922235909132e-6, + 2.1250180774699461e-3}, + {2.1216837098382522e+2, 1.3107863022633868e+1, -4.9698285932871748e+2, + 7.3121595266969204e+2, -4.8213821720890847e+2, -2.8817248692894889e-2, + 3.2616720302947102e+2, -3.4389340280087117e+2, 1.7195193870816232e+2, + 1.4038077378096158e-4, -7.52594195897599e+1, 6.651969984520934e+1, + -2.8447519748152462e+1, -7.613702615875391e-7, 9.5402237105304373, + -7.5175301113311376, 2.8943997568871961, -4.6612194999538201e-7, + -8.0615149598794088e-1, 5.8483006570631029e-1, -2.0845408972964956e-1, + 1.4765818959305817e-4, 5.1000433863753019e-2, -3.3066252141883665e-2, + 1.5109265210467774e-2}, + {-9.8959643098322368e+2, 2.1925555360905233e+3, -1.9283586782723356e+3, + -1.5925738122215253e-1, 1.9569985945919857e+3, -2.4072514765081556e+3, + 1.3756149959336496e+3, 1.2920735237496668e-3, -7.525941715948055e+2, + 7.3171668742208716e+2, -3.4137023466220065e+2, -9.9857390260608043e-6, + 1.3356313181291573e+2, -1.1276295161252794e+2, 4.6310396098204458e+1, + -7.9237387133614756e-6, -1.4510726927018646e+1, 1.1111771248100563e+1, + -4.1690817945270892, 3.1008219800117808e-3, 1.1220095449981468, + -7.6052379926149916e-1, 3.6262236505085254e-1, 2.216867741940747e-1, + 4.8683443692930507e-1}}; + + int k, n, sgn; + int maxpow = 0; + static scalar_t MACHEP = std::is_same_v ? + 1.11022302462515654042E-16 : 5.9604644775390625E-8; + scalar_t lambda = x / a; + scalar_t sigma = (x - a) / a; + scalar_t eta, res, ck, ckterm, term, absterm; + scalar_t absoldterm = INFINITY; + scalar_t etapow[25] = {1}; + scalar_t sum = 0; + scalar_t afac = 1; + + if (igam) { + sgn = -1; + } + else { + sgn = 1; + } + + if (lambda > 1) { + eta = std::sqrt(-2 * (std::log1p(sigma) - sigma)); + } + else if (lambda < 1) { + eta = -std::sqrt(-2 * (std::log1p(sigma) - sigma)); + } + else { + eta = 0; + } + res = 0.5 * std::erfc(sgn * eta * std::sqrt(a / 2)); + + for (k = 0; k < 25; k++) { + ck = d[k][0]; + for (n = 1; n < 25; n++) { + if (n > maxpow) { + etapow[n] = eta * etapow[n-1]; + maxpow += 1; + } + ckterm = d[k][n]*etapow[n]; + ck += ckterm; + if (std::fabs(ckterm) < MACHEP * std::fabs(ck)) { + break; + } + } + term = ck * afac; + absterm = std::fabs(term); + if (absterm > absoldterm) { + break; + } + sum += term; + if (absterm < MACHEP * std::fabs(sum)) { + break; + } + absoldterm = absterm; + afac /= a; + } + res += sgn * std::exp(-0.5 * a * eta * eta) * sum / std::sqrt(2 * c10::pi * a); + + return res; +} + +template +static scalar_t _igamc_helper_continued_fraction(scalar_t a, scalar_t x) { + // Compute igamc using DLMF 8.9.2. [igam1] + int i; + scalar_t ans, ax, c, yc, r, t, y, z; + scalar_t pk, pkm1, pkm2, qk, qkm1, qkm2; + int MAXITER = 2000; + static scalar_t MACHEP = std::is_same_v ? + 1.11022302462515654042E-16 : 5.9604644775390625E-8; + static scalar_t BIG = std::is_same_v ? + 4.503599627370496e15 : 16777216.; + static scalar_t BIGINV = std::is_same_v ? + 2.22044604925031308085e-16 : 5.9604644775390625E-8; + + ax = _igam_helper_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* continued fraction */ + y = 1.0 - a; + z = x + y + 1.0; + c = 0.0; + pkm2 = 1.0; + qkm2 = x; + pkm1 = x + 1.0; + qkm1 = z * x; + ans = pkm1 / qkm1; + + for (i = 0; i < MAXITER; i++) { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk != 0) { + r = pk / qk; + t = std::fabs((ans - r) / r); + ans = r; + } + else { + t = 1.0; + } + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (std::fabs(pk) > BIG) { + pkm2 *= BIGINV; + pkm1 *= BIGINV; + qkm2 *= BIGINV; + qkm1 *= BIGINV; + } + if (t <= MACHEP) { + break; + } + } + return ans * ax; +} + +template +inline scalar_t calc_igammac(scalar_t a, scalar_t x) { + /* the calculation of the regularized upper incomplete gamma function + * is done differently based on the values of a and x: + * - if x and/or a is at the boundary of defined region, then assign the + * result at the boundary + * - if a is large and a ~ x, then using Uniform Asymptotic Expansions for + * Large Parameter (see DLMF 8.12.4 [igam1]) + * - if x > 1.1 and x < a, using the subtraction from the regularized lower + * incomplete gamma + * - otherwise, calculate the series from [igam2] eq (5) + */ + scalar_t absxma_a; + + static scalar_t SMALL = 20.0; + static scalar_t LARGE = 200.0; + static scalar_t SMALLRATIO = 0.3; + static scalar_t LARGERATIO = 4.5; + + // note that in SciPy, a and x are non-negative, with exclusive 0s (i.e., + // at most 1 of them can be 0), where igammac(0, x) = 0.0 iff x > 0. + if ((x < 0) || (a < 0)) { + // out of defined-region of the function + return std::numeric_limits::quiet_NaN(); + } + else if (a == 0) { + if (x > 0) { + return 0.0; + } + else { + return std::numeric_limits::quiet_NaN(); + } + } + else if (x == 0) { + return 1.0; + } + else if (std::isinf(a)) { + if (std::isinf(x)) { + return std::numeric_limits::quiet_NaN(); + } + return 1.0; + } + else if (std::isinf(x)) { + return 0.0; + } + + absxma_a = std::fabs(x - a) / a; + if ((a > SMALL) && (a < LARGE) && (absxma_a < SMALLRATIO)) { + return _igam_helper_asymptotic_series(a, x, 0); + } + else if ((a > LARGE) && (absxma_a < LARGERATIO / std::sqrt(a))) { + return _igam_helper_asymptotic_series(a, x, 0); + } + + if (x > 1.1) { + if (x < a) { + return 1.0 - _igam_helper_series(a, x); + } + else { + return _igamc_helper_continued_fraction(a, x); + } + } + else if (x <= 0.5) { + if (-0.4 / std::log(x) < a) { + return 1.0 - _igam_helper_series(a, x); + } + else { + return _igamc_helper_series(a, x); + } + } + else { + if (x * 1.1 < a) { + return 1.0 - _igam_helper_series(a, x); + } + else { + return _igamc_helper_series(a, x); + } + } +} + +template +scalar_t calc_igamma(scalar_t a, scalar_t x) { + /* the calculation of the regularized lower incomplete gamma function + * is done differently based on the values of a and x: + * - if x and/or a is at the boundary of defined region, then assign the + * result at the boundary + * - if a is large and a ~ x, then using Uniform Asymptotic Expansions for + * Large Parameter (see DLMF 8.12.3 [igam1]) + * - if x > 1 and x > a, using the subtraction from the regularized upper + * incomplete gamma + * - otherwise, calculate the series from [igam2] eq (4) + */ + scalar_t absxma_a; + static scalar_t SMALL = 20.0; + static scalar_t LARGE = 200.0; + static scalar_t SMALLRATIO = 0.3; + static scalar_t LARGERATIO = 4.5; + + // boundary values following SciPy + // note that in SciPy, a and x are non-negative, with exclusive 0s (i.e., + // at most 1 of them can be 0), where igamma(0, x) = 1.0 iff x > 0. + if ((x < 0) || (a < 0)) { + // out of defined-region of the function + return std::numeric_limits::quiet_NaN(); + } + else if (a == 0) { + if (x > 0) { + return 1.0; + } + else { + return std::numeric_limits::quiet_NaN(); + } + } + else if (x == 0) { + return 0.0; // zero integration limit + } + else if (std::isinf(a)) { + if (std::isinf(x)) { + return std::numeric_limits::quiet_NaN(); + } + return 0.0; + } + else if (std::isinf(x)) { + return 1.0; + } + + /* Asymptotic regime where a ~ x. See [igam2] */ + absxma_a = std::fabs(x - a) / a; + if ((a > SMALL) && (a < LARGE) && (absxma_a < SMALLRATIO)) { + return _igam_helper_asymptotic_series(a, x, 1); + } + else if ((a > LARGE) && (absxma_a < LARGERATIO / std::sqrt(a))) { + return _igam_helper_asymptotic_series(a, x, 1); + } + + if ((x > 1.0) && (x > a)) { + return 1.0 - calc_igammac(a, x); + } + + return _igam_helper_series(a, x); +} + +template <> +[[maybe_unused]] inline c10::BFloat16 calc_igamma( + c10::BFloat16 a, + c10::BFloat16 x) { + return calc_igamma(float(a), float(x)); +} + +template <> +[[maybe_unused]] inline c10::Half calc_igamma( + c10::Half a, + c10::Half x) { + return calc_igamma(float(a), float(x)); +} + +template <> +[[maybe_unused]] inline c10::BFloat16 calc_igammac( + c10::BFloat16 a, + c10::BFloat16 x) { + return calc_igammac(float(a), float(x)); +} + +template <> +[[maybe_unused]] inline c10::Half calc_igammac( + c10::Half a, + c10::Half x) { + return calc_igammac(float(a), float(x)); +} + +inline c10::BFloat16 calc_erfinv(c10::BFloat16 a) { return calc_erfinv(float(a)); } + +template +inline T abs_impl(T v) { + return std::abs(v); +} + +template <> +[[maybe_unused]] inline uint8_t abs_impl(uint8_t v) { + return v; +} + +template +inline typename std::enable_if_t, T> +calc_gcd(T a, T b) { + a = abs_impl(a); + b = abs_impl(b); + while (a != 0) { + T c = a; + a = b % a; + b = c; + } + return b; +} + +template +C10_HOST_DEVICE T exp2_impl(T x) { + return std::exp2(x); +} + +template +C10_HOST_DEVICE c10::complex exp2_impl(c10::complex x) { + // There is no std::exp2 overload for complex, so instead + // use the identity 2^x = e^(ln(2) * x) + constexpr auto ln2 = c10::ln_2; + return std::exp(ln2 * x); +} + +/* + * This function is derived from the implementation of the chbevl function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + * + * Evaluates the series + * + * len-1 + * - ' + * y = > array[i] T (x/2) + * - i + * i=0 + * + * of Chebyshev polynomials Ti at argument x/2. + * + * Coefficients are stored in reverse order, i.e. the zero order term is last in the array. Note len is the number of + * coefficients, not the order. + * + * If coefficients are for the interval a to b, x must have been transformed to x -> 2(2x - b - a)/(b-a) before + * entering the routine. This maps x from (a, b) to (-1, 1), over which the Chebyshev polynomials are defined. + * + * If the coefficients are for the inverted interval, in which (a, b) is mapped to (1/b, 1/a), the transformation + * required is x -> 2(2ab/x - b - a)/(b-a). If b is infinity, this becomes x -> 4a/x - 1. + */ +template +inline typename std::enable_if_t, T> +chbevl(const T x, const T array[], size_t len) { + T b0, b1, b2 = static_cast(0.0); + + b0 = array[0]; + b1 = static_cast(0.0); + + for (size_t i = 1; i < len; ++i) { + b2 = b1; + b1 = b0; + b0 = x * b1 - b2 + array[i]; + } + + return (static_cast(0.5) * (b0 - b2)); +} + +/* + * This function is derived from the implementation of the i0 function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + * + * Computes an approximation of the zeroth order modified Bessel function of the first kind. + * The approximation is actually two (sub)approximations, both using a Chebyshev polynomial expansion. + * One approximates the function over [0, 8], and the other over (8, infinity). This function takes the absolute value + * of all inputs to convert them into the domain of the approximation. + */ +template +inline std::tuple chebyshev_coefficients_i0e_A() { + /* Chebyshev coefficients for exp(-x) I0(x) + * in the interval [0,8]. + * + * lim(x->0){ exp(-x) I0(x) } = 1. + */ + static const T coeff[] = { + -4.41534164647933937950E-18, 3.33079451882223809783E-17, + -2.43127984654795469359E-16, 1.71539128555513303061E-15, + -1.16853328779934516808E-14, 7.67618549860493561688E-14, + -4.85644678311192946090E-13, 2.95505266312963983461E-12, + -1.72682629144155570723E-11, 9.67580903537323691224E-11, + -5.18979560163526290666E-10, 2.65982372468238665035E-9, + -1.30002500998624804212E-8, 6.04699502254191894932E-8, + -2.67079385394061173391E-7, 1.11738753912010371815E-6, + -4.41673835845875056359E-6, 1.64484480707288970893E-5, + -5.75419501008210370398E-5, 1.88502885095841655729E-4, + -5.76375574538582365885E-4, 1.63947561694133579842E-3, + -4.32430999505057594430E-3, 1.05464603945949983183E-2, + -2.37374148058994688156E-2, 4.93052842396707084878E-2, + -9.49010970480476444210E-2, 1.71620901522208775349E-1, + -3.04682672343198398683E-1, 6.76795274409476084995E-1}; + return std::make_tuple(coeff, 30); +} + +template +inline std::tuple chebyshev_coefficients_i0e_B() { + /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x) + * in the inverted interval [8,infinity]. + * + * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi). + */ + static const T coeff[] = { + -7.23318048787475395456E-18, -4.83050448594418207126E-18, + 4.46562142029675999901E-17, 3.46122286769746109310E-17, + -2.82762398051658348494E-16, -3.42548561967721913462E-16, + 1.77256013305652638360E-15, 3.81168066935262242075E-15, + -9.55484669882830764870E-15, -4.15056934728722208663E-14, + 1.54008621752140982691E-14, 3.85277838274214270114E-13, + 7.18012445138366623367E-13, -1.79417853150680611778E-12, + -1.32158118404477131188E-11, -3.14991652796324136454E-11, + 1.18891471078464383424E-11, 4.94060238822496958910E-10, + 3.39623202570838634515E-9, 2.26666899049817806459E-8, + 2.04891858946906374183E-7, 2.89137052083475648297E-6, + 6.88975834691682398426E-5, 3.36911647825569408990E-3, + 8.04490411014108831608E-1}; + + return std::make_tuple(coeff, 25); +} + +template +inline typename std::enable_if_t, std::tuple> +chebyshev_coefficients_i1e_A() { + /* Chebyshev coefficients for exp(-x) I1(x) + * in the interval [0,8]. + * + * lim(x->0){ exp(-x) I1(x) / x } = 1/2. + */ + static const T coeff[] = { + 2.77791411276104639959E-18, -2.11142121435816608115E-17, + 1.55363195773620046921E-16, -1.10559694773538630805E-15, + 7.60068429473540693410E-15, -5.04218550472791168711E-14, + 3.22379336594557470981E-13, -1.98397439776494371520E-12, + 1.17361862988909016308E-11, -6.66348972350202774223E-11, + 3.62559028155211703701E-10, -1.88724975172282928790E-9, + 9.38153738649577178388E-9, -4.44505912879632808065E-8, + 2.00329475355213526229E-7, -8.56872026469545474066E-7, + 3.47025130813767847674E-6, -1.32731636560394358279E-5, + 4.78156510755005422638E-5, -1.61760815825896745588E-4, + 5.12285956168575772895E-4, -1.51357245063125314899E-3, + 4.15642294431288815669E-3, -1.05640848946261981558E-2, + 2.47264490306265168283E-2, -5.29459812080949914269E-2, + 1.02643658689847095384E-1, -1.76416518357834055153E-1, + 2.52587186443633654823E-1}; + return std::make_tuple(coeff, 29); +} + +template +inline typename std::enable_if_t, std::tuple> +chebyshev_coefficients_i1e_A() { + /* Chebyshev coefficients for exp(-x) I1(x) + * in the interval [0,8]. + * + * lim(x->0){ exp(-x) I1(x) / x } = 1/2. + */ + static const T coeff[] = { + 9.38153738649577178388E-9f, + -4.44505912879632808065E-8f, + 2.00329475355213526229E-7f, + -8.56872026469545474066E-7f, + 3.47025130813767847674E-6f, + -1.32731636560394358279E-5f, + 4.78156510755005422638E-5f, + -1.61760815825896745588E-4f, + 5.12285956168575772895E-4f, + -1.51357245063125314899E-3f, + 4.15642294431288815669E-3f, + -1.05640848946261981558E-2f, + 2.47264490306265168283E-2f, + -5.29459812080949914269E-2f, + 1.02643658689847095384E-1f, + -1.76416518357834055153E-1f, + 2.52587186443633654823E-1f}; + return std::make_tuple(coeff, 17); +} + +template +inline typename std::enable_if_t, std::tuple> +chebyshev_coefficients_i1e_B() { + /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x) + * in the inverted interval [8,infinity]. + * + * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi). + */ + static const T coeff[] = { + 7.51729631084210481353E-18, 4.41434832307170791151E-18, + -4.65030536848935832153E-17, -3.20952592199342395980E-17, + 2.96262899764595013876E-16, 3.30820231092092828324E-16, + -1.88035477551078244854E-15, -3.81440307243700780478E-15, + 1.04202769841288027642E-14, 4.27244001671195135429E-14, + -2.10154184277266431302E-14, -4.08355111109219731823E-13, + -7.19855177624590851209E-13, 2.03562854414708950722E-12, + 1.41258074366137813316E-11, 3.25260358301548823856E-11, + -1.89749581235054123450E-11, -5.58974346219658380687E-10, + -3.83538038596423702205E-9, -2.63146884688951950684E-8, + -2.51223623787020892529E-7, -3.88256480887769039346E-6, + -1.10588938762623716291E-4, -9.76109749136146840777E-3, + 7.78576235018280120474E-1}; + + return std::make_tuple(coeff, 25); +} + +template +inline typename std::enable_if_t, std::tuple> +chebyshev_coefficients_i1e_B() { + /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x) + * in the inverted interval [8,infinity]. + * + * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi). + */ + static const T coeff[] = { + -3.83538038596423702205E-9f, + -2.63146884688951950684E-8f, + -2.51223623787020892529E-7f, + -3.88256480887769039346E-6f, + -1.10588938762623716291E-4f, + -9.76109749136146840777E-3f, + 7.78576235018280120474E-1f}; + + return std::make_tuple(coeff, 7); +} + +template +inline typename std::enable_if_t, T> +calc_i0(T _x) { + T x = std::abs(_x); + + if (x <= T{8.0}) { + auto [A, len] = chebyshev_coefficients_i0e_A(); + T y = (x / T{2.0}) - T{2.0}; + return static_cast(std::exp(x) * chbevl(y, A, len)); + } + auto [B, len] = chebyshev_coefficients_i0e_B(); + return std::exp(x) * chbevl(T{32.0} / x - T{2.0}, B, len) / std::sqrt(x); +} + +// Upcast bfloat16/half input to float for numerical accuracy purposes +inline c10::BFloat16 calc_i0(c10::BFloat16 a) { return calc_i0(static_cast(a)); } +inline c10::Half calc_i0(c10::Half a) { return calc_i0(static_cast(a)); } + +/* + * This function is derived from the implementation of the i1 function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + * + * Computes an approximation of the first order modified Bessel function of the first kind. + * The approximation is actually two (sub)approximations, both using a Chebyshev polynomial expansion. + * One approximates the function over [0, 8], and the other over (8, infinity). This function takes the absolute value + * of all inputs to convert them into the domain of the approximation. + */ +template +inline typename std::enable_if_t, T> +calc_i1(T _x) { + T x = std::abs(_x); + + if (x <= T{8.0}) { + auto [A, len] = chebyshev_coefficients_i1e_A(); + T y = (x / T{2.0}) - T{2.0}; + const T out = std::exp(x) * x * chbevl(y, A, len); + return (_x < T{0.0}) ? -out : out; + } + auto [B, len] = chebyshev_coefficients_i1e_B(); + const T out = (std::exp(x) * chbevl(T{32.0} / x - T{2.0}, B, len)) / std::sqrt(x); + return (_x < T{0.0}) ? -out : out; +} + +// Upcast bfloat16/half input to float for numerical accuracy purposes +inline c10::BFloat16 calc_i1(c10::BFloat16 a) { return calc_i1(static_cast(a)); } +inline c10::Half calc_i1(c10::Half a) { return calc_i1(static_cast(a)); } + + +/* + * This function is derived from the implementation of the i1e function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + * + * Computes an approximation of the exponentially scaled first order modified Bessel function of the first kind. + * The approximation is actually two (sub)approximations, both using a Chebyshev polynomial expansion. + * One approximates the function over [0, 8], and the other over (8, infinity). This function takes the absolute value + * of all inputs to convert them into the domain of the approximation. + */ +template +inline typename std::enable_if_t, T> +calc_i1e(T _x) { + T x = std::abs(_x); + + if (x <= T{8.0}) { + auto [A, len] = chebyshev_coefficients_i1e_A(); + T y = (x / T{2.0}) - T{2.0}; + const T out = chbevl(y, A, len) * x; + return (_x < T{0.0}) ? -out : out; + } + auto [B, len] = chebyshev_coefficients_i1e_B(); + const auto out = chbevl(T{32.0} / x - T{2.0}, B, len) / std::sqrt(x); + return (_x < T{0.0}) ? -out : out; +} + +// Upcast bfloat16/half input to float for numerical accuracy purposes +inline c10::BFloat16 calc_i1e(c10::BFloat16 a) { return calc_i1e(static_cast(a)); } +inline c10::Half calc_i1e(c10::Half a) { return calc_i1e(static_cast(a)); } + + +/* + * This function is derived from the implementation of the i1e function in the Cephes Math Library. + * See note [3-Clause BSD License for the Cephes Math Library]. + * + * Computes the argument, x, for which the area under the Gaussian probability density function + * (integrated from minus infinity to x) is equal to y. + */ +template +inline C10_HOST_DEVICE T calc_ndtri(T y0) { + + /* sqrt(2pi) */ + constexpr T s2pi = 2.50662827463100050242E0; + constexpr T one = 1; + constexpr T zero = 0; + + /* approximation for 0 <= |y - 0.5| <= 3/8 */ + static const T P0[5] = { + -5.99633501014107895267E1, + 9.80010754185999661536E1, + -5.66762857469070293439E1, + 1.39312609387279679503E1, + -1.23916583867381258016E0, + }; + + static const T Q0[9] = { + 1.00000000000000000000E0, + 1.95448858338141759834E0, + 4.67627912898881538453E0, + 8.63602421390890590575E1, + -2.25462687854119370527E2, + 2.00260212380060660359E2, + -8.20372256168333339912E1, + 1.59056225126211695515E1, + -1.18331621121330003142E0, + }; + + /* Approximation for interval z = sqrt(-2 log y ) between 2 and 8 + * i.e., y between exp(-2) = .135 and exp(-32) = 1.27e-14. + */ + static const T P1[9] = { + 4.05544892305962419923E0, + 3.15251094599893866154E1, + 5.71628192246421288162E1, + 4.40805073893200834700E1, + 1.46849561928858024014E1, + 2.18663306850790267539E0, + -1.40256079171354495875E-1, + -3.50424626827848203418E-2, + -8.57456785154685413611E-4, + }; + + static const T Q1[9] = { + 1.00000000000000000000E0, + 1.57799883256466749731E1, + 4.53907635128879210584E1, + 4.13172038254672030440E1, + 1.50425385692907503408E1, + 2.50464946208309415979E0, + -1.42182922854787788574E-1, + -3.80806407691578277194E-2, + -9.33259480895457427372E-4, + }; + + /* Approximation for interval z = sqrt(-2 log y ) between 8 and 64 + * i.e., y between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890. + */ + + static const T P2[9] = { + 3.23774891776946035970E0, + 6.91522889068984211695E0, + 3.93881025292474443415E0, + 1.33303460815807542389E0, + 2.01485389549179081538E-1, + 1.23716634817820021358E-2, + 3.01581553508235416007E-4, + 2.65806974686737550832E-6, + 6.23974539184983293730E-9, + }; + + static const T Q2[9] = { + 1.00000000000000000000E0, + 6.02427039364742014255E0, + 3.67983563856160859403E0, + 1.37702099489081330271E0, + 2.16236993594496635890E-1, + 1.34204006088543189037E-2, + 3.28014464682127739104E-4, + 2.89247864745380683936E-6, + 6.79019408009981274425E-9, + }; + + if (y0 == zero) { + return -std::numeric_limits::infinity(); + } + if (y0 == one) { + return std::numeric_limits::infinity(); + } + if (y0 < zero || y0 > one) { + return std::numeric_limits::quiet_NaN(); + } + bool code = true; + T y = y0; + if (y > one - T{0.13533528323661269189}) { /* 0.135... = exp(-2) */ + y = one - y; + code = false; + } + + if (y > T{0.13533528323661269189}) { + y = y - T{0.5}; + const T y2 = y * y; + T x = y + y * (y2 * polevl(y2, P0, 4) / polevl(y2, Q0, 8)); + return (x * s2pi); + } + + T x = ::sqrt(T{-2.0} * ::log(y)); + const T x0 = x - ::log(x) / x; + + const T z = one / x; + T x1; + if (x < T{8.0}) /* y > exp(-32) = 1.2664165549e-14 */ + { + x1 = z * polevl(z, P1, 8) / polevl(z, Q1, 8); + } else { + x1 = z * polevl(z, P2, 8) / polevl(z, Q2, 8); + } + x = x0 - x1; + if (code) { + x = -x; + } + return x; +} + +/* The next function is taken from http://ab-initio.mit.edu/faddeeva */ + +/* Copyright (c) 2012 Massachusetts Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* erfcx(x) = exp(x^2) erfc(x) function, for real x, written by + Steven G. Johnson, October 2012. + + This function combines a few different ideas. + + First, for x > 50, it uses a continued-fraction expansion (same as + for the Faddeeva function, but with algebraic simplifications for z=i*x). + + Second, for 0 <= x <= 50, it uses Chebyshev polynomial approximations, + but with two twists: + + a) It maps x to y = 4 / (4+x) in [0,1]. This simple transformation, + inspired by a similar transformation in the octave-forge/specfun + erfcx by Soren Hauberg, results in much faster Chebyshev convergence + than other simple transformations I have examined. + + b) Instead of using a single Chebyshev polynomial for the entire + [0,1] y interval, we break the interval up into 100 equal + subintervals, with a switch/lookup table, and use much lower + degree Chebyshev polynomials in each subinterval. This greatly + improves performance in my tests. + + For x < 0, we use the relationship erfcx(-x) = 2 exp(x^2) - erfc(x), + with the usual checks for overflow etcetera. + + Performance-wise, it seems to be substantially faster than either + the SLATEC DERFC function [or an erfcx function derived there from] + or Cody's CALERF function (from netlib.org/specfun), while + retaining near machine precision in accuracy. */ + +/* Given y100=100*y, where y = 4/(4+x) for x >= 0, compute erfc(x). + + Uses a look-up table of 100 different Chebyshev polynomials + for y intervals [0,0.01], [0.01,0.02], ...., [0.99,1], generated + with the help of Maple and a little shell script. This allows + the Chebyshev polynomials to be of significantly lower degree (about 1/4) + compared to fitting the whole [0,1] interval with a single polynomial. */ + + +template +C10_HOST_DEVICE inline typename std::enable_if_t, T> +erfcx_y100(T y100) +{ + switch (static_cast(y100)) { +case 0: { +T t = 2*y100 - 1; +return 0.70878032454106438663e-3 + (0.71234091047026302958e-3 + (0.35779077297597742384e-5 + (0.17403143962587937815e-7 + (0.81710660047307788845e-10 + (0.36885022360434957634e-12 + 0.15917038551111111111e-14 * t) * t) * t) * t) * t) * t; +} +case 1: { +T t = 2*y100 - 3; +return 0.21479143208285144230e-2 + (0.72686402367379996033e-3 + (0.36843175430938995552e-5 + (0.18071841272149201685e-7 + (0.85496449296040325555e-10 + (0.38852037518534291510e-12 + 0.16868473576888888889e-14 * t) * t) * t) * t) * t) * t; +} +case 2: { +T t = 2*y100 - 5; +return 0.36165255935630175090e-2 + (0.74182092323555510862e-3 + (0.37948319957528242260e-5 + (0.18771627021793087350e-7 + (0.89484715122415089123e-10 + (0.40935858517772440862e-12 + 0.17872061464888888889e-14 * t) * t) * t) * t) * t) * t; +} +case 3: { +T t = 2*y100 - 7; +return 0.51154983860031979264e-2 + (0.75722840734791660540e-3 + (0.39096425726735703941e-5 + (0.19504168704300468210e-7 + (0.93687503063178993915e-10 + (0.43143925959079664747e-12 + 0.18939926435555555556e-14 * t) * t) * t) * t) * t) * t; +} +case 4: { +T t = 2*y100 - 9; +return 0.66457513172673049824e-2 + (0.77310406054447454920e-3 + (0.40289510589399439385e-5 + (0.20271233238288381092e-7 + (0.98117631321709100264e-10 + (0.45484207406017752971e-12 + 0.20076352213333333333e-14 * t) * t) * t) * t) * t) * t; +} +case 5: { +T t = 2*y100 - 11; +return 0.82082389970241207883e-2 + (0.78946629611881710721e-3 + (0.41529701552622656574e-5 + (0.21074693344544655714e-7 + (0.10278874108587317989e-9 + (0.47965201390613339638e-12 + 0.21285907413333333333e-14 * t) * t) * t) * t) * t) * t; +} +case 6: { +T t = 2*y100 - 13; +return 0.98039537275352193165e-2 + (0.80633440108342840956e-3 + (0.42819241329736982942e-5 + (0.21916534346907168612e-7 + (0.10771535136565470914e-9 + (0.50595972623692822410e-12 + 0.22573462684444444444e-14 * t) * t) * t) * t) * t) * t; +} +case 7: { +T t = 2*y100 - 15; +return 0.11433927298290302370e-1 + (0.82372858383196561209e-3 + (0.44160495311765438816e-5 + (0.22798861426211986056e-7 + (0.11291291745879239736e-9 + (0.53386189365816880454e-12 + 0.23944209546666666667e-14 * t) * t) * t) * t) * t) * t; +} +case 8: { +T t = 2*y100 - 17; +return 0.13099232878814653979e-1 + (0.84167002467906968214e-3 + (0.45555958988457506002e-5 + (0.23723907357214175198e-7 + (0.11839789326602695603e-9 + (0.56346163067550237877e-12 + 0.25403679644444444444e-14 * t) * t) * t) * t) * t) * t; +} +case 9: { +T t = 2*y100 - 19; +return 0.14800987015587535621e-1 + (0.86018092946345943214e-3 + (0.47008265848816866105e-5 + (0.24694040760197315333e-7 + (0.12418779768752299093e-9 + (0.59486890370320261949e-12 + 0.26957764568888888889e-14 * t) * t) * t) * t) * t) * t; +} +case 10: { +T t = 2*y100 - 21; +return 0.16540351739394069380e-1 + (0.87928458641241463952e-3 + (0.48520195793001753903e-5 + (0.25711774900881709176e-7 + (0.13030128534230822419e-9 + (0.62820097586874779402e-12 + 0.28612737351111111111e-14 * t) * t) * t) * t) * t) * t; +} +case 11: { +T t = 2*y100 - 23; +return 0.18318536789842392647e-1 + (0.89900542647891721692e-3 + (0.50094684089553365810e-5 + (0.26779777074218070482e-7 + (0.13675822186304615566e-9 + (0.66358287745352705725e-12 + 0.30375273884444444444e-14 * t) * t) * t) * t) * t) * t; +} +case 12: { +T t = 2*y100 - 25; +return 0.20136801964214276775e-1 + (0.91936908737673676012e-3 + (0.51734830914104276820e-5 + (0.27900878609710432673e-7 + (0.14357976402809042257e-9 + (0.70114790311043728387e-12 + 0.32252476000000000000e-14 * t) * t) * t) * t) * t) * t; +} +case 13: { +T t = 2*y100 - 27; +return 0.21996459598282740954e-1 + (0.94040248155366777784e-3 + (0.53443911508041164739e-5 + (0.29078085538049374673e-7 + (0.15078844500329731137e-9 + (0.74103813647499204269e-12 + 0.34251892320000000000e-14 * t) * t) * t) * t) * t) * t; +} +case 14: { +T t = 2*y100 - 29; +return 0.23898877187226319502e-1 + (0.96213386835900177540e-3 + (0.55225386998049012752e-5 + (0.30314589961047687059e-7 + (0.15840826497296335264e-9 + (0.78340500472414454395e-12 + 0.36381553564444444445e-14 * t) * t) * t) * t) * t) * t; +} +case 15: { +T t = 2*y100 - 31; +return 0.25845480155298518485e-1 + (0.98459293067820123389e-3 + (0.57082915920051843672e-5 + (0.31613782169164830118e-7 + (0.16646478745529630813e-9 + (0.82840985928785407942e-12 + 0.38649975768888888890e-14 * t) * t) * t) * t) * t) * t; +} +case 16: { +T t = 2*y100 - 33; +return 0.27837754783474696598e-1 + (0.10078108563256892757e-2 + (0.59020366493792212221e-5 + (0.32979263553246520417e-7 + (0.17498524159268458073e-9 + (0.87622459124842525110e-12 + 0.41066206488888888890e-14 * t) * t) * t) * t) * t) * t; +} +case 17: { +T t = 2*y100 - 35; +return 0.29877251304899307550e-1 + (0.10318204245057349310e-2 + (0.61041829697162055093e-5 + (0.34414860359542720579e-7 + (0.18399863072934089607e-9 + (0.92703227366365046533e-12 + 0.43639844053333333334e-14 * t) * t) * t) * t) * t) * t; +} +case 18: { +T t = 2*y100 - 37; +return 0.31965587178596443475e-1 + (0.10566560976716574401e-2 + (0.63151633192414586770e-5 + (0.35924638339521924242e-7 + (0.19353584758781174038e-9 + (0.98102783859889264382e-12 + 0.46381060817777777779e-14 * t) * t) * t) * t) * t) * t; +} +case 19: { +T t = 2*y100 - 39; +return 0.34104450552588334840e-1 + (0.10823541191350532574e-2 + (0.65354356159553934436e-5 + (0.37512918348533521149e-7 + (0.20362979635817883229e-9 + (0.10384187833037282363e-11 + 0.49300625262222222221e-14 * t) * t) * t) * t) * t) * t; +} +case 20: { +T t = 2*y100 - 41; +return 0.36295603928292425716e-1 + (0.11089526167995268200e-2 + (0.67654845095518363577e-5 + (0.39184292949913591646e-7 + (0.21431552202133775150e-9 + (0.10994259106646731797e-11 + 0.52409949102222222221e-14 * t) * t) * t) * t) * t) * t; +} +case 21: { +T t = 2*y100 - 43; +return 0.38540888038840509795e-1 + (0.11364917134175420009e-2 + (0.70058230641246312003e-5 + (0.40943644083718586939e-7 + (0.22563034723692881631e-9 + (0.11642841011361992885e-11 + 0.55721092871111111110e-14 * t) * t) * t) * t) * t) * t; +} +case 22: { +T t = 2*y100 - 45; +return 0.40842225954785960651e-1 + (0.11650136437945673891e-2 + (0.72569945502343006619e-5 + (0.42796161861855042273e-7 + (0.23761401711005024162e-9 + (0.12332431172381557035e-11 + 0.59246802364444444445e-14 * t) * t) * t) * t) * t) * t; +} +case 23: { +T t = 2*y100 - 47; +return 0.43201627431540222422e-1 + (0.11945628793917272199e-2 + (0.75195743532849206263e-5 + (0.44747364553960993492e-7 + (0.25030885216472953674e-9 + (0.13065684400300476484e-11 + 0.63000532853333333334e-14 * t) * t) * t) * t) * t) * t; +} +case 24: { +T t = 2*y100 - 49; +return 0.45621193513810471438e-1 + (0.12251862608067529503e-2 + (0.77941720055551920319e-5 + (0.46803119830954460212e-7 + (0.26375990983978426273e-9 + (0.13845421370977119765e-11 + 0.66996477404444444445e-14 * t) * t) * t) * t) * t) * t; +} +case 25: { +T t = 2*y100 - 51; +return 0.48103121413299865517e-1 + (0.12569331386432195113e-2 + (0.80814333496367673980e-5 + (0.48969667335682018324e-7 + (0.27801515481905748484e-9 + (0.14674637611609884208e-11 + 0.71249589351111111110e-14 * t) * t) * t) * t) * t) * t; +} +case 26: { +T t = 2*y100 - 53; +return 0.50649709676983338501e-1 + (0.12898555233099055810e-2 + (0.83820428414568799654e-5 + (0.51253642652551838659e-7 + (0.29312563849675507232e-9 + (0.15556512782814827846e-11 + 0.75775607822222222221e-14 * t) * t) * t) * t) * t) * t; +} +case 27: { +T t = 2*y100 - 55; +return 0.53263363664388864181e-1 + (0.13240082443256975769e-2 + (0.86967260015007658418e-5 + (0.53662102750396795566e-7 + (0.30914568786634796807e-9 + (0.16494420240828493176e-11 + 0.80591079644444444445e-14 * t) * t) * t) * t) * t) * t; +} +case 28: { +T t = 2*y100 - 57; +return 0.55946601353500013794e-1 + (0.13594491197408190706e-2 + (0.90262520233016380987e-5 + (0.56202552975056695376e-7 + (0.32613310410503135996e-9 + (0.17491936862246367398e-11 + 0.85713381688888888890e-14 * t) * t) * t) * t) * t) * t; +} +case 29: { +T t = 2*y100 - 59; +return 0.58702059496154081813e-1 + (0.13962391363223647892e-2 + (0.93714365487312784270e-5 + (0.58882975670265286526e-7 + (0.34414937110591753387e-9 + (0.18552853109751857859e-11 + 0.91160736711111111110e-14 * t) * t) * t) * t) * t) * t; +} +case 30: { +T t = 2*y100 - 61; +return 0.61532500145144778048e-1 + (0.14344426411912015247e-2 + (0.97331446201016809696e-5 + (0.61711860507347175097e-7 + (0.36325987418295300221e-9 + (0.19681183310134518232e-11 + 0.96952238400000000000e-14 * t) * t) * t) * t) * t) * t; +} +case 31: { +T t = 2*y100 - 63; +return 0.64440817576653297993e-1 + (0.14741275456383131151e-2 + (0.10112293819576437838e-4 + (0.64698236605933246196e-7 + (0.38353412915303665586e-9 + (0.20881176114385120186e-11 + 0.10310784480000000000e-13 * t) * t) * t) * t) * t) * t; +} +case 32: { +T t = 2*y100 - 65; +return 0.67430045633130393282e-1 + (0.15153655418916540370e-2 + (0.10509857606888328667e-4 + (0.67851706529363332855e-7 + (0.40504602194811140006e-9 + (0.22157325110542534469e-11 + 0.10964842115555555556e-13 * t) * t) * t) * t) * t) * t; +} +case 33: { +T t = 2*y100 - 67; +return 0.70503365513338850709e-1 + (0.15582323336495709827e-2 + (0.10926868866865231089e-4 + (0.71182482239613507542e-7 + (0.42787405890153386710e-9 + (0.23514379522274416437e-11 + 0.11659571751111111111e-13 * t) * t) * t) * t) * t) * t; +} +case 34: { +T t = 2*y100 - 69; +return 0.73664114037944596353e-1 + (0.16028078812438820413e-2 + (0.11364423678778207991e-4 + (0.74701423097423182009e-7 + (0.45210162777476488324e-9 + (0.24957355004088569134e-11 + 0.12397238257777777778e-13 * t) * t) * t) * t) * t) * t; +} +case 35: { +T t = 2*y100 - 71; +return 0.76915792420819562379e-1 + (0.16491766623447889354e-2 + (0.11823685320041302169e-4 + (0.78420075993781544386e-7 + (0.47781726956916478925e-9 + (0.26491544403815724749e-11 + 0.13180196462222222222e-13 * t) * t) * t) * t) * t) * t; +} +case 36: { +T t = 2*y100 - 73; +return 0.80262075578094612819e-1 + (0.16974279491709504117e-2 + (0.12305888517309891674e-4 + (0.82350717698979042290e-7 + (0.50511496109857113929e-9 + (0.28122528497626897696e-11 + 0.14010889635555555556e-13 * t) * t) * t) * t) * t) * t; +} +case 37: { +T t = 2*y100 - 75; +return 0.83706822008980357446e-1 + (0.17476561032212656962e-2 + (0.12812343958540763368e-4 + (0.86506399515036435592e-7 + (0.53409440823869467453e-9 + (0.29856186620887555043e-11 + 0.14891851591111111111e-13 * t) * t) * t) * t) * t) * t; +} +case 38: { +T t = 2*y100 - 77; +return 0.87254084284461718231e-1 + (0.17999608886001962327e-2 + (0.13344443080089492218e-4 + (0.90900994316429008631e-7 + (0.56486134972616465316e-9 + (0.31698707080033956934e-11 + 0.15825697795555555556e-13 * t) * t) * t) * t) * t) * t; +} +case 39: { +T t = 2*y100 - 79; +return 0.90908120182172748487e-1 + (0.18544478050657699758e-2 + (0.13903663143426120077e-4 + (0.95549246062549906177e-7 + (0.59752787125242054315e-9 + (0.33656597366099099413e-11 + 0.16815130613333333333e-13 * t) * t) * t) * t) * t) * t; +} +case 40: { +T t = 2*y100 - 81; +return 0.94673404508075481121e-1 + (0.19112284419887303347e-2 + (0.14491572616545004930e-4 + (0.10046682186333613697e-6 + (0.63221272959791000515e-9 + (0.35736693975589130818e-11 + 0.17862931591111111111e-13 * t) * t) * t) * t) * t) * t; +} +case 41: { +T t = 2*y100 - 83; +return 0.98554641648004456555e-1 + (0.19704208544725622126e-2 + (0.15109836875625443935e-4 + (0.10567036667675984067e-6 + (0.66904168640019354565e-9 + (0.37946171850824333014e-11 + 0.18971959040000000000e-13 * t) * t) * t) * t) * t) * t; +} +case 42: { +T t = 2*y100 - 85; +return 0.10255677889470089531e0 + (0.20321499629472857418e-2 + (0.15760224242962179564e-4 + (0.11117756071353507391e-6 + (0.70814785110097658502e-9 + (0.40292553276632563925e-11 + 0.20145143075555555556e-13 * t) * t) * t) * t) * t) * t; +} +case 43: { +T t = 2*y100 - 87; +return 0.10668502059865093318e0 + (0.20965479776148731610e-2 + (0.16444612377624983565e-4 + (0.11700717962026152749e-6 + (0.74967203250938418991e-9 + (0.42783716186085922176e-11 + 0.21385479360000000000e-13 * t) * t) * t) * t) * t) * t; +} +case 44: { +T t = 2*y100 - 89; +return 0.11094484319386444474e0 + (0.21637548491908170841e-2 + (0.17164995035719657111e-4 + (0.12317915750735938089e-6 + (0.79376309831499633734e-9 + (0.45427901763106353914e-11 + 0.22696025653333333333e-13 * t) * t) * t) * t) * t) * t; +} +case 45: { +T t = 2*y100 - 91; +return 0.11534201115268804714e0 + (0.22339187474546420375e-2 + (0.17923489217504226813e-4 + (0.12971465288245997681e-6 + (0.84057834180389073587e-9 + (0.48233721206418027227e-11 + 0.24079890062222222222e-13 * t) * t) * t) * t) * t) * t; +} +case 46: { +T t = 2*y100 - 93; +return 0.11988259392684094740e0 + (0.23071965691918689601e-2 + (0.18722342718958935446e-4 + (0.13663611754337957520e-6 + (0.89028385488493287005e-9 + (0.51210161569225846701e-11 + 0.25540227111111111111e-13 * t) * t) * t) * t) * t) * t; +} +case 47: { +T t = 2*y100 - 95; +return 0.12457298393509812907e0 + (0.23837544771809575380e-2 + (0.19563942105711612475e-4 + (0.14396736847739470782e-6 + (0.94305490646459247016e-9 + (0.54366590583134218096e-11 + 0.27080225920000000000e-13 * t) * t) * t) * t) * t) * t; +} +case 48: { +T t = 2*y100 - 97; +return 0.12941991566142438816e0 + (0.24637684719508859484e-2 + (0.20450821127475879816e-4 + (0.15173366280523906622e-6 + (0.99907632506389027739e-9 + (0.57712760311351625221e-11 + 0.28703099555555555556e-13 * t) * t) * t) * t) * t) * t; +} +case 49: { +T t = 2*y100 - 99; +return 0.13443048593088696613e0 + (0.25474249981080823877e-2 + (0.21385669591362915223e-4 + (0.15996177579900443030e-6 + (0.10585428844575134013e-8 + (0.61258809536787882989e-11 + 0.30412080142222222222e-13 * t) * t) * t) * t) * t) * t; +} +case 50: { +T t = 2*y100 - 101; +return 0.13961217543434561353e0 + (0.26349215871051761416e-2 + (0.22371342712572567744e-4 + (0.16868008199296822247e-6 + (0.11216596910444996246e-8 + (0.65015264753090890662e-11 + 0.32210394506666666666e-13 * t) * t) * t) * t) * t) * t; +} +case 51: { +T t = 2*y100 - 103; +return 0.14497287157673800690e0 + (0.27264675383982439814e-2 + (0.23410870961050950197e-4 + (0.17791863939526376477e-6 + (0.11886425714330958106e-8 + (0.68993039665054288034e-11 + 0.34101266222222222221e-13 * t) * t) * t) * t) * t) * t; +} +case 52: { +T t = 2*y100 - 105; +return 0.15052089272774618151e0 + (0.28222846410136238008e-2 + (0.24507470422713397006e-4 + (0.18770927679626136909e-6 + (0.12597184587583370712e-8 + (0.73203433049229821618e-11 + 0.36087889048888888890e-13 * t) * t) * t) * t) * t) * t; +} +case 53: { +T t = 2*y100 - 107; +return 0.15626501395774612325e0 + (0.29226079376196624949e-2 + (0.25664553693768450545e-4 + (0.19808568415654461964e-6 + (0.13351257759815557897e-8 + (0.77658124891046760667e-11 + 0.38173420035555555555e-13 * t) * t) * t) * t) * t) * t; +} +case 54: { +T t = 2*y100 - 109; +return 0.16221449434620737567e0 + (0.30276865332726475672e-2 + (0.26885741326534564336e-4 + (0.20908350604346384143e-6 + (0.14151148144240728728e-8 + (0.82369170665974313027e-11 + 0.40360957457777777779e-13 * t) * t) * t) * t) * t) * t; +} +case 55: { +T t = 2*y100 - 111; +return 0.16837910595412130659e0 + (0.31377844510793082301e-2 + (0.28174873844911175026e-4 + (0.22074043807045782387e-6 + (0.14999481055996090039e-8 + (0.87348993661930809254e-11 + 0.42653528977777777779e-13 * t) * t) * t) * t) * t) * t; +} +case 56: { +T t = 2*y100 - 113; +return 0.17476916455659369953e0 + (0.32531815370903068316e-2 + (0.29536024347344364074e-4 + (0.23309632627767074202e-6 + (0.15899007843582444846e-8 + (0.92610375235427359475e-11 + 0.45054073102222222221e-13 * t) * t) * t) * t) * t) * t; +} +case 57: { +T t = 2*y100 - 115; +return 0.18139556223643701364e0 + (0.33741744168096996041e-2 + (0.30973511714709500836e-4 + (0.24619326937592290996e-6 + (0.16852609412267750744e-8 + (0.98166442942854895573e-11 + 0.47565418097777777779e-13 * t) * t) * t) * t) * t) * t; +} +case 58: { +T t = 2*y100 - 117; +return 0.18826980194443664549e0 + (0.35010775057740317997e-2 + (0.32491914440014267480e-4 + (0.26007572375886319028e-6 + (0.17863299617388376116e-8 + (0.10403065638343878679e-10 + 0.50190265831111111110e-13 * t) * t) * t) * t) * t) * t; +} +case 59: { +T t = 2*y100 - 119; +return 0.19540403413693967350e0 + (0.36342240767211326315e-2 + (0.34096085096200907289e-4 + (0.27479061117017637474e-6 + (0.18934228504790032826e-8 + (0.11021679075323598664e-10 + 0.52931171733333333334e-13 * t) * t) * t) * t) * t) * t; +} +case 60: { +T t = 2*y100 - 121; +return 0.20281109560651886959e0 + (0.37739673859323597060e-2 + (0.35791165457592409054e-4 + (0.29038742889416172404e-6 + (0.20068685374849001770e-8 + (0.11673891799578381999e-10 + 0.55790523093333333334e-13 * t) * t) * t) * t) * t) * t; +} +case 61: { +T t = 2*y100 - 123; +return 0.21050455062669334978e0 + (0.39206818613925652425e-2 + (0.37582602289680101704e-4 + (0.30691836231886877385e-6 + (0.21270101645763677824e-8 + (0.12361138551062899455e-10 + 0.58770520160000000000e-13 * t) * t) * t) * t) * t) * t; +} +case 62: { +T t = 2*y100 - 125; +return 0.21849873453703332479e0 + (0.40747643554689586041e-2 + (0.39476163820986711501e-4 + (0.32443839970139918836e-6 + (0.22542053491518680200e-8 + (0.13084879235290858490e-10 + 0.61873153262222222221e-13 * t) * t) * t) * t) * t) * t; +} +case 63: { +T t = 2*y100 - 127; +return 0.22680879990043229327e0 + (0.42366354648628516935e-2 + (0.41477956909656896779e-4 + (0.34300544894502810002e-6 + (0.23888264229264067658e-8 + (0.13846596292818514601e-10 + 0.65100183751111111110e-13 * t) * t) * t) * t) * t) * t; +} +case 64: { +T t = 2*y100 - 129; +return 0.23545076536988703937e0 + (0.44067409206365170888e-2 + (0.43594444916224700881e-4 + (0.36268045617760415178e-6 + (0.25312606430853202748e-8 + (0.14647791812837903061e-10 + 0.68453122631111111110e-13 * t) * t) * t) * t) * t) * t; +} +case 65: { +T t = 2*y100 - 131; +return 0.24444156740777432838e0 + (0.45855530511605787178e-2 + (0.45832466292683085475e-4 + (0.38352752590033030472e-6 + (0.26819103733055603460e-8 + (0.15489984390884756993e-10 + 0.71933206364444444445e-13 * t) * t) * t) * t) * t) * t; +} +case 66: { +T t = 2*y100 - 133; +return 0.25379911500634264643e0 + (0.47735723208650032167e-2 + (0.48199253896534185372e-4 + (0.40561404245564732314e-6 + (0.28411932320871165585e-8 + (0.16374705736458320149e-10 + 0.75541379822222222221e-13 * t) * t) * t) * t) * t) * t; +} +case 67: { +T t = 2*y100 - 135; +return 0.26354234756393613032e0 + (0.49713289477083781266e-2 + (0.50702455036930367504e-4 + (0.42901079254268185722e-6 + (0.30095422058900481753e-8 + (0.17303497025347342498e-10 + 0.79278273368888888890e-13 * t) * t) * t) * t) * t) * t; +} +case 68: { +T t = 2*y100 - 137; +return 0.27369129607732343398e0 + (0.51793846023052643767e-2 + (0.53350152258326602629e-4 + (0.45379208848865015485e-6 + (0.31874057245814381257e-8 + (0.18277905010245111046e-10 + 0.83144182364444444445e-13 * t) * t) * t) * t) * t) * t; +} +case 69: { +T t = 2*y100 - 139; +return 0.28426714781640316172e0 + (0.53983341916695141966e-2 + (0.56150884865255810638e-4 + (0.48003589196494734238e-6 + (0.33752476967570796349e-8 + (0.19299477888083469086e-10 + 0.87139049137777777779e-13 * t) * t) * t) * t) * t) * t; +} +case 70: { +T t = 2*y100 - 141; +return 0.29529231465348519920e0 + (0.56288077305420795663e-2 + (0.59113671189913307427e-4 + (0.50782393781744840482e-6 + (0.35735475025851713168e-8 + (0.20369760937017070382e-10 + 0.91262442613333333334e-13 * t) * t) * t) * t) * t) * t; +} +case 71: { +T t = 2*y100 - 143; +return 0.30679050522528838613e0 + (0.58714723032745403331e-2 + (0.62248031602197686791e-4 + (0.53724185766200945789e-6 + (0.37827999418960232678e-8 + (0.21490291930444538307e-10 + 0.95513539182222222221e-13 * t) * t) * t) * t) * t) * t; +} +case 72: { +T t = 2*y100 - 145; +return 0.31878680111173319425e0 + (0.61270341192339103514e-2 + (0.65564012259707640976e-4 + (0.56837930287837738996e-6 + (0.40035151353392378882e-8 + (0.22662596341239294792e-10 + 0.99891109760000000000e-13 * t) * t) * t) * t) * t) * t; +} +case 73: { +T t = 2*y100 - 147; +return 0.33130773722152622027e0 + (0.63962406646798080903e-2 + (0.69072209592942396666e-4 + (0.60133006661885941812e-6 + (0.42362183765883466691e-8 + (0.23888182347073698382e-10 + 0.10439349811555555556e-12 * t) * t) * t) * t) * t) * t; +} +case 74: { +T t = 2*y100 - 149; +return 0.34438138658041336523e0 + (0.66798829540414007258e-2 + (0.72783795518603561144e-4 + (0.63619220443228800680e-6 + (0.44814499336514453364e-8 + (0.25168535651285475274e-10 + 0.10901861383111111111e-12 * t) * t) * t) * t) * t) * t; +} +case 75: { +T t = 2*y100 - 151; +return 0.35803744972380175583e0 + (0.69787978834882685031e-2 + (0.76710543371454822497e-4 + (0.67306815308917386747e-6 + (0.47397647975845228205e-8 + (0.26505114141143050509e-10 + 0.11376390933333333333e-12 * t) * t) * t) * t) * t) * t; +} +case 76: { +T t = 2*y100 - 153; +return 0.37230734890119724188e0 + (0.72938706896461381003e-2 + (0.80864854542670714092e-4 + (0.71206484718062688779e-6 + (0.50117323769745883805e-8 + (0.27899342394100074165e-10 + 0.11862637614222222222e-12 * t) * t) * t) * t) * t) * t; +} +case 77: { +T t = 2*y100 - 155; +return 0.38722432730555448223e0 + (0.76260375162549802745e-2 + (0.85259785810004603848e-4 + (0.75329383305171327677e-6 + (0.52979361368388119355e-8 + (0.29352606054164086709e-10 + 0.12360253370666666667e-12 * t) * t) * t) * t) * t) * t; +} +case 78: { +T t = 2*y100 - 157; +return 0.40282355354616940667e0 + (0.79762880915029728079e-2 + (0.89909077342438246452e-4 + (0.79687137961956194579e-6 + (0.55989731807360403195e-8 + (0.30866246101464869050e-10 + 0.12868841946666666667e-12 * t) * t) * t) * t) * t) * t; +} +case 79: { +T t = 2*y100 - 159; +return 0.41914223158913787649e0 + (0.83456685186950463538e-2 + (0.94827181359250161335e-4 + (0.84291858561783141014e-6 + (0.59154537751083485684e-8 + (0.32441553034347469291e-10 + 0.13387957943111111111e-12 * t) * t) * t) * t) * t) * t; +} +case 80: { +T t = 2*y100 - 161; +return 0.43621971639463786896e0 + (0.87352841828289495773e-2 + (0.10002929142066799966e-3 + (0.89156148280219880024e-6 + (0.62480008150788597147e-8 + (0.34079760983458878910e-10 + 0.13917107176888888889e-12 * t) * t) * t) * t) * t) * t; +} +case 81: { +T t = 2*y100 - 163; +return 0.45409763548534330981e0 + (0.91463027755548240654e-2 + (0.10553137232446167258e-3 + (0.94293113464638623798e-6 + (0.65972492312219959885e-8 + (0.35782041795476563662e-10 + 0.14455745872000000000e-12 * t) * t) * t) * t) * t) * t; +} +case 82: { +T t = 2*y100 - 165; +return 0.47282001668512331468e0 + (0.95799574408860463394e-2 + (0.11135019058000067469e-3 + (0.99716373005509038080e-6 + (0.69638453369956970347e-8 + (0.37549499088161345850e-10 + 0.15003280712888888889e-12 * t) * t) * t) * t) * t) * t; +} +case 83: { +T t = 2*y100 - 167; +return 0.49243342227179841649e0 + (0.10037550043909497071e-1 + (0.11750334542845234952e-3 + (0.10544006716188967172e-5 + (0.73484461168242224872e-8 + (0.39383162326435752965e-10 + 0.15559069118222222222e-12 * t) * t) * t) * t) * t) * t; +} +case 84: { +T t = 2*y100 - 169; +return 0.51298708979209258326e0 + (0.10520454564612427224e-1 + (0.12400930037494996655e-3 + (0.11147886579371265246e-5 + (0.77517184550568711454e-8 + (0.41283980931872622611e-10 + 0.16122419680000000000e-12 * t) * t) * t) * t) * t) * t; +} +case 85: { +T t = 2*y100 - 171; +return 0.53453307979101369843e0 + (0.11030120618800726938e-1 + (0.13088741519572269581e-3 + (0.11784797595374515432e-5 + (0.81743383063044825400e-8 + (0.43252818449517081051e-10 + 0.16692592640000000000e-12 * t) * t) * t) * t) * t) * t; +} +case 86: { +T t = 2*y100 - 173; +return 0.55712643071169299478e0 + (0.11568077107929735233e-1 + (0.13815797838036651289e-3 + (0.12456314879260904558e-5 + (0.86169898078969313597e-8 + (0.45290446811539652525e-10 + 0.17268801084444444444e-12 * t) * t) * t) * t) * t) * t; +} +case 87: { +T t = 2*y100 - 175; +return 0.58082532122519320968e0 + (0.12135935999503877077e-1 + (0.14584223996665838559e-3 + (0.13164068573095710742e-5 + (0.90803643355106020163e-8 + (0.47397540713124619155e-10 + 0.17850211608888888889e-12 * t) * t) * t) * t) * t) * t; +} +case 88: { +T t = 2*y100 - 177; +return 0.60569124025293375554e0 + (0.12735396239525550361e-1 + (0.15396244472258863344e-3 + (0.13909744385382818253e-5 + (0.95651595032306228245e-8 + (0.49574672127669041550e-10 + 0.18435945564444444444e-12 * t) * t) * t) * t) * t) * t; +} +case 89: { +T t = 2*y100 - 179; +return 0.63178916494715716894e0 + (0.13368247798287030927e-1 + (0.16254186562762076141e-3 + (0.14695084048334056083e-5 + (0.10072078109604152350e-7 + (0.51822304995680707483e-10 + 0.19025081422222222222e-12 * t) * t) * t) * t) * t) * t; +} +case 90: { +T t = 2*y100 - 181; +return 0.65918774689725319200e0 + (0.14036375850601992063e-1 + (0.17160483760259706354e-3 + (0.15521885688723188371e-5 + (0.10601827031535280590e-7 + (0.54140790105837520499e-10 + 0.19616655146666666667e-12 * t) * t) * t) * t) * t) * t; +} +case 91: { +T t = 2*y100 - 183; +return 0.68795950683174433822e0 + (0.14741765091365869084e-1 + (0.18117679143520433835e-3 + (0.16392004108230585213e-5 + (0.11155116068018043001e-7 + (0.56530360194925690374e-10 + 0.20209663662222222222e-12 * t) * t) * t) * t) * t) * t; +} +case 92: { +T t = 2*y100 - 185; +return 0.71818103808729967036e0 + (0.15486504187117112279e-1 + (0.19128428784550923217e-3 + (0.17307350969359975848e-5 + (0.11732656736113607751e-7 + (0.58991125287563833603e-10 + 0.20803065333333333333e-12 * t) * t) * t) * t) * t) * t; +} +case 93: { +T t = 2*y100 - 187; +return 0.74993321911726254661e0 + (0.16272790364044783382e-1 + (0.20195505163377912645e-3 + (0.18269894883203346953e-5 + (0.12335161021630225535e-7 + (0.61523068312169087227e-10 + 0.21395783431111111111e-12 * t) * t) * t) * t) * t) * t; +} +case 94: { +T t = 2*y100 - 189; +return 0.78330143531283492729e0 + (0.17102934132652429240e-1 + (0.21321800585063327041e-3 + (0.19281661395543913713e-5 + (0.12963340087354341574e-7 + (0.64126040998066348872e-10 + 0.21986708942222222222e-12 * t) * t) * t) * t) * t) * t; +} +case 95: { +T t = 2*y100 - 191; +return 0.81837581041023811832e0 + (0.17979364149044223802e-1 + (0.22510330592753129006e-3 + (0.20344732868018175389e-5 + (0.13617902941839949718e-7 + (0.66799760083972474642e-10 + 0.22574701262222222222e-12 * t) * t) * t) * t) * t) * t; +} +case 96: { +T t = 2*y100 - 193; +return 0.85525144775685126237e0 + (0.18904632212547561026e-1 + (0.23764237370371255638e-3 + (0.21461248251306387979e-5 + (0.14299555071870523786e-7 + (0.69543803864694171934e-10 + 0.23158593688888888889e-12 * t) * t) * t) * t) * t) * t; +} +case 97: { +T t = 2*y100 - 195; +return 0.89402868170849933734e0 + (0.19881418399127202569e-1 + (0.25086793128395995798e-3 + (0.22633402747585233180e-5 + (0.15008997042116532283e-7 + (0.72357609075043941261e-10 + 0.23737194737777777778e-12 * t) * t) * t) * t) * t) * t; +} +case 98: { +T t = 2*y100 - 197; +return 0.93481333942870796363e0 + (0.20912536329780368893e-1 + (0.26481403465998477969e-3 + (0.23863447359754921676e-5 + (0.15746923065472184451e-7 + (0.75240468141720143653e-10 + 0.24309291271111111111e-12 * t) * t) * t) * t) * t) * t; +} +case 99: { +T t = 2*y100 - 199; +return 0.97771701335885035464e0 + (0.22000938572830479551e-1 + (0.27951610702682383001e-3 + (0.25153688325245314530e-5 + (0.16514019547822821453e-7 + (0.78191526829368231251e-10 + 0.24873652355555555556e-12 * t) * t) * t) * t) * t) * t; +} + } + // we only get here if y = 1, i.e. |x| < 4*eps, in which case + // erfcx is within 1e-15 of 1.. + return 1.0; +} + +template +C10_HOST_DEVICE inline typename std::enable_if_t, T> +calc_erfcx(T x) +{ + if (at::_isnan(x)) { + return x; + } + + if (x >= 0) { + if (x > 50) { // continued-fraction expansion is faster + const T ispi = 0.56418958354775628694807945156; // 1 / sqrt(pi) + if (x > 5e7) { // 1-term expansion, important to avoid overflow + return ispi / x; + } + /* 5-term expansion (rely on compiler for CSE), simplified from: + ispi / (x+0.5/(x+1/(x+1.5/(x+2/x)))) */ + return ispi*((x*x) * (x*x+4.5) + 2) / (x * ((x*x) * (x*x+5) + 3.75)); + } + return erfcx_y100(400/(4+x)); + } + else { + if (x < -26.7) { + return std::numeric_limits::infinity(); + } + else if (x < -6.1) { + return 2*exp(x*x); + } + else { + return 2*exp(x*x) - erfcx_y100(400/(4-x)); + } + } +} + +/* + * Logarithm of Gaussian cumulative distribution function. + + * This implementation of log_ndtr and its helper functions + * follow SciPy's implementation + * See NOTICE for the licenses. + */ +template +inline C10_HOST_DEVICE T calc_log_ndtr(T x) { + T t = x * c10::frac_sqrt_2; + if (x < T{-1.0}) { + return std::log(calc_erfcx(-t) / 2) - t * t; + } else { + return std::log1p(-std::erfc(t) / 2); + } +} + +template +inline C10_HOST_DEVICE T airy_ai_forward(T x) { + static const T AN[] = { + +3.46538101525629032477e-01, + +1.20075952739645805542e+01, + +7.62796053615234516538e+01, + +1.68089224934630576269e+02, + +1.59756391350164413639e+02, + +7.05360906840444183113e+01, + +1.40264691163389668864e+01, + +9.99999999999999995305e-01, + }; + + static const T AD[] = { + +5.67594532638770212846e-01, + +1.47562562584847203173e+01, + +8.45138970141474626562e+01, + +1.77318088145400459522e+02, + +1.64234692871529701831e+02, + +7.14778400825575695274e+01, + +1.40959135607834029598e+01, + +1.00000000000000000470e+00, + }; + + static const T AFN[] = { + -1.31696323418331795333e-01, + -6.26456544431912369773e-01, + -6.93158036036933542233e-01, + -2.79779981545119124951e-01, + -4.91900132609500318020e-02, + -4.06265923594885404393e-03, + -1.59276496239262096340e-04, + -2.77649108155232920844e-06, + -1.67787698489114633780e-08, + }; + + static const T AFD[] = { + +1.33560420706553243746e+01, + +3.26825032795224613948e+01, + +2.67367040941499554804e+01, + +9.18707402907259625840e+00, + +1.47529146771666414581e+00, + +1.15687173795188044134e-01, + +4.40291641615211203805e-03, + +7.54720348287414296618e-05, + +4.51850092970580378464e-07, + }; + + static const T AGN[] = { + +1.97339932091685679179e-02, + +3.91103029615688277255e-01, + +1.06579897599595591108e+00, + +9.39169229816650230044e-01, + +3.51465656105547619242e-01, + +6.33888919628925490927e-02, + +5.85804113048388458567e-03, + +2.82851600836737019778e-04, + +6.98793669997260967291e-06, + +8.11789239554389293311e-08, + +3.41551784765923618484e-10, + }; + + static const T AGD[] = { + +9.30892908077441974853e+00, + +1.98352928718312140417e+01, + +1.55646628932864612953e+01, + +5.47686069422975497931e+00, + +9.54293611618961883998e-01, + +8.64580826352392193095e-02, + +4.12656523824222607191e-03, + +1.01259085116509135510e-04, + +1.17166733214413521882e-06, + +4.91834570062930015649e-09, + }; + + int domain_flag = 0; + + T ai = T(0.0); + + if (std::isinf(x)) { + return std::numeric_limits::quiet_NaN(); + } + + if (x > T(103.892)) { + return T(0.0); + } + + T f; + T g; + T k; + + if (x < T(-2.09)) { + T z = T(1.0) / (T(-2.0) * x * std::sqrt(-x) / T(3.0)); + + T afn = 0.0; + + for (uint8_t index = 0; index <= 8; index++) { + afn = afn * (z * z) + AFN[index]; + } + + T afd = 0.0; + + for (uint8_t index = 0; index <= 8; index++) { + afd = afd * (z * z) + AFD[index]; + } + + T agn = 0.0; + + for (uint8_t index = 0; index <= 10 + 0; index++) { + agn = agn * (z * z) + AGN[index]; + } + + T agd = 0.0; + + for (uint8_t index = 0; index <= 10 - 1; index++) { + agd = agd * (z * z) + AGD[index]; + } + + T t = T(-2.0) * x * std::sqrt(-x) / T(3.0) + T(0.25) * c10::pi; + + return T(5.64189583547756286948e-01) / std::sqrt(std::sqrt(-x)) * (std::sin(t) * (T(1.0) + z * z * afn / afd) - std::cos(t) * (z * agn / agd)); + } + + if (x >= T(2.09)) { + domain_flag = 5; + + T zeta = T(2.0) * x * std::sqrt(x) / T(3.0); + + T an = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + an = an * (T(1.0) / zeta) + AN[index]; + } + + T ad = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + ad = ad * (T(1.0) / zeta) + AD[index]; + } + + ai = T(5.64189583547756286948e-01) * (an / ad) / (T(2.0) * std::sqrt(std::sqrt(x)) * std::exp(zeta)); + + if (x > T(8.3203353)) { + return ai; + } + } + + f = 1.0; + g = x; + k = 1.0; + + T m = 1.0; + T n = x; + T t = 1.0; + T z = x * x * x; + + while (t > std::numeric_limits::epsilon()) { + m *= z; + k += T(1.0); + m /= k; + n *= z; + k += T(1.0); + n /= k; + m /= k; + f += m; + k += T(1.0); + n /= k; + g += n; + + t = std::abs(m / f); + } + + if ((domain_flag & 1) == 0) { + return T(0.355028053887817239260) * f - T(0.258819403792806798405) * g; + } + + return ai; +} // T airy_ai(T x) + +template +inline C10_HOST_DEVICE T bessel_j0_forward(T x) { + static const T PP[] = { + +7.96936729297347051624e-04, + +8.28352392107440799803e-02, + +1.23953371646414299388e+00, + +5.44725003058768775090e+00, + +8.74716500199817011941e+00, + +5.30324038235394892183e+00, + +9.99999999999999997821e-01, + }; + + static const T PQ[] = { + +9.24408810558863637013e-04, + +8.56288474354474431428e-02, + +1.25352743901058953537e+00, + +5.47097740330417105182e+00, + +8.76190883237069594232e+00, + +5.30605288235394617618e+00, + +1.00000000000000000218e+00, + }; + + static const T QP[] = { + -1.13663838898469149931e-02, + -1.28252718670509318512e+00, + -1.95539544257735972385e+01, + -9.32060152123768231369e+01, + -1.77681167980488050595e+02, + -1.47077505154951170175e+02, + -5.14105326766599330220e+01, + -6.05014350600728481186e+00, + }; + + static const T QQ[] = { + +6.43178256118178023184e+01, + +8.56430025976980587198e+02, + +3.88240183605401609683e+03, + +7.24046774195652478189e+03, + +5.93072701187316984827e+03, + +2.06209331660327847417e+03, + +2.42005740240291393179e+02, + }; + + static const T RP[] = { + -4.79443220978201773821e+09, + +1.95617491946556577543e+12, + -2.49248344360967716204e+14, + +9.70862251047306323952e+15, + }; + + static const T RQ[] = { + +4.99563147152651017219e+02, + +1.73785401676374683123e+05, + +4.84409658339962045305e+07, + +1.11855537045356834862e+10, + +2.11277520115489217587e+12, + +3.10518229857422583814e+14, + +3.18121955943204943306e+16, + +1.71086294081043136091e+18, + }; + + if (x < T(0)) { + x = -x; + } + + if (x <= T(5.0)) { + if (x < T(0.00001)) { + return T(1.0) - x * x / T(4.0); + } + + T rp = 0.0; + + for (uint8_t index = 0; index <= 3; index++) { + rp = rp * (x * x) + RP[index]; + } + + T rq = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + rq = rq * (x * x) + RQ[index]; + } + + return (x * x - T(5.78318596294678452118e+00)) * (x * x - T(3.04712623436620863991e+01)) * rp / rq; + } + + T pp = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pp = pp * (T(25.0) / (x * x)) + PP[index]; + } + + T pq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pq = pq * (T(25.0) / (x * x)) + PQ[index]; + } + + T qp = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + qp = qp * (T(25.0) / (x * x)) + QP[index]; + } + + T qq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + qq = qq * (T(25.0) / (x * x)) + QQ[index]; + } + + return (pp / pq * std::cos(x - T(0.785398163397448309615660845819875721)) - T(5.0) / x * (qp / qq) * std::sin(x - T(0.785398163397448309615660845819875721))) * T(0.797884560802865355879892119868763737) / std::sqrt(x); +} // bessel_j0_forward(T x) + +template +inline C10_HOST_DEVICE T bessel_j1_forward(T x) { + static const T PP[] = { + +7.62125616208173112003e-04, + +7.31397056940917570436e-02, + +1.12719608129684925192e+00, + +5.11207951146807644818e+00, + +8.42404590141772420927e+00, + +5.21451598682361504063e+00, + +1.00000000000000000254e+00, + }; + + static const T PQ[] = { + +5.71323128072548699714e-04, + +6.88455908754495404082e-02, + +1.10514232634061696926e+00, + +5.07386386128601488557e+00, + +8.39985554327604159757e+00, + +5.20982848682361821619e+00, + +9.99999999999999997461e-01, + }; + + static const T QP[] = { + +5.10862594750176621635e-02, + +4.98213872951233449420e+00, + +7.58238284132545283818e+01, + +3.66779609360150777800e+02, + +7.10856304998926107277e+02, + +5.97489612400613639965e+02, + +2.11688757100572135698e+02, + +2.52070205858023719784e+01, + }; + + static const T QQ[] = { + +7.42373277035675149943e+01, + +1.05644886038262816351e+03, + +4.98641058337653607651e+03, + +9.56231892404756170795e+03, + +7.99704160447350683650e+03, + +2.82619278517639096600e+03, + +3.36093607810698293419e+02, + }; + + static const T RP[] = { + -8.99971225705559398224e+08, + +4.52228297998194034323e+11, + -7.27494245221818276015e+13, + +3.68295732863852883286e+15, + }; + + static const T RQ[] = { + +6.20836478118054335476e+02, + +2.56987256757748830383e+05, + +8.35146791431949253037e+07, + +2.21511595479792499675e+10, + +4.74914122079991414898e+12, + +7.84369607876235854894e+14, + +8.95222336184627338078e+16, + +5.32278620332680085395e+18, + }; + + if (x < T(0.0)) { + return -bessel_j1_forward(-x); + } + + if (x <= T(5.0)) { + T rp = 0.0; + + for (uint8_t index = 0; index <= 3; index++) { + rp = rp * (x * x) + RP[index]; + } + + T rq = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + rq = rq * (x * x) + RQ[index]; + } + + return rp / rq * x * (x * x - T(1.46819706421238932572e+01)) * (x * x - T(4.92184563216946036703e+01)); + } + + T pp = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pp = pp * (T(5.0) / x * (T(5.0) / x)) + PP[index]; + } + + T pq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pq = pq * (T(5.0) / x * (T(5.0) / x)) + PQ[index]; + } + + T qp = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + qp = qp * (T(5.0) / x * (T(5.0) / x)) + QP[index]; + } + + T qq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + qq = qq * (T(5.0) / x * (T(5.0) / x)) + QQ[index]; + } + + return (pp / pq * std::cos(x - T(2.356194490192344928846982537459627163)) - T(5.0) / x * (qp / qq) * std::sin(x - T(2.356194490192344928846982537459627163))) * T(0.797884560802865355879892119868763737) / std::sqrt(x); +} // bessel_j1_forward(T x) + +template +inline C10_HOST_DEVICE T bessel_y0_forward(T x) { + static const T PP[] = { + +7.96936729297347051624e-04, + +8.28352392107440799803e-02, + +1.23953371646414299388e+00, + +5.44725003058768775090e+00, + +8.74716500199817011941e+00, + +5.30324038235394892183e+00, + +9.99999999999999997821e-01, + }; + + static const T PQ[] = { + +9.24408810558863637013e-04, + +8.56288474354474431428e-02, + +1.25352743901058953537e+00, + +5.47097740330417105182e+00, + +8.76190883237069594232e+00, + +5.30605288235394617618e+00, + +1.00000000000000000218e+00, + }; + + static const T QP[] = { + -1.13663838898469149931e-02, + -1.28252718670509318512e+00, + -1.95539544257735972385e+01, + -9.32060152123768231369e+01, + -1.77681167980488050595e+02, + -1.47077505154951170175e+02, + -5.14105326766599330220e+01, + -6.05014350600728481186e+00, + }; + + static const T QQ[] = { + +6.43178256118178023184e+01, + +8.56430025976980587198e+02, + +3.88240183605401609683e+03, + +7.24046774195652478189e+03, + +5.93072701187316984827e+03, + +2.06209331660327847417e+03, + +2.42005740240291393179e+02, + }; + + static const T YP[] = { + +1.55924367855235737965e+04, + -1.46639295903971606143e+07, + +5.43526477051876500413e+09, + -9.82136065717911466409e+11, + +8.75906394395366999549e+13, + -3.46628303384729719441e+15, + +4.42733268572569800351e+16, + -1.84950800436986690637e+16, + }; + + static const T YQ[] = { + +1.04128353664259848412e+03, + +6.26107330137134956842e+05, + +2.68919633393814121987e+08, + +8.64002487103935000337e+10, + +2.02979612750105546709e+13, + +3.17157752842975028269e+15, + +2.50596256172653059228e+17, + }; + + if (x <= T(5.0)) { + if (x == T(0.0)) { + return -std::numeric_limits::infinity(); + } + + if (x < T(0.0)) { + return std::numeric_limits::quiet_NaN(); + } + + T yp = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + yp = yp * (x * x) + YP[index]; + } + + T yq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + yq = yq * (x * x) + YQ[index]; + } + + return yp / yq + (T(0.636619772367581343075535053490057448) * std::log(x) * bessel_j0_forward(x)); + } + + T pp = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pp = pp * (T(25.0) / (x * x)) + PP[index]; + } + + T pq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pq = pq * (T(25.0) / (x * x)) + PQ[index]; + } + + T qp = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + qp = qp * (T(25.0) / (x * x)) + QP[index]; + } + + T qq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + qq = qq * (T(25.0) / (x * x)) + QQ[index]; + } + + return (pp / pq * std::sin(x - T(0.785398163397448309615660845819875721)) + T(5.0) / x * (qp / qq) * std::cos(x - T(0.785398163397448309615660845819875721))) * T(0.797884560802865355879892119868763737) / std::sqrt(x); +} // bessel_y0_forward(T x) + +template +inline C10_HOST_DEVICE T bessel_y1_forward(T x) { + static const T PP[] = { + +7.62125616208173112003e-04, + +7.31397056940917570436e-02, + +1.12719608129684925192e+00, + +5.11207951146807644818e+00, + +8.42404590141772420927e+00, + +5.21451598682361504063e+00, + +1.00000000000000000254e+00, + }; + + static const T PQ[] = { + +5.71323128072548699714e-04, + +6.88455908754495404082e-02, + +1.10514232634061696926e+00, + +5.07386386128601488557e+00, + +8.39985554327604159757e+00, + +5.20982848682361821619e+00, + +9.99999999999999997461e-01, + }; + + static const T QP[] = { + +5.10862594750176621635e-02, + +4.98213872951233449420e+00, + +7.58238284132545283818e+01, + +3.66779609360150777800e+02, + +7.10856304998926107277e+02, + +5.97489612400613639965e+02, + +2.11688757100572135698e+02, + +2.52070205858023719784e+01, + }; + + static const T QQ[] = { + +7.42373277035675149943e+01, + +1.05644886038262816351e+03, + +4.98641058337653607651e+03, + +9.56231892404756170795e+03, + +7.99704160447350683650e+03, + +2.82619278517639096600e+03, + +3.36093607810698293419e+02, + }; + + static const T YP[] = { + +1.26320474790178026440e+09, + -6.47355876379160291031e+11, + +1.14509511541823727583e+14, + -8.12770255501325109621e+15, + +2.02439475713594898196e+17, + -7.78877196265950026825e+17, + }; + + static const T YQ[] = { + +5.94301592346128195359e+02, + +2.35564092943068577943e+05, + +7.34811944459721705660e+07, + +1.87601316108706159478e+10, + +3.88231277496238566008e+12, + +6.20557727146953693363e+14, + +6.87141087355300489866e+16, + +3.97270608116560655612e+18, + }; + + if (x <= T(5.0)) { + if (x == T(0.0)) { + return -std::numeric_limits::infinity(); + } + + if (x <= T(0.0)) { + return std::numeric_limits::quiet_NaN(); + } + + T yp = 0.0; + + for (uint8_t index = 0; index <= 5; index++) { + yp = yp * (x * x) + YP[index]; + } + + T yq = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + yq = yq * (x * x) + YQ[index]; + } + + return x * (yp / yq) + (T(0.636619772367581343075535053490057448) * (bessel_j1_forward(x) * std::log(x) - T(1.0) / x)); + } + + T pp = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pp = pp * (T(5.0) / x * (T(5.0) / x)) + PP[index]; + } + + T pq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + pq = pq * (T(5.0) / x * (T(5.0) / x)) + PQ[index]; + } + + T qp = 0.0; + + for (uint8_t index = 0; index <= 7; index++) { + qp = qp * (T(5.0) / x * (T(5.0) / x)) + QP[index]; + } + + T qq = 0.0; + + for (uint8_t index = 0; index <= 6; index++) { + qq = qq * (T(5.0) / x * (T(5.0) / x)) + QQ[index]; + } + + return (pp / pq * std::sin(x - T(2.356194490192344928846982537459627163)) + T(5.0) / x * (qp / qq) * std::cos(x - T(2.356194490192344928846982537459627163))) * T(0.797884560802865355879892119868763737) / std::sqrt(x); +} // bessel_y1_forward(T x) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_t_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (std::abs(x) == T(1.0)) { + if (x > T(0.0) || n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if ((n > 6) && (std::abs(x) < T(1.0))) { + return std::cos(n * std::acos(x)); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x; + } + + T p = T(1.0); + T q = x; + T r = x; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x) * q - p; + p = q; + q = r; + } + + return r; +} // chebyshev_polynomial_t_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_t_forward(T x, T n) { + return chebyshev_polynomial_t_forward(x, static_cast(n)); +} // chebyshev_polynomial_t_forward(T x, T n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_u_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (std::abs(x) == T(1.0)) { + if (x > T(0.0) || n % 2 == 0) { + return n + 1; + } + + return -(n + 1); + } + + if ((n > 8) && (std::abs(x) < T(1.0))) { + if (std::sin(std::acos(x)) != T(0.0)) { + return std::sin((n + 1) * std::acos(x)) / std::sin(std::acos(x)); + } + + return (n + 1) * std::cos((n + 1) * std::acos(x)) / x; + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x; + } + + T p = T(1.0); + T q = x + x; + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x) * q - p; + p = q; + q = r; + } + + return r; +} // chebyshev_polynomial_u_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_u_forward(T x, T n) { + return chebyshev_polynomial_u_forward(x, static_cast(n)); +} // chebyshev_polynomial_u_forward(T x, T n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_v_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (std::abs(x) == T(1.0)) { + if (x > T(0.0)) { + return T(1.0); + } + + if (n % 2 == 0) { + return n + n + 1; + } + + return -(n + n + 1); + } + + if ((n > 8) && (std::abs(x) < T(1.0))) { + if (std::sin(std::acos(x) / T(2.0)) != T(1.0)) { + return std::cos((n + T(0.5)) * std::acos(x)) / std::cos(std::acos(x) / T(2.0)); + } + + if (n % 2 == 0) { + return n + n + 1; + } + + return -(n + n + 1); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x - T(1.0); + } + + T p = T(1.0); + T q = x + x - T(1.0); + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x) * q - p; + p = q; + q = r; + } + + return r; +} // chebyshev_polynomial_v_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_v_forward(T x, T n) { + return chebyshev_polynomial_v_forward(x, static_cast(n)); +} // chebyshev_polynomial_v_forward(T x, T n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_w_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (std::abs(x) == T(1.0)) { + if (x > T(0.0)) { + return n + n + 1; + } + + if (n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if ((n > 8) && (std::abs(x) < T(1.0))) { + if (std::cos(std::acos(x) / T(2.0)) != T(1.0)) { + return std::sin((n + T(0.5)) * std::acos(x)) / std::sin(std::acos(x) / T(2.0)); + } + + if (x > T(0.0)) { + return n + n + 1; + } + + if (n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x + T(1.0); + } + + T p = T(1.0); + T q = x + x + T(1.0); + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x) * q - p; + p = q; + q = r; + } + + return r; +} // chebyshev_polynomial_w_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T chebyshev_polynomial_w_forward(T x, T n) { + return chebyshev_polynomial_w_forward(x, static_cast(n)); +} // chebyshev_polynomial_w_forward(T x, T n) + +template +constexpr auto getHermitianLimit() { + if constexpr (std::is_same_v) { + return 128; + } else if constexpr (std::is_same_v) { + return 512; + } else { + return 1024; + } +} + +template +inline C10_HOST_DEVICE T hermite_polynomial_h_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x; + } + + if (n > getHermitianLimit()) { + return std::numeric_limits::quiet_NaN(); + } + + T p = T(1.0); + T q = x + x; + T r = T(0.0); + + for (int64_t k = 2; k < n + n; k += 2) { + r = (x + x) * q - k * p; + p = q; + q = r; + } + + return r; +} // hermite_polynomial_h_forward(T x, int64_t n) + +template, int> = 0> +inline C10_HOST_DEVICE T hermite_polynomial_h_forward(T x, T n) { + return hermite_polynomial_h_forward(x, static_cast(n)); +} // hermite_polynomial_h_forward(T x, T n) + +template, int> = 0> +__ubsan_ignore_float_cast_overflow__ inline C10_HOST_DEVICE T hermite_polynomial_h_forward(T x, T n) { + return hermite_polynomial_h_forward(x, (!std::isinf(n) && !std::isnan(n)) ? static_cast(n) : static_cast(-1)); +} // hermite_polynomial_h_forward(T x, T n) + +template +inline C10_HOST_DEVICE T hermite_polynomial_he_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x; + } + + if (n > getHermitianLimit()) { + return std::numeric_limits::quiet_NaN(); + } + + T p = T(1.0); + T q = x; + T r; + + for (int64_t k = 1; k < n; k++) { + r = x * q - k * p; + p = q; + q = r; + } + + return r; +} // hermite_polynomial_he_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T hermite_polynomial_he_forward(T x, T n) { + return hermite_polynomial_he_forward(x, static_cast(n)); +} // hermite_polynomial_he_forward(T x, T n) + +template +inline C10_HOST_DEVICE T laguerre_polynomial_l_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (std::abs(x) == T(0.0)) { + return T(1.0); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return T(1.0) - x; + } + + T p = T(1.0); + T q = T(1.0) - x; + T r = q; + + for (int64_t k = 1; (k < n) && !std::isnan(q); k++) { + r = (((k + k) + (T(1.0) - x)) * q - k * p) / (k + 1); + p = q; + q = r; + } + + return r; +} // laguerre_polynomial_l_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T laguerre_polynomial_l_forward(T x, T n) { + return laguerre_polynomial_l_forward(x, static_cast(n)); +} // laguerre_polynomial_l_forward(T x, T n) + +template +inline C10_HOST_DEVICE T legendre_polynomial_p_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (std::abs(x) == T(1.0)) { + if (x > T(0.0) || n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x; + } + + T p = T(1.0); + T q = x; + T r = q; + + for (int64_t k = 1; (k < n) && !std::isnan(q); k++) { + r = ((k + k + 1) * x * q - k * p) / (k + 1); + p = q; + q = r; + } + + return r; +} // legendre_polynomial_p_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T legendre_polynomial_p_forward(T x, T n) { + return legendre_polynomial_p_forward(x, static_cast(n)); +} // legendre_polynomial_p_forward(T x, T n) + +template +inline C10_HOST_DEVICE T modified_bessel_i0_forward(T x) { + static const T A[] = { + -4.41534164647933937950e-18, + +3.33079451882223809783e-17, + -2.43127984654795469359e-16, + +1.71539128555513303061e-15, + -1.16853328779934516808e-14, + +7.67618549860493561688e-14, + -4.85644678311192946090e-13, + +2.95505266312963983461e-12, + -1.72682629144155570723e-11, + +9.67580903537323691224e-11, + -5.18979560163526290666e-10, + +2.65982372468238665035e-09, + -1.30002500998624804212e-08, + +6.04699502254191894932e-08, + -2.67079385394061173391e-07, + +1.11738753912010371815e-06, + -4.41673835845875056359e-06, + +1.64484480707288970893e-05, + -5.75419501008210370398e-05, + +1.88502885095841655729e-04, + -5.76375574538582365885e-04, + +1.63947561694133579842e-03, + -4.32430999505057594430e-03, + +1.05464603945949983183e-02, + -2.37374148058994688156e-02, + +4.93052842396707084878e-02, + -9.49010970480476444210e-02, + +1.71620901522208775349e-01, + -3.04682672343198398683e-01, + +6.76795274409476084995e-01, + }; + + static const T B[] = { + -7.23318048787475395456e-18, + -4.83050448594418207126e-18, + +4.46562142029675999901e-17, + +3.46122286769746109310e-17, + -2.82762398051658348494e-16, + -3.42548561967721913462e-16, + +1.77256013305652638360e-15, + +3.81168066935262242075e-15, + -9.55484669882830764870e-15, + -4.15056934728722208663e-14, + +1.54008621752140982691e-14, + +3.85277838274214270114e-13, + +7.18012445138366623367e-13, + -1.79417853150680611778e-12, + -1.32158118404477131188e-11, + -3.14991652796324136454e-11, + +1.18891471078464383424e-11, + +4.94060238822496958910e-10, + +3.39623202570838634515e-09, + +2.26666899049817806459e-08, + +2.04891858946906374183e-07, + +2.89137052083475648297e-06, + +6.88975834691682398426e-05, + +3.36911647825569408990e-03, + +8.04490411014108831608e-01, + }; + + T p = T{0}; + T q = 0.0; + + if (std::abs(x) <= T(8.0)) { + T a = A[0]; + + for (uint8_t index = 1; index < 30; index++) { + p = q; + q = a; + a = ((std::abs(x) / T(2.0)) - T(2.0)) * q - p + A[index]; + } + + return std::exp(std::abs(x)) * (T(0.5) * (a - p)); + } + + T b = B[0]; + + for (uint8_t index = 1; index < 25; index++) { + p = q; + q = b; + b = (T(32.0) / std::abs(x) - T(2.0)) * q - p + B[index]; + } + + return std::exp(std::abs(x)) * (T(0.5) * (b - p)) / std::sqrt(std::abs(x)); +} // modified_bessel_i0_forward(T x) + +template +inline C10_HOST_DEVICE T modified_bessel_i1_forward(T x) { + static const T A[] = { + +2.77791411276104639959e-18, + -2.11142121435816608115e-17, + +1.55363195773620046921e-16, + -1.10559694773538630805e-15, + +7.60068429473540693410e-15, + -5.04218550472791168711e-14, + +3.22379336594557470981e-13, + -1.98397439776494371520e-12, + +1.17361862988909016308e-11, + -6.66348972350202774223e-11, + +3.62559028155211703701e-10, + -1.88724975172282928790e-09, + +9.38153738649577178388e-09, + -4.44505912879632808065e-08, + +2.00329475355213526229e-07, + -8.56872026469545474066e-07, + +3.47025130813767847674e-06, + -1.32731636560394358279e-05, + +4.78156510755005422638e-05, + -1.61760815825896745588e-04, + +5.12285956168575772895e-04, + -1.51357245063125314899e-03, + +4.15642294431288815669e-03, + -1.05640848946261981558e-02, + +2.47264490306265168283e-02, + -5.29459812080949914269e-02, + +1.02643658689847095384e-01, + -1.76416518357834055153e-01, + +2.52587186443633654823e-01, + }; + + static const T B[] = { + +7.51729631084210481353e-18, + +4.41434832307170791151e-18, + -4.65030536848935832153e-17, + -3.20952592199342395980e-17, + +2.96262899764595013876e-16, + +3.30820231092092828324e-16, + -1.88035477551078244854e-15, + -3.81440307243700780478e-15, + +1.04202769841288027642e-14, + +4.27244001671195135429e-14, + -2.10154184277266431302e-14, + -4.08355111109219731823e-13, + -7.19855177624590851209e-13, + +2.03562854414708950722e-12, + +1.41258074366137813316e-11, + +3.25260358301548823856e-11, + -1.89749581235054123450e-11, + -5.58974346219658380687e-10, + -3.83538038596423702205e-09, + -2.63146884688951950684e-08, + -2.51223623787020892529e-07, + -3.88256480887769039346e-06, + -1.10588938762623716291e-04, + -9.76109749136146840777e-03, + +7.78576235018280120474e-01, + }; + + T p = T{0}; + T q = 0.0; + + if (std::abs(x) <= T(8.0)) { + T a = A[0]; + + for (uint8_t index = 1; index < 29; index++) { + p = q; + q = a; + a = ((std::abs(x) / T(2.0)) - T(2.0)) * q - p + A[index]; + } + + if (x < T(0.0)) { + return -(T(0.5) * (a - p) * std::abs(x) * std::exp(std::abs(x))); + } + + return T(0.5) * (a - p) * std::abs(x) * std::exp(std::abs(x)); + } + + T b = B[0]; + + for (uint8_t index = 1; index < 25; index++) { + p = q; + q = b; + b = (T(32.0) / std::abs(x) - T(2.0)) * q - p + B[index]; + } + + if (x < T(0.0)) { + return -(std::exp(std::abs(x)) * (T(0.5) * (b - p)) / std::sqrt(std::abs(x))); + } + + return std::exp(std::abs(x)) * (T(0.5) * (b - p)) / std::sqrt(std::abs(x)); +} // modified_bessel_i1_forward(T x) + +template +inline C10_HOST_DEVICE T modified_bessel_k0_forward(T x) { + static const T A[] = { + +1.37446543561352307156e-16, + +4.25981614279661018399e-14, + +1.03496952576338420167e-11, + +1.90451637722020886025e-09, + +2.53479107902614945675e-07, + +2.28621210311945178607e-05, + +1.26461541144692592338e-03, + +3.59799365153615016266e-02, + +3.44289899924628486886e-01, + -5.35327393233902768720e-01, + }; + + static const T B[] = { + +5.30043377268626276149e-18, + -1.64758043015242134646e-17, + +5.21039150503902756861e-17, + -1.67823109680541210385e-16, + +5.51205597852431940784e-16, + -1.84859337734377901440e-15, + +6.34007647740507060557e-15, + -2.22751332699166985548e-14, + +8.03289077536357521100e-14, + -2.98009692317273043925e-13, + +1.14034058820847496303e-12, + -4.51459788337394416547e-12, + +1.85594911495471785253e-11, + -7.95748924447710747776e-11, + +3.57739728140030116597e-10, + -1.69753450938905987466e-09, + +8.57403401741422608519e-09, + -4.66048989768794782956e-08, + +2.76681363944501510342e-07, + -1.83175552271911948767e-06, + +1.39498137188764993662e-05, + -1.28495495816278026384e-04, + +1.56988388573005337491e-03, + -3.14481013119645005427e-02, + +2.44030308206595545468e+00, + }; + + if (x == T(0.0)) { + return std::numeric_limits::infinity(); + } + + if (x < T(0.0)) { + return std::numeric_limits::quiet_NaN(); + } + + T p = T{0}; + T q = 0.0; + + if (x <= T(2.0)) { + T a = A[0]; + + for (uint8_t index = 1; index < 10; index++) { + p = q; + q = a; + a = (x * x - T(2.0)) * q - p + A[index]; + } + + return T(0.5) * (a - p) - std::log(0.5 * x) * modified_bessel_i0_forward(x); + } + + T b = B[0]; + + for (uint8_t index = 1; index < 25; index++) { + p = q; + q = b; + b = (T(8.0) / x - T(2.0)) * q - p + B[index]; + } + + return std::exp(-x) * (T(0.5) * (b - p)) / std::sqrt(x); +} // modified_bessel_k0_forward(T x) + +template +inline C10_HOST_DEVICE T modified_bessel_k1_forward(T x) { + static const T A[] = { + -7.02386347938628759343e-18, + -2.42744985051936593393e-15, + -6.66690169419932900609e-13, + -1.41148839263352776110e-10, + -2.21338763073472585583e-08, + -2.43340614156596823496e-06, + -1.73028895751305206302e-04, + -6.97572385963986435018e-03, + -1.22611180822657148235e-01, + -3.53155960776544875667e-01, + +1.52530022733894777053e+00, + }; + + static const T B[] = { + -5.75674448366501715755e-18, + +1.79405087314755922667e-17, + -5.68946255844285935196e-17, + +1.83809354436663880070e-16, + -6.05704724837331885336e-16, + +2.03870316562433424052e-15, + -7.01983709041831346144e-15, + +2.47715442448130437068e-14, + -8.97670518232499435011e-14, + +3.34841966607842919884e-13, + -1.28917396095102890680e-12, + +5.13963967348173025100e-12, + -2.12996783842756842877e-11, + +9.21831518760500529508e-11, + -4.19035475934189648750e-10, + +2.01504975519703286596e-09, + -1.03457624656780970260e-08, + +5.74108412545004946722e-08, + -3.50196060308781257119e-07, + +2.40648494783721712015e-06, + -1.93619797416608296024e-05, + +1.95215518471351631108e-04, + -2.85781685962277938680e-03, + +1.03923736576817238437e-01, + +2.72062619048444266945e+00, + }; + + if (x == T(0.0)) { + return std::numeric_limits::infinity(); + } + + if (x < T(0.0)) { + return std::numeric_limits::quiet_NaN(); + } + + T p = T{0}; + T q = 0.0; + + if (x <= T(2.0)) { + T a = A[0]; + + for (uint8_t index = 1; index < 11; index++) { + p = q; + q = a; + a = (x * x - T(2.0)) * q - p + A[index]; + } + + return std::log(T(0.5) * x) * modified_bessel_i1_forward(x) + T(0.5) * (a - p) / x; + } + + T b = B[0]; + + for (uint8_t index = 1; index < 25; index++) { + p = q; + q = b; + b = (T(8.0) / x - T(2.0)) * q - p + B[index]; + } + + return std::exp(-x) * (T(0.5) * (b - p)) / std::sqrt(x); +} // modified_bessel_k1_forward(T x) + +template +inline C10_HOST_DEVICE T scaled_modified_bessel_k0_forward(T x) { + static const T A[] = { + +1.37446543561352307156e-16, + +4.25981614279661018399e-14, + +1.03496952576338420167e-11, + +1.90451637722020886025e-09, + +2.53479107902614945675e-07, + +2.28621210311945178607e-05, + +1.26461541144692592338e-03, + +3.59799365153615016266e-02, + +3.44289899924628486886e-01, + -5.35327393233902768720e-01, + }; + + static const T B[] = { + +5.30043377268626276149e-18, + -1.64758043015242134646e-17, + +5.21039150503902756861e-17, + -1.67823109680541210385e-16, + +5.51205597852431940784e-16, + -1.84859337734377901440e-15, + +6.34007647740507060557e-15, + -2.22751332699166985548e-14, + +8.03289077536357521100e-14, + -2.98009692317273043925e-13, + +1.14034058820847496303e-12, + -4.51459788337394416547e-12, + +1.85594911495471785253e-11, + -7.95748924447710747776e-11, + +3.57739728140030116597e-10, + -1.69753450938905987466e-09, + +8.57403401741422608519e-09, + -4.66048989768794782956e-08, + +2.76681363944501510342e-07, + -1.83175552271911948767e-06, + +1.39498137188764993662e-05, + -1.28495495816278026384e-04, + +1.56988388573005337491e-03, + -3.14481013119645005427e-02, + +2.44030308206595545468e+00, + }; + + if (x == T(0.0)) { + return std::numeric_limits::infinity(); + } + + if (x < T(0.0)) { + return std::numeric_limits::quiet_NaN(); + } + + T p = T{0}; + T q = 0.0; + + if (x <= T(2.0)) { + T a = A[0]; + + for (uint64_t index = 1; index < 10; index++) { + p = q; + q = a; + a = (x * x - T(2.0)) * q - p + A[index]; + } + + return (T(0.5) * (a - p) - std::log(T(0.5) * x) * modified_bessel_i0_forward(x)) * std::exp(x); + } + + T b = B[0]; + + for (uint64_t index = 1; index < 25; index++) { + p = q; + q = b; + b = (T(8.0) / x - T(2.0)) * q - p + B[index]; + } + + return T(0.5) * (b - p) / std::sqrt(x); +} // T scaled_modified_bessel_k0_forward(T x) + +template +inline C10_HOST_DEVICE T scaled_modified_bessel_k1_forward(T x) { + static const T A[] = { + -7.02386347938628759343e-18, + -2.42744985051936593393e-15, + -6.66690169419932900609e-13, + -1.41148839263352776110e-10, + -2.21338763073472585583e-08, + -2.43340614156596823496e-06, + -1.73028895751305206302e-04, + -6.97572385963986435018e-03, + -1.22611180822657148235e-01, + -3.53155960776544875667e-01, + +1.52530022733894777053e+00, + }; + + static const T B[] = { + -5.75674448366501715755e-18, + +1.79405087314755922667e-17, + -5.68946255844285935196e-17, + +1.83809354436663880070e-16, + -6.05704724837331885336e-16, + +2.03870316562433424052e-15, + -7.01983709041831346144e-15, + +2.47715442448130437068e-14, + -8.97670518232499435011e-14, + +3.34841966607842919884e-13, + -1.28917396095102890680e-12, + +5.13963967348173025100e-12, + -2.12996783842756842877e-11, + +9.21831518760500529508e-11, + -4.19035475934189648750e-10, + +2.01504975519703286596e-09, + -1.03457624656780970260e-08, + +5.74108412545004946722e-08, + -3.50196060308781257119e-07, + +2.40648494783721712015e-06, + -1.93619797416608296024e-05, + +1.95215518471351631108e-04, + -2.85781685962277938680e-03, + +1.03923736576817238437e-01, + +2.72062619048444266945e+00, + }; + + if (x == T(0.0)) { + return std::numeric_limits::infinity(); + } + + if (x < T(0.0)) { + return std::numeric_limits::quiet_NaN(); + } + + T p = T{0}; + T q = 0.0; + + if (x <= T(2.0)) { + T a = A[0]; + + for (uint64_t index = 1; index < 11; index++) { + p = q; + q = a; + a = (x * x - T(2.0)) * q - p + A[index]; + } + + return (std::log(T(0.5) * x) * modified_bessel_i1_forward(x) + T(0.5) * (a - p) / x) * std::exp(x); + } + + T b = B[0]; + + for (uint64_t index = 1; index < 25; index++) { + p = q; + q = b; + b = (T(8.0) / x - T(2.0)) * q - p + B[index]; + } + + return (T(0.5) * (b - p) / std::sqrt(x)); +} // T scaled_modified_bessel_k1_forward(T x) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_t_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (x == T(1.0)) { + return T(1.0); + } + + if (x == T(0.0)) { + if (n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if ((n > 6) && (std::abs(x + x - T(1.0)) < T(1.0))) { + return std::cos(n * std::acos(x + x - T(1.0))); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x - T(1.0); + } + + T p = T(1.0); + T q = x + x - T(1.0); + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p; + p = q; + q = r; + } + + return r; +} // shifted_chebyshev_polynomial_t_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_t_forward(T x, T n) { + return shifted_chebyshev_polynomial_t_forward(x, static_cast(n)); +} // shifted_chebyshev_polynomial_t_forward(T x, T n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_u_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (x == T(1.0)) { + return n + 1; + } + + if (x == T(0.0)) { + if (n % 2 == 0) { + return n + 1; + } + + return -(n + 1); + } + + if ((n > 6) && (std::abs(x + x - T(1.0)) < T(1.0))) { + if (std::sin(std::acos(x + x - T(1.0))) != T(0.0)) { + return std::sin((n + 1) * std::acos(x + x - T(1.0))) / std::sin(std::acos(x + x - T(1.0))); + } + + return (n + 1) * std::cos((n + 1) * std::acos(x + x - T(1.0))) / (x + x - T(1.0)); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x - T(1.0) + (x + x - T(1.0)); + } + + T p = T(1.0); + T q = x + x - T(1.0) + (x + x - T(1.0)); + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p; + p = q; + q = r; + } + + return r; +} // shifted_chebyshev_polynomial_u_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_u_forward(T x, T n) { + return shifted_chebyshev_polynomial_u_forward(x, static_cast(n)); +} // shifted_chebyshev_polynomial_u_forward(T x, T n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_v_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (x == T(1.0)) { + return T(1.0); + } + + if (x == T(0.0)) { + if (n % 2 == 0) { + return (n + n + 1); + } + + return -(n + n + 1); + } + + if ((n > 6) && (std::abs(x + x - T(1.0)) < T(1.0))) { + if (std::sin(std::acos(x + x - T(1.0)) / T(2.0)) != T(1.0)) { + return std::cos((n + T(0.5)) * std::acos(x + x - T(1.0))) / std::cos(std::acos(x + x - T(1.0)) / T(2.0)); + } + + if (n % 2 == 0) { + return n + n + 1; + } + + return -(n + n + 1); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x - T(1.0) + (x + x - T(1.0)) - T(1.0); + } + + T p = T(1.0); + T q = x + x - T(1.0) + (x + x - T(1.0)) - T(1.0); + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p; + p = q; + q = r; + } + + return r; +} // shifted_chebyshev_polynomial_v_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_v_forward(T x, T n) { + return shifted_chebyshev_polynomial_v_forward(x, static_cast(n)); +} // shifted_chebyshev_polynomial_v_forward(T x, T n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_w_forward(T x, int64_t n) { + if (n < 0) { + return T(0.0); + } + + if (x == T(1.0)) { + return n + n + 1; + } + + if (x == T(0.0)) { + if (n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if ((n > 4) && (std::abs(x + x - T(1.0)) < T(1.0))) { + if (std::cos(std::acos(x + x - T(1.0)) / T(2.0)) != T(1.0)) { + return std::sin((n + T(0.5)) * std::acos(x + x - T(1.0))) / std::sin(std::acos(x + x - T(1.0)) / T(2.0)); + } + + if (n % 2 == 0) { + return T(1.0); + } + + return T(-1.0); + } + + if (n == 0) { + return T(1.0); + } + + if (n == 1) { + return x + x - T(1.0) + (x + x - T(1.0)) + T(1.0); + } + + T p = T(1.0); + T q = x + x - T(1.0) + (x + x - T(1.0)) + T(1.0); + T r = q; + + for (int64_t k = 2; (k <= n) && !std::isnan(q); k++) { + r = (x + x - T(1.0) + (x + x - T(1.0))) * q - p; + p = q; + q = r; + } + + return r; +} // shifted_chebyshev_polynomial_w_forward(T x, int64_t n) + +template +inline C10_HOST_DEVICE T shifted_chebyshev_polynomial_w_forward(T x, T n) { + return shifted_chebyshev_polynomial_w_forward(x, static_cast(n)); +} // shifted_chebyshev_polynomial_w_forward(T x, T n) + +template +inline C10_HOST_DEVICE T spherical_bessel_j0_forward(T x) { + if (std::isinf(x)) { + return T(0.0); + } + + if (std::abs(x) < T(0.5)) { + return T(1.0) + x * x * (T(-1.0) / T(6.0) + x * x * (T(1.0) / T(120.0) + x * x * (T(-1.0) / T(5040.0) + x * x * (T(1.0) / T(362880.0) + x * x * (T(-1.0) / T(39916800.0) + x * x * (T(1.0) / T(6227020800.0))))))); + } + + return std::sin(x) / x; +} // T spherical_bessel_j0_forward(T x) + +C10_CLANG_DIAGNOSTIC_POP() diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/MathBitFallThroughLists.h b/western_ai/usa/pytorch/aten/src/ATen/native/MathBitFallThroughLists.h new file mode 100644 index 0000000000000000000000000000000000000000..d9ce1dfa0380abce0c12b59a0e7db958537542bc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/MathBitFallThroughLists.h @@ -0,0 +1,65 @@ +#pragma once + +namespace at { +// views and their in-place version ops +#define TORCH_VIEW_FNS(m) \ + m.impl("as_strided_", torch::CppFunction::makeFallthrough()); \ + m.impl("detach", torch::CppFunction::makeFallthrough()); \ + m.impl("detach_", torch::CppFunction::makeFallthrough()); \ + m.impl("diagonal", torch::CppFunction::makeFallthrough()); \ + m.impl("expand", torch::CppFunction::makeFallthrough()); \ + m.impl("expand_as", torch::CppFunction::makeFallthrough()); \ + m.impl("movedim.int", torch::CppFunction::makeFallthrough()); \ + m.impl("movedim.intlist", torch::CppFunction::makeFallthrough()); \ + m.impl("narrow", torch::CppFunction::makeFallthrough()); \ + m.impl("permute", torch::CppFunction::makeFallthrough()); \ + m.impl("select.int", torch::CppFunction::makeFallthrough()); \ + m.impl("squeeze", torch::CppFunction::makeFallthrough()); \ + m.impl("squeeze_", torch::CppFunction::makeFallthrough()); \ + m.impl("transpose.int", torch::CppFunction::makeFallthrough()); \ + m.impl("transpose_", torch::CppFunction::makeFallthrough()); \ + m.impl("t", torch::CppFunction::makeFallthrough()); \ + m.impl("t_", torch::CppFunction::makeFallthrough()); \ + m.impl("real", torch::CppFunction::makeFallthrough()); \ + m.impl("imag", torch::CppFunction::makeFallthrough()); \ + m.impl("view_as_real", torch::CppFunction::makeFallthrough()); \ + m.impl("unflatten.int", torch::CppFunction::makeFallthrough()); \ + m.impl("unfold", torch::CppFunction::makeFallthrough()); \ + m.impl("unsqueeze", torch::CppFunction::makeFallthrough()); \ + m.impl("unsqueeze_", torch::CppFunction::makeFallthrough()); \ + m.impl("view_as", torch::CppFunction::makeFallthrough()); \ + m.impl("unbind.int", torch::CppFunction::makeFallthrough()); \ + m.impl("split.Tensor", torch::CppFunction::makeFallthrough()); \ + m.impl("split_with_sizes", torch::CppFunction::makeFallthrough()); \ + m.impl("swapaxes", torch::CppFunction::makeFallthrough()); \ + m.impl("swapdims", torch::CppFunction::makeFallthrough()); \ + m.impl("chunk", torch::CppFunction::makeFallthrough()); \ + m.impl("reshape", torch::CppFunction::makeFallthrough()); \ + m.impl("alias", torch::CppFunction::makeFallthrough()); \ + m.impl("hsplit.int", torch::CppFunction::makeFallthrough()); \ + m.impl("hsplit.array", torch::CppFunction::makeFallthrough()); \ + m.impl("dsplit.int", torch::CppFunction::makeFallthrough()); \ + m.impl("dsplit.array", torch::CppFunction::makeFallthrough()); \ + m.impl("vsplit.int", torch::CppFunction::makeFallthrough()); \ + m.impl("vsplit.array", torch::CppFunction::makeFallthrough()); \ + m.impl("conj", torch::CppFunction::makeFallthrough()); \ + m.impl("_conj", torch::CppFunction::makeFallthrough()); \ + m.impl("_unsafe_view", torch::CppFunction::makeFallthrough()); \ + m.impl("resize_", torch::CppFunction::makeFallthrough()); + +#define TENSOR_UTILITIES_AND_CONSTRUCTORS(m) \ + m.impl("empty_like", torch::CppFunction::makeFallthrough()); \ + m.impl("empty.memory_format", torch::CppFunction::makeFallthrough()); \ + m.impl("empty.out", torch::CppFunction::makeFallthrough()); \ + m.impl("empty_strided", torch::CppFunction::makeFallthrough()); \ + m.impl("full_like", torch::CppFunction::makeFallthrough()); \ + m.impl("stride.int", torch::CppFunction::makeFallthrough()); \ + m.impl("size.int", torch::CppFunction::makeFallthrough()); \ + m.impl("is_complex", torch::CppFunction::makeFallthrough()); \ + m.impl("is_floating_point", torch::CppFunction::makeFallthrough()); \ + m.impl("requires_grad_", torch::CppFunction::makeFallthrough()); +} + +#define TORCH_VIEW_FNS_NATIVE_FN_REGISTRATION(m) \ + m.impl("as_strided", torch::CppFunction::makeFallthrough()); \ + m.impl("view", torch::CppFunction::makeFallthrough()); diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/MathBitsFallback.h b/western_ai/usa/pytorch/aten/src/ATen/native/MathBitsFallback.h new file mode 100644 index 0000000000000000000000000000000000000000..af8ca30bcb470514966205211a5da25c3775d309 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/MathBitsFallback.h @@ -0,0 +1,157 @@ +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include + +#include +#endif + +namespace at::native { +// This fallback should only be used for operations that are self inverse and have a corresponding tensor +// bit (internally implemented using DispatchKey) to maintain the state on tensor using tensor bit. +// Currently there are two tensor bits that trigger this fallback: conjugate bit and negative bit. +// Conjugate bit is set on a tensor when `.conj()` is called and neg bit is set on a tensor when `.conj().imag` is called. + +// NOTE: To use this fallback, `clone` and `copy_` should fully understand and be able to correctly handle the semantic of your math bit. +struct MathOpFallback { + MathOpFallback(DispatchKey key_, std::string op_name_) : key(key_), op_name(std::move(op_name_)) {} + virtual bool is_bit_set(const Tensor&) = 0; + void fallback_impl(const c10::OperatorHandle& op, DispatchKeySet dispatch_keys, torch::jit::Stack* stack) { + /* + Situations to handle: + 1. Out-of-place operation. Easy: materialize all inputs and + call it a day. + 2. Inplace operation. Desugar x.add_(2) into x.conj_().add_(2).conj_(). + Materialize other inputs as in (1). + 3. out= operation. Desugar add(x, 2, out=y) into y.copy_(add(x, 2)) + Materialize other inputs as in (1). + + It is important to be able to tell if we READ from an argument and if we + WRITE to an argument. Conservative approach is to assume that we always + READ from an argument, but in out= operations you can skip + conjugating inputs on entry that never get used. In the current schema we + can't easily tell if the operation is in in-place or out= operation. + + Note: + 1. Mutable tensorlists containing tensors whose math bit set to true are disallowed. + 2. Mutable tensors with math bit set to true are unconditionally cloned to ensure + correct behavior in the case when the mutable tensor shares memory with non mutable arguments. + + If we were to in-place resolve the math bit for mutable inputs, then the non-mutable inputs sharing partial or full memory + with these mutable inputs would read into wrong values in the following cases: + 1. Non mutable inputs have their math bit set to false. + 2. Math bit for mutable input(s) is resolved before the non mutable inputs (with bit set to true and sharing memory + with one or more mutable arg(s)) are cloned. + At the end, the final value of the mutable arguments from the stack are copied into the original input mutable tensor inputs. + */ + const auto& arguments = op.schema().arguments(); + const auto num_arguments = arguments.size(); + const auto stack_start = stack->size() - num_arguments; + + std::optional is_write; + for (const auto i : c10::irange(num_arguments)) { + // Three possible states: + // 1. alias_info has no value --> out-of-place operation + // 2. alias_info does have a value, alias_info->is_write=True --> in-place or out= operation + // 3. alias_info does have a value, alias_info->is_write=False --> view operation + const AliasInfo* alias_info = arguments[i].alias_info(); + if (alias_info != nullptr) { + if (is_write.has_value()) { + TORCH_CHECK(*is_write == alias_info->isWrite(), + "Unsupported operator for ", op_name, " fallback: ", op.schema().name(), + op_name, " fallback doesn't work for operators with a mix " + "mutable and non-mutable inputs that alias with outputs, " + "this must be implemented manually. " + "If you got this error on a core op, please report a bug to PyTorch."); + } else { + is_write = alias_info->isWrite(); + } + } + } + + if (is_write.has_value() && !*is_write) { + // We assume that view operators automatically handle the math bit + // correctly by propagating the dispatch key in key_set. + // This is not necessarily always right, so you should test these cases. + op.redispatchBoxed(dispatch_keys & c10::DispatchKeySet(DispatchKeySet::FULL_AFTER, key), stack); + return; + } + + // Mutable inputs with math bit set to True and their clones + std::vector> mutable_inputs_with_their_clones; + for (const auto i : c10::irange(num_arguments)) { + auto& ivalue = (*stack)[stack_start + i]; + if (!(ivalue.isTensor() || ivalue.isTensorList())) { + continue; + } + const auto& argument = arguments[i]; + bool mut_arg = false; + if (argument.alias_info()) { + // Was already tested by is_write loop above + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(argument.alias_info()->isWrite()); + mut_arg = true; + } + if (ivalue.isTensor()) { + if (!is_bit_set(ivalue.toTensor())) { + continue; + } + auto tensor = std::move(ivalue).toTensor(); + auto resolved_tensor = at::clone(tensor); + if (mut_arg) { + TORCH_CHECK(mutable_inputs_with_their_clones.empty(), op_name, " fallback does not support operators with more than one mutable tensors with ", + op_name, "bit set to true."); + mutable_inputs_with_their_clones.emplace_back(std::move(tensor), resolved_tensor); + } + (*stack)[stack_start + i] = std::move(resolved_tensor); + } else if (ivalue.isTensorList()) { + auto tensors = std::move(ivalue).toTensorList(); + for(const auto j : c10::irange(tensors.size())) { + const auto& tensor = tensors[j]; + if (!is_bit_set(tensor)) { + continue; + } + TORCH_CHECK(!mut_arg, " fallback doesn't currently support mutable TensorLists with ", + op_name, " inputs. Please materialize all the ", op_name, " input tensor(s) in the mutable TensorList inputs before calling ", + op.schema().name()); + tensors[j] = at::clone(tensor); + } + (*stack)[stack_start + i] = std::move(tensors); + } + } + + op.redispatchBoxed(dispatch_keys & c10::DispatchKeySet(DispatchKeySet::FULL_AFTER, key), stack); + + TORCH_INTERNAL_ASSERT(mutable_inputs_with_their_clones.size() <= 1); + + for (std::pair mut_tensors: mutable_inputs_with_their_clones) { + auto& mutable_input = mut_tensors.first; + auto& cloned_mutable_input = mut_tensors.second; + auto& ivalue = (*stack)[stack_start]; + auto returned_output = std::move(ivalue).toTensor(); + + // sanity check to ensure that the tensor in stack aliases the cloned_mutable_input + TORCH_INTERNAL_ASSERT(cloned_mutable_input.is_same(returned_output)); + + // necessary for out= arg + at::native::resize_output(mutable_input, returned_output.sizes()); + + mutable_input.copy_(returned_output); + (*stack)[stack_start] = std::move(mutable_input); + } + } + + virtual ~MathOpFallback() = default; + + DispatchKey key; + std::string op_name; +}; + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/MaxPooling.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/MaxPooling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2d6ebef29220d9d65b9424f8d7f4a75ed50af2d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/MaxPooling.cpp @@ -0,0 +1,93 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { + +DEFINE_DISPATCH(max_pool1d_stub); + +namespace { + +Tensor max_pool1d_impl( + const Tensor& self, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) { + + // If stride=None then set it to kernel_size + if (stride.empty()) { + stride = kernel_size; + } + + const int64_t NB = self.dim() == 3 ? self.size(-3) : 1; + const int64_t NC = self.size(-2); + const int64_t IW = self.size(-1); + const int64_t KW = kernel_size[0]; + const int64_t SJ = stride[0]; + const int64_t PJ = padding[0]; + const int64_t DJ = dilation[0]; + + const int64_t OW = pooling_output_shape(IW, KW, PJ, SJ, DJ, ceil_mode); + Tensor output = at::empty({NB, NC, OW}, self.options()); + + PoolingParams1D params{NB, NC, IW, OW, KW, SJ, PJ, DJ}; + max_pool1d_stub(self.device().type(), output, self, params); + + if (self.dim() == 2) { + output.squeeze_(0); + } + + return output; +} + +} // namespace + +Tensor max_pool1d( + const Tensor& self, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) { + + auto ndim = self.ndimension(); + TORCH_CHECK( + (ndim == 2 && self.sym_size(0) != 0 && self.sym_size(1) != 0) || + (ndim == 3 && self.sym_size(1) != 0 && self.sym_size(2) != 0), + "max_pool1d: Expected 2D or 3D (batch mode) tensor with optional 0 dim batch size for input, but got:", + self.sym_sizes()); + + if (self.is_quantized()) { + return at::quantized_max_pool1d( + self, kernel_size, stride, padding, dilation, ceil_mode); + } + + check_max_pool1d(self, kernel_size, stride, padding, dilation, ceil_mode); + if ((self.requires_grad() && at::GradMode::is_enabled()) || + self._fw_grad(/*level */ 0).defined() || + !self.device().is_cpu() || + isTensorSubclassLike(self)) { + // Needs indices for grad and with_indices defines CUDA dispatch + return std::get<0>(at::max_pool1d_with_indices( + self, kernel_size, stride, padding, dilation, ceil_mode)); + } + return max_pool1d_impl( + self, kernel_size, stride, padding, dilation, ceil_mode); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/MaxPooling.h b/western_ai/usa/pytorch/aten/src/ATen/native/MaxPooling.h new file mode 100644 index 0000000000000000000000000000000000000000..1426c513c83fb4b5c929a0fc3345d1f9ebef9039 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/MaxPooling.h @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include +#include + +namespace at::native { + +inline void check_max_pool1d( + const Tensor& self, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) { + + TORCH_CHECK( + self.dim() == 2 || self.dim() == 3, + "max_pool1d() Expected 2D or 3D input tensor, but got ", self.sym_sizes()); + TORCH_CHECK( + kernel_size.size() == 1, + "max_pool1d() kernel_size must be an int, list of ints or tuple of ints of size 1 but got size ", + kernel_size.size()); + TORCH_CHECK( + stride.empty() || stride.size() == 1, + "max_pool1d() stride must be None, an int, list of ints, or tuple of ints of size 1 but got size ", + stride.size()); + TORCH_CHECK( + padding.size() == 1, + "max_pool1d() padding must be an int, list of ints, or tuple of ints of size 1 but got size ", + padding.size()); + TORCH_CHECK( + dilation.size() == 1, + "max_pool1d() dilation must be an int, list of ints or tuple of ints of size 1 but got size ", + dilation.size()); + + // If stride=None then set it to kernel_size + if (stride.empty()) { + stride = kernel_size; + } + + TORCH_CHECK( + kernel_size[0] > 0, + "max_pool1d() kernel_size must be greater than zero, but got ", + kernel_size[0]); + TORCH_CHECK( + stride[0] > 0, "max_pool1d() stride must be greater than zero, but got ", stride[0]); + TORCH_CHECK( + padding[0] >= 0, "max_pool1d() padding must be non-negative, but got ", padding[0]); + TORCH_CHECK( + padding[0] <= kernel_size[0] / 2, + "max_pool1d() padding should be at most half of kernel size, but got padding=", + padding[0], + " and kernel_size=", + kernel_size[0]); + TORCH_CHECK( + dilation[0] > 0, "max_pool1d() dilation must be greater than zero, but got ", dilation[0]); + + const int64_t OW = pooling_output_shape(self.sym_size(-1).guard_int(__FILE__, __LINE__), kernel_size[0], padding[0], stride[0], dilation[0], ceil_mode); + TORCH_CHECK(OW > 0, "max_pool1d() Invalid computed output size: ", OW); +} + +// TODO(Heitor) Template by dimension +struct PoolingParams1D { + int64_t NB; // Number of batches + int64_t NC; // Number of channels + int64_t IW; // Input width + int64_t OW; // Output width + int64_t KW; // Kernel width + int64_t SJ; // Column stride + int64_t PJ; // Column padding + int64_t DJ; // Column dilation + + // Return index of input element for the given kernel and output index + inline int64_t index(int64_t kj, int64_t oj) const { + return oj * SJ + kj * DJ - PJ; + } + + // Return index of first output within bounds for this kernel index + inline int64_t valid_output_start(int64_t kj) const { + int64_t ij = index(kj, 0);; + return ij < 0 ? at::divup(-ij, SJ) : 0; + } + + // Return index one past last output within bounds for this kernel index + inline int64_t valid_output_end(int64_t kj) const { + int64_t ij = index(kj, OW - 1); + return ij >= IW ? OW - at::divup(ij - (IW - 1), SJ) : OW; + } +}; + +using pooling_fn = void (*)(Tensor&, const Tensor&, const PoolingParams1D&); + +DECLARE_DISPATCH(pooling_fn, max_pool1d_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/MaxUnpooling.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/MaxUnpooling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c9117a492c2b9e3cb2b337afecc15bd194d5462 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/MaxUnpooling.cpp @@ -0,0 +1,227 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { + +Tensor& max_unpooling2d_forward_out_cpu( + const Tensor& self_, + const Tensor& indices_, + IntArrayRef output_size, + Tensor& output) { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic with duplicate indices + at::globalContext().alertNotDeterministic("max_unpooling2d_forward_out"); + + TORCH_CHECK( + indices_.scalar_type() == at::ScalarType::Long, + "elements in indices should be type int64 but got: ", indices_.scalar_type()); + TORCH_CHECK( + output_size.size() == 2, + "There should be exactly two elements (height, width) in output_size, but got ", output_size.size(), " elements."); + TORCH_CHECK( + (self_.ndimension() == 3 || self_.ndimension() == 4), + "Input to max_unpooling2d should be a 3d or 4d Tensor, but got a tensor with ", self_.ndimension(), " dimensions."); + TORCH_CHECK( + self_.sizes() == indices_.sizes(), + "Expected shape of indices to be same as that of the input tensor (", self_.sizes(), + ") but got indices tensor with shape: ", indices_.sizes()); + + for (const auto i : c10::irange(1, self_.ndimension())) { + TORCH_CHECK(self_.size(i) > 0, "max_unpooling2d_forward_out_cpu(): ", + "Expected input to have non-zero size for non-batch dimensions, but got ", + self_.sizes(), " with dimension ", i , " being empty."); + } + + auto oheight = output_size[0]; + auto owidth = output_size[1]; + TORCH_CHECK( + oheight >= 0 && owidth >= 0, + "max_unpooling2d(): output_size must contain non-negative spatial dimensions, but got output_size=(", + oheight, + ", ", + owidth, + ")"); + + auto memory_format = self_.suggest_memory_format(); + auto self = self_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + if (self.ndimension() == 3) { + int64_t numChannels = self.size(0); + output.resize_({numChannels, oheight, owidth}); + } else { + int64_t numBatch = self.size(0); + int64_t numChannels = self.size(1); + output.resize_({numBatch, numChannels, oheight, owidth}, memory_format); + } + output.zero_(); + + if (output.numel() != 0) { + max_unpool2d_kernel(kCPU, output, self, indices); + } + + return output; +} + +Tensor max_unpooling2d_forward_cpu( + const Tensor& self, + const Tensor& indices, + IntArrayRef output_size) { + auto output = at::empty({0}, self.options()); + at::native::max_unpooling2d_forward_out_cpu(self, indices, output_size, output); + return output; +} + +static void max_unpooling3d_shape_check( + const Tensor& input, + const Tensor& gradOutput, + const Tensor& indices, + IntArrayRef output_size, + IntArrayRef stride, + IntArrayRef padding, + const char *fn_name) { + + TORCH_CHECK( + indices.scalar_type() == at::ScalarType::Long, + "elements in indices should be type int64"); + TORCH_CHECK( + (input.ndimension() == 4 || input.ndimension() == 5), + "Input to max_unpooling3d should be a 4d or 5d Tensor, but got a tensor with ", input.ndimension(), " dimensions."); + TORCH_CHECK( + output_size.size() == 3, + "There should be exactly three elements (depth, height, width) in output_size, but got ", output_size.size(), " elements."); + TORCH_CHECK( + stride.size() == 3, + "There should be exactly three elements (depth, height, width) in stride, but got: ", stride.size(), " elements."); + TORCH_CHECK( + padding.size() == 3, + "There should be exactly three elements (depth, height, width) in padding, but got: ", padding.size(), " elements."); + TORCH_CHECK( + input.sizes() == indices.sizes(), + "Expected shape of indices to be same as that of the input tensor (", input.sizes(), + ") but got indices tensor with shape: ", indices.sizes()); + + for (const auto i : c10::irange(1, input.ndimension())) { + TORCH_CHECK(input.size(i) > 0, fn_name, + ": Expected input to have non-zero size for non-batch dimensions, but got ", + input.sizes(), " with dimension ", i , " being empty."); + } + + TORCH_CHECK( + stride[0] > 0 && stride[1] > 0 && stride[2] > 0, + "strides should be greater than zero, but got stride: ", + stride); + + int64_t oT = output_size[0]; + int64_t oH = output_size[1]; + int64_t oW = output_size[2]; + TORCH_CHECK( + oT >= 0 && oH >= 0 && oW >= 0, + "max_unpooling3d(): output_size must contain non-negative spatial dimensions, but got output_size=(", + oT, + ", ", + oH, + ", ", + oW, + ")"); + + int dimw = 3; + int dimh = 2; + int dimt = 1; + int dimn = 0; + + if (input.ndimension() == 5) { + dimw++; + dimh++; + dimt++; + dimn++; + } + + int nslices = input.size(dimn); + + if (gradOutput.defined()) { + if (oT != gradOutput.size(dimt) || oH != gradOutput.size(dimh) || + oW != gradOutput.size(dimw)) { + TORCH_CHECK(false, + "Inconsistent gradOutput size. oT= ", + oT, + ", oH= ", + oH, + ", oW= ", + oW, + ". gradOutput: ", + gradOutput.size(dimt), + "x", + gradOutput.size(dimh), + "x", + gradOutput.size(dimw)); + } + TORCH_CHECK( + gradOutput.ndimension() == input.ndimension() && + gradOutput.size(dimn) == nslices, + "gradOutput and input Tensors should have same number of dimensions and also the same number of channels/slices"); + } +} + +Tensor& max_unpooling3d_forward_out_cpu(const Tensor& self_, + const Tensor& indices_, + IntArrayRef output_size, + IntArrayRef stride, + IntArrayRef padding, + Tensor& output) { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic with duplicate indices + at::globalContext().alertNotDeterministic("max_unpooling3d_forward_out"); + + TORCH_CHECK(output.is_contiguous(), "output must be contiguous"); + + auto self = self_.contiguous(); + auto indices = indices_.contiguous(); + + max_unpooling3d_shape_check( + self_, Tensor(), indices_, output_size, stride, padding, "max_unpooling3d_forward_out_cpu()"); + + int64_t oT = output_size[0]; + int64_t oH = output_size[1]; + int64_t oW = output_size[2]; + + if (self_.ndimension() == 5) { + output.resize_({self.size(0), self.size(1), oT, oH, oW}); + } else { + output.resize_({self.size(0), oT, oH, oW}); + } + output.zero_(); + if (output.numel() != 0) { + max_unpool3d_kernel(kCPU, output, self, indices); + } + + return output; +} + +Tensor max_unpooling3d_forward_cpu( + const Tensor& self, + const Tensor& indices, + IntArrayRef output_size, + IntArrayRef stride, + IntArrayRef padding) { + auto output = at::empty({0}, self.options()); + at::native::max_unpooling3d_forward_out_cpu( + self, indices, output_size, stride, padding, output); + return output; +} + +DEFINE_DISPATCH(max_unpool2d_kernel); +DEFINE_DISPATCH(max_unpool3d_kernel); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/Memory.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/Memory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22aa40537643477a9bffcb2377f376d434e82d3c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/Memory.cpp @@ -0,0 +1,75 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +// Exposes at::has_internal_overlap as an operator for testing purposes +int64_t _debug_has_internal_overlap(const Tensor& self) { + return static_cast(at::has_internal_overlap(self)); +} + +bool is_pinned(const Tensor& self, std::optional device) { + std::optional opt_device_type; + if (device.has_value()) { + TORCH_WARN_DEPRECATION( + "The argument 'device' of Tensor.is_pinned() ", + "is deprecated. Please do not pass this argument.") + opt_device_type = device.value().type(); + } + // Only CPU tensors can be pinned + if (!self.is_cpu()) { + return false; + } + // Use getAcceleratorHooksInterface to make is_pinned device-agnostic + return at::globalContext().isPinnedPtr(self.storage().data(), opt_device_type); +} + +Tensor pin_memory(const Tensor& self, std::optional device) { + if (device.has_value()) { + TORCH_WARN_DEPRECATION( + "The argument 'device' of Tensor.pin_memory() ", + "is deprecated. Please do not pass this argument.") + } + // Kind of mad that I have to do two dynamic dispatches here, pretty + // annoying + if (self.is_pinned(device)) { + return self; + } + return at::_pin_memory(self, device); +} + +Tensor _pin_memory(const Tensor& self, std::optional device) { + TORCH_CHECK(self.device().is_cpu(), "cannot pin '", self.toString(), "' only dense CPU tensors can be pinned"); + // Use getAcceleratorHooksInterface to make pin_memory device-agnostic + auto* allocator = device.has_value()? + at::globalContext().getPinnedMemoryAllocator(device.value().type()): + at::globalContext().getPinnedMemoryAllocator(); + auto storage = Storage( + Storage::use_byte_size_t(), + detail::computeStorageNbytes( + self.sizes(), self.strides(), self.dtype().itemsize()), + allocator, + /*resizable=*/false); + auto tensor = at::cpu::empty({0}, self.options()).set_(storage, 0, self.sizes(), self.strides()); + tensor.copy_(self); + return tensor; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/MetaTensor.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/MetaTensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0a1c42b7abc55e0a469b8a2ba5c590439f3e902 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/MetaTensor.cpp @@ -0,0 +1,43 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at::native { + +Tensor empty_meta_symint( + SymIntArrayRef size, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt, + std::optional memory_format_opt +) { + + auto opt_size = asIntArrayRefSlowOpt(size); + if (opt_size.has_value()) { + return at::detail::empty_meta(*opt_size, dtype_opt, layout_opt, device_opt, pin_memory_opt, memory_format_opt); + } + return at::detail::empty_symint_meta( + size, dtype_opt, layout_opt, device_opt, pin_memory_opt, memory_format_opt); +} + +Tensor empty_strided_meta_symint( + SymIntArrayRef size, + SymIntArrayRef stride, + std::optional dtype_opt, + std::optional layout_opt, + std::optional device_opt, + std::optional pin_memory_opt +) { + return at::detail::empty_strided_symint_meta( + size, stride, dtype_opt, layout_opt, device_opt); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/README b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/README new file mode 100644 index 0000000000000000000000000000000000000000..3c6745759f85518c9803c46359bffcf607afe5aa --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/README @@ -0,0 +1,23 @@ +For C++ implementation, there are no plans to migrate quantization kernels. For sparsity, we plan to follow the structure below: + +./torch/aten/src/ATen +├── (...) +├── native +│ ├── ao_sparse # New folder containing ops with sparse packed weights +│ │ ├── cpu +│ │ ├── cuda +│ │ └── quantized # New folder with fused sparse and quantized packed weights +│ │ ├── cpu +│ │ └── cuda +│ ├── quantized # Existing quantized kernels +│ │ ├── cpu +│ │ │ ├── kernels +│ │ │ └── qnnpack # Existing mobile quantized and sparse kernels +│ │ ├── cuda +│ │ ├── QTensor.cpp +│ │ ├── library.cpp +│ │ └── (*.cpp, *.h) +│ └── sparse # Existing folder containing torch.sparse methods +└── quantized # Quantized Tensor definition and methods + ├── QTensorImpl.{cpp,h} + └── Quantizer.{cpp,h} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/library.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/library.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0aa08dcc61405062b4bca3647cee358889b2e25e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/library.cpp @@ -0,0 +1,27 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include + +// Register operators +TORCH_LIBRARY(sparse, m) { + ao::sparse::register_linear_params(); + + m.def(TORCH_SELECTIVE_SCHEMA( + "sparse::qlinear(Tensor X, __torch__.torch.classes.sparse.LinearPackedParamsBase W_prepack, float Y_scale_i, int Y_zero_point_i) -> Tensor Y")); + m.def(TORCH_SELECTIVE_SCHEMA( + "sparse::qlinear_relu(Tensor X, __torch__.torch.classes.sparse.LinearPackedParamsBase W_prepack, float Y_scale_i, int Y_zero_point_i) -> Tensor Y")); + + m.def(TORCH_SELECTIVE_SCHEMA( + "sparse::qlinear_dynamic(Tensor X, __torch__.torch.classes.sparse.LinearPackedParamsBase W_prepack) -> Tensor Y")); + m.def(TORCH_SELECTIVE_SCHEMA( + "sparse::qlinear_relu_dynamic(Tensor X, __torch__.torch.classes.sparse.LinearPackedParamsBase W_prepack) -> Tensor Y")); + + m.def(TORCH_SELECTIVE_SCHEMA( + "sparse::qlinear_prepack(Tensor W, Tensor? B, int out_features_block_size, int in_features_block_size) -> __torch__.torch.classes.sparse.LinearPackedParamsBase W_prepack")); + + m.def(TORCH_SELECTIVE_SCHEMA( + "sparse::qlinear_unpack(__torch__.torch.classes.sparse.LinearPackedParamsBase W_prepack) -> (Tensor W_origin, Tensor? B_origin, int[] block_pattern)")); +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2adcd3ad945984435f4486ad94ab0b1024b0413 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.cpp @@ -0,0 +1,44 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#include + +#include +#include +#include + +namespace ao::sparse { +int register_linear_params() { + [[maybe_unused]] static auto register_linear_params = + torch::selective_class_( + "sparse", TORCH_SELECTIVE_CLASS("LinearPackedParamsBase")) + .def_pickle( + [](const c10::intrusive_ptr& params) + -> BCSRSerializationType { // __getstate__ + return params->serialize(); + }, + [](BCSRSerializationType state) + -> c10::intrusive_ptr< + LinearPackedParamsBase> { // __setstate__ +#ifdef USE_FBGEMM + if (at::globalContext().qEngine() == at::QEngine::FBGEMM) { + return PackedLinearWeight::deserialize(state); + } +#endif // USE_FBGEMM +#ifdef USE_PYTORCH_QNNPACK + if (at::globalContext().qEngine() == at::QEngine::QNNPACK) { + return PackedLinearWeightQnnp::deserialize(state); + } +#endif // USE_FBGEMM + TORCH_CHECK(false, "Unknown qengine"); + }); + // (1) we can't (easily) return the static initializer itself because it can have a different type because of selective build + // (2) we can't return void and be able to call the function in the global scope + return 0; +} + +namespace { +[[maybe_unused]] auto linear_params = register_linear_params(); +} // namespace +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.h b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..4155efc708cc0199ff5aa0453125a0d20768d251 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/fbgemm_utils.h @@ -0,0 +1,97 @@ +#pragma once + +#include +#include + +#ifdef USE_FBGEMM +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi") +#include +#include +#include +C10_DIAGNOSTIC_POP() + + +namespace ao::sparse { + +struct TORCH_API PackedLinearWeight + : public LinearPackedParamsBase { + PackedLinearWeight(std::unique_ptr> w, + std::optional bias, + std::vector col_offsets, + std::vector w_scale, + std::vector w_zp, + c10::QScheme q_scheme, + const int64_t out_features_block_size /* block sparsity size across output_features */, + const int64_t in_features_block_size /* block sparsity size across input_features */) + : LinearPackedParamsBase( + out_features_block_size, + in_features_block_size), + w(std::move(w)), + bias_(std::move(bias)), + col_offsets(std::move(col_offsets)), + w_scale(std::move(w_scale)), + w_zp(std::move(w_zp)), + q_scheme(q_scheme) {} + std::unique_ptr> w; + std::optional bias_; + std::vector col_offsets; + std::vector w_scale; + std::vector w_zp; + c10::QScheme q_scheme; + + at::Tensor apply( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override; + at::Tensor apply_relu( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override; + + at::Tensor apply_dynamic(const at::Tensor& input) override { + TORCH_INTERNAL_ASSERT( + false, + "Sparse quantized dynamic linear with fused relu is not yet " + "supported on qnnpack backend."); + return at::Tensor(); + } + at::Tensor apply_dynamic_relu(const at::Tensor& input) override { + TORCH_INTERNAL_ASSERT( + false, + "Sparse quantized dynamic linear with fused relu is not yet " + "supported on qnnpack backend."); + return at::Tensor(); + } + + LinearPackedSerializationType unpack() override; + + BCSRSerializationType serialize() override; + + static c10::intrusive_ptr deserialize( + const BCSRSerializationType& serialized); + + std::optional bias() override { + return bias_; + } + + static c10::intrusive_ptr prepack( + const at::Tensor& weight, + const std::optional& bias, + const int64_t out_features_block_size, + const int64_t in_features_block_size); + + private: + template + at::Tensor apply_impl( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point); +}; + +} // namespace ao::sparse + +#endif // USE_FBGEMM + +namespace ao::sparse { +int register_linear_params(); +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/packed_params.h b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/packed_params.h new file mode 100644 index 0000000000000000000000000000000000000000..bbaf727001c137a6e5aa375a077d26418a816e6f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/packed_params.h @@ -0,0 +1,73 @@ +#pragma once + +#include + +#include +#include + +namespace ao::sparse { + +// +using LinearPackedSerializationType = + std::tuple, std::vector>; + +#define SPARSE_LINEAR_PACKED_PARAM_SERIALIZATION_VERSION 2 + +using BCSRSerializationType = + std::tuple< + int64_t, // Serialization Version + std::optional, // Bias + int64_t, // Out Features (Row) Block Size + int64_t, // In Features (Column) Block Size + at::Tensor, // Weight Scales (single element vector if per-tensor) (float) + at::Tensor, // Wrapper for Weight Zero Points (single element vector if per-tensor) (int8_t) + bool, // Quantization Scheme (true: per tensor, false: per channel) + at::Tensor, // Wrapper for Row Block Indices (int8_t, int16_t, or int32_t) + at::Tensor, // Wrapper for Column Block Indices (int8_t, int16_t, or int32_t) + at::Tensor, // Wrapper for Non-Zero Weight Values, each +128 (uint8_t) + int64_t, // Number of Output Channels + int64_t // Number of Input Channels + >; + +using BCSR = + std::tuple< + std::vector, // Non-Zero Weight Values + std::vector, // Compressed Row Block Indices + std::vector // Column Block Indices + >; + +struct LinearPackedParamsBase : public torch::jit::CustomClassHolder { + public: + LinearPackedParamsBase( + const int64_t out_features_block_size, + const int64_t in_features_block_size) + : out_features_block_size_(out_features_block_size), + in_features_block_size_(in_features_block_size) {} + + virtual at::Tensor apply( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) = 0; + virtual at::Tensor apply_relu( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) = 0; + + virtual at::Tensor apply_dynamic(const at::Tensor& input) = 0; + virtual at::Tensor apply_dynamic_relu(const at::Tensor& input) = 0; + + virtual LinearPackedSerializationType unpack() = 0; + + virtual BCSRSerializationType serialize() = 0; + + virtual std::optional bias() = 0; + + virtual void set_bias(const std::optional& bias) { + TORCH_CHECK(false, "set_bias is not implemented for this packed parameter type"); + } + + protected: + const int64_t out_features_block_size_, in_features_block_size_; +}; + +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9837885cfe375790ee352132d154dc90a50d13f6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear.cpp @@ -0,0 +1,259 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace ao::sparse { + + + +#ifdef USE_FBGEMM + +template +at::Tensor PackedLinearWeight::apply_impl( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) { + // uint8 * int8 -> uint8 (no quantization/dequantization) + + // We make a strong guarantee that models using these operators will have + // the same numerics across different machines. Therefore, we do not provide + // a fallback path and rather fail loudly if we cannot run FBGEMM. + TORCH_CHECK( + fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM."); + + // TODO: contiguous is called for further jit optimizations. + auto input_contig = input.contiguous(); + const auto* input_ptr = + reinterpret_cast(input_contig.const_data_ptr()); + + TORCH_CHECK( + input.dim() >= 2, + "The dimension of input tensor should be larger than or equal to 2"); + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + int64_t batch_size = size_to_dim_(input.dim() - 1, input.sizes()); + + auto packW = w.get(); + + int64_t out_channels = static_cast(packW->R); + int64_t K = input.size(input.dim() - 1); + TORCH_CHECK( + K == static_cast(packW->C), + "The number of columns in the packW should be equal to K: " + + std::to_string(K)); + + // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions,bugprone-narrowing-conversions) + float input_scale_float = input.q_scale(); + int32_t input_zero_point_int32 = input.q_zero_point(); + + std::vector output_multiplier_float(1, 0.0); + std::vector act_times_w_scale(1, 0.0); + TORCH_CHECK( + w_scale.size() == w_zp.size(), + "Weight scales and zero points vectors should have the same size."); + if (q_scheme == c10::kPerTensorAffine) { + // Process the per tensor quantization. + act_times_w_scale[0] = (input_scale_float * w_scale[0]); + output_multiplier_float[0] = + act_times_w_scale[0] / static_cast(output_scale); + } else if (q_scheme == c10::kPerChannelAffine) { + // Process the per channel quantization. + output_multiplier_float.resize(out_channels, 0.0); + act_times_w_scale.resize(out_channels, 1.0f); + for (const auto i : c10::irange(out_channels)) { + act_times_w_scale[i] = (input_scale_float * w_scale[i]); + output_multiplier_float[i] = + act_times_w_scale[i] / static_cast(output_scale); + } + } + int32_t output_zero_point_int32 = static_cast(output_zero_point); + + const float* bias_ptr = nullptr; + at::Tensor bias; + if (this->bias_.has_value()) { + bias = this->bias_.value(); + bias = bias.contiguous(); + TORCH_CHECK(bias.dim() == 1, "bias should be a vector (1D Tensor)"); + TORCH_CHECK( + bias.size(0) == out_channels, + "bias should have out_channels elements: " + + std::to_string(out_channels)); + bias_ptr = reinterpret_cast(bias.data_ptr()); + } + + // The resulting matrix here is 2-D, let's view it with the original + // left hand dimensions of the input. Here are two examples: + // 1. If the input tensor is {batch_size, K}, the output tensor is + // {batch_size, out_channels}. + // 2. If the input tensor is {x, batch_size, K}, the output tensor is {x, + // batch_size, out_channels}. + std::vector out_sizes = input.sizes().vec(); + out_sizes.back() = out_channels; + // Allocate output Tensor and a buffer for fbgemmPacked to use + auto output_tr = at::_empty_affine_quantized( + out_sizes, + at::device(c10::kCPU).dtype(c10::kQUInt8), + output_scale, + output_zero_point); + auto output = at::_empty_affine_quantized( + out_sizes, + at::device(c10::kCPU).dtype(c10::kQUInt8), + output_scale, + output_zero_point); + + auto buffer = at::empty(out_sizes, output.options().dtype(at::kInt)); + + // fbgemm kernel computes the following: + // C(output) = A(weight) x B(input), where C, A, B are out_channels x + // batch_size, out_channels x K, K x batch_size matrices, respectively. + // Therefore we need to transpose input + auto input_tr = at::_empty_affine_quantized( + input.sizes(), + at::device(c10::kCPU).dtype(c10::kQUInt8), + input_scale_float, + input_zero_point_int32); + + auto* input_tr_ptr = + reinterpret_cast(input_tr.data_ptr()); + // TODO: Activation transpose before and after the kernel can be removed if we + // keep activation tensor always transposed. + fbgemm::transpose_simd( + batch_size, K, input_ptr, K, input_tr_ptr, batch_size); + + int num_tasks = at::get_num_threads(); + at::parallel_for(0, num_tasks, 1, [&](int64_t begin, int64_t end) { + for (const auto task_id : c10::irange(begin, end)) { + fbgemm::trRequantizationParams_t reqParams = { + input_zero_point_int32, + w_zp.data(), + output_zero_point_int32, + static_cast(output_scale), + col_offsets.data(), + /*activation offsets*/ nullptr, + bias_ptr, + act_times_w_scale.data()}; + + if (q_scheme == c10::kPerTensorAffine) { + // Process the per tensor quantization. + // + // After the uint8 * int8 matrix multiplication is performed, this + // operation does: + // 1) Add in row and column offsets to the rows and columns, + // respectively. + // 2) Add in the bias term. + + // Do the GEMM + fbgemm::fbgemmSparseDenseInt8MM< + ReluFused, + fbgemm::QuantizationGranularity::TENSOR>( + batch_size, + w, + input_tr_ptr, + /*ldb=*/batch_size, + /*C_i32=*/buffer.data_ptr(), + /*C_u8=*/ + reinterpret_cast(output_tr.data_ptr()), + /*ldc=*/batch_size, + /*rParams=*/reqParams, + /*accum=*/false, + /*thread_id=*/task_id, + /*num_threads=*/num_tasks); + } else if (q_scheme == c10::kPerChannelAffine) { + // Process the per channel quantization. + // + // After the uint8 * int8 matrix multiplication is performed, this + // operation does: + // 1) Add in row and column offsets to the rows and columns, + // respectively. + // 2) Add in the bias term. + + // Do the GEMM + fbgemm::fbgemmSparseDenseInt8MM< + ReluFused, + fbgemm::QuantizationGranularity::OUT_CHANNEL>( + batch_size, + w, + input_tr_ptr, + /*ldb=*/batch_size, + /*C_i32=*/buffer.data_ptr(), + /*C_u8=*/ + reinterpret_cast(output_tr.data_ptr()), + /*ldc=*/batch_size, + /*rParams=*/reqParams, + /*accum*/ false, + /*thread_id=*/task_id, + /*num_threads=*/num_tasks); + } + } + }); + + // transpose output_tr back to batch_size x out_channels + fbgemm::transpose_simd( + out_channels, + batch_size, + reinterpret_cast(output_tr.data_ptr()), + batch_size, + reinterpret_cast(output.data_ptr()), + out_channels); + + return output; +} + +at::Tensor PackedLinearWeight::apply( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) { + return apply_impl(input, output_scale, output_zero_point); +} + +at::Tensor PackedLinearWeight::apply_relu( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) { + return apply_impl(input, output_scale, output_zero_point); +} + +#endif // USE_FBGEMM + +namespace { + +template +class QLinearInt8 final { + public: + static at::Tensor run( + const at::Tensor& input, + const c10::intrusive_ptr& packed_weight, + double output_scale, + int64_t output_zero_point) { + if (ReluFused) { + return packed_weight->apply_relu(input, output_scale, output_zero_point); + } else { + return packed_weight->apply(input, output_scale, output_zero_point); + } + } +}; + +TORCH_LIBRARY_IMPL(sparse, QuantizedCPU, m) { + register_linear_params(); + m.impl( + TORCH_SELECTIVE_NAME("sparse::qlinear"), + TORCH_FN(QLinearInt8::run)); + m.impl( + TORCH_SELECTIVE_NAME("sparse::qlinear_relu"), + TORCH_FN(QLinearInt8::run)); +} + +} // namespace +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_deserialize.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_deserialize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35784c269fe4e952e1257d84964f35ba7c1dfb78 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_deserialize.cpp @@ -0,0 +1,316 @@ +#include + +#ifdef USE_FBGEMM +#include +#endif +#ifdef USE_PYTORCH_QNNPACK +#include +#endif + +namespace ao::sparse { + +namespace { +constexpr int64_t serialization_version_index [[maybe_unused]] = 0; +constexpr int64_t bias_index [[maybe_unused]] = 1; +constexpr int64_t out_features_block_size_index [[maybe_unused]] = 2; +constexpr int64_t in_features_block_size_index [[maybe_unused]] = 3; +constexpr int64_t weight_scales_index [[maybe_unused]] = 4; +constexpr int64_t weight_zero_point_index [[maybe_unused]] = 5; +constexpr int64_t quantization_scheme_index [[maybe_unused]] = 6; +constexpr int64_t row_block_indices_index [[maybe_unused]] = 7; +constexpr int64_t col_block_indices_index [[maybe_unused]] = 8; +constexpr int64_t weight_values_index [[maybe_unused]] = 9; +constexpr int64_t num_output_channels_index [[maybe_unused]] = 10; +constexpr int64_t num_input_channels_index [[maybe_unused]] = 11; + +template +std::vector unwrap_vector(at::Tensor tensor) { + std::vector vec(tensor.numel()); + const TENSOR_DTYPE* tensor_data_ptr = tensor.const_data_ptr(); + std::copy(tensor_data_ptr, tensor_data_ptr + tensor.numel(), vec.data()); + return vec; +} + +#ifdef USE_FBGEMM +/** + * Adapted from Fbgemm BCSRMatrix::unpack, but with non-zero zero points and + * without tiling + * https://github.com/pytorch/FBGEMM/blob/9d7c48a65419d0350f9e9e72f31e05bfe37e85a4/src/FbgemmSparseDense.cc#L154 + */ +void unpack_bcsr( + int8_t* dst, + ao::sparse::BCSR bcsr, + const int64_t R, + const int64_t C, + const int64_t RB, + const int64_t CB, + const int8_t* zero_points, + const bool qscheme_per_tensor) { + const size_t ld = C; + // zero out destination + if (qscheme_per_tensor) { + memset(dst, zero_points[0], R * C * sizeof(int8_t)); + } else { + for (int64_t i = 0; i < R; i++) { + memset(dst + i * C, zero_points[i], C * sizeof(int8_t)); + } + } + const auto& [weight_values, row_indices, col_indices] = bcsr; + int64_t rowBlocks = (R + RB - 1) / RB; + for (int64_t i = 0; i < rowBlocks; ++i) { + // For the current tile, rowBPtr starts from currentTileIdx + for (int64_t r = row_indices[i]; r < row_indices[i + 1]; ++r) { + int64_t curColIdx = col_indices[r]; + for (int64_t ib = 0; ib < RB; ++ib) { + for (int64_t jb = 0; jb < CB; ++jb) { + // Are we within bounds of destination matrix? + if ((i * RB + ib) < R && (curColIdx * CB + jb) < C) { + dst[(i * RB + ib) * ld + curColIdx * CB + jb] = + weight_values[r * RB * CB + ib * CB + jb]; + } + } + } + } + } +} +#endif // USE_FBGEMM +} // namespace + +#ifdef USE_FBGEMM + +c10::intrusive_ptr PackedLinearWeight::deserialize( + const BCSRSerializationType& serialized) { + const int64_t out_features_block_size = + std::get(serialized); + const int64_t in_features_block_size = + std::get(serialized); + const c10::QScheme q_scheme = std::get(serialized) + ? c10::kPerTensorAffine + : c10::kPerChannelAffine; + const int64_t output_channels = + std::get(serialized); + const int64_t input_channels = std::get(serialized); + // Unpack the untiled bcsr, then pack it in tiled form + at::Tensor weight_origin; + const at::Tensor weight_zero_points = + std::get(serialized); + if (q_scheme == c10::kPerTensorAffine) { + weight_origin = at::_empty_affine_quantized( + {output_channels, input_channels}, + at::device(c10::kCPU).dtype(c10::kQInt8), + std::get(serialized).data_ptr()[0], + weight_zero_points.data_ptr()[0]); + } else if (q_scheme == c10::kPerChannelAffine) { + weight_origin = at::_empty_per_channel_affine_quantized( + {output_channels, input_channels}, + std::get(serialized), + weight_zero_points, + 0, // The output channel axis is 0 + at::device(c10::kCPU).dtype(c10::kQInt8)); + } + + const at::Tensor loaded_weight_values = + std::get(serialized); + const uint8_t* loaded_weight_values_ptr = + loaded_weight_values.const_data_ptr(); + const int64_t loaded_weight_values_size = loaded_weight_values.numel(); + // Subtract 128 because we serialize as +128, which s best for + // minimizing memory footprint for QNNPack + std::vector weight_values(loaded_weight_values_size); + std::transform( + loaded_weight_values_ptr, + loaded_weight_values_ptr + loaded_weight_values_size, + weight_values.begin(), + [](uint8_t v) { + return static_cast(static_cast(v) - 128); + }); + + const at::Tensor row_block_indices = + std::get(serialized); + const at::Tensor col_block_indices = + std::get(serialized); + // Unpack as non backend specific untiled BCSR then pack as Fbgemm tiled BCSR + // because untiled Fbgemm BCSR currently doesn't exist + unpack_bcsr( + reinterpret_cast(weight_origin.data_ptr()), + AT_DISPATCH_INTEGRAL_TYPES( + row_block_indices.scalar_type(), + "packed_linear_weight_fbgemm_setup_bcsr", + [&] { + return ao::sparse::BCSR( + std::move(weight_values), + unwrap_vector( + std::get(serialized)), + unwrap_vector( + std::get(serialized))); + }), + output_channels, + input_channels, + out_features_block_size, + in_features_block_size, + weight_zero_points.data_ptr(), + q_scheme == c10::kPerTensorAffine); + + return PackedLinearWeight::prepack( + weight_origin, + std::get(serialized), + out_features_block_size, + in_features_block_size); +} + +#endif // USE_FBGEMM + +#ifdef USE_PYTORCH_QNNPACK + +c10::intrusive_ptr PackedLinearWeightQnnp::deserialize( + const BCSRSerializationType& serialized) { + return c10::make_intrusive(serialized); +} + +template +struct UnsignedIndicesTypeTrait { + static_assert( + sizeof(INDICES_DTYPE) == 0, + "Invalid dtype for UnsignedIndicesTypeTrait"); +}; + +template <> +struct UnsignedIndicesTypeTrait { + using t = uint32_t; +}; + +template <> +struct UnsignedIndicesTypeTrait { + using t = uint16_t; +}; + +template <> +struct UnsignedIndicesTypeTrait { + using t = uint8_t; +}; + +PackedLinearWeightQnnp::PackedLinearWeightQnnp( + const BCSRSerializationType& serialized) + : LinearPackedParamsBase( + std::get(serialized), + std::get(serialized)), + orig_bias_(std::get(serialized)), + q_scheme_( + std::get(serialized) + ? c10::kPerTensorAffine + : c10::kPerChannelAffine), + output_channels_(std::get(serialized)), + input_channels_(std::get(serialized)) { + const int64_t serialization_version = + std::get(serialized); + TORCH_CHECK( + serialization_version <= SPARSE_LINEAR_PACKED_PARAM_SERIALIZATION_VERSION, + "Attempted to deserialize sparse qlinear packed params with an ", + "incompatible serialization version (", + serialization_version, + " > ", + SPARSE_LINEAR_PACKED_PARAM_SERIALIZATION_VERSION, + ")"); + + if (orig_bias_.has_value()) { + bias_ = orig_bias_.value(); + + TORCH_CHECK( + (bias_.ndimension() == 1 && bias_.size(0) == output_channels_), + "ao::sparse::qlinear_deserialize (qnnpack): Given weight of size ", + "{", + output_channels_, + ", ", + input_channels_, + "}", + ", expected bias to be 1-dimensional with ", + output_channels_, + " elements", + ", but got bias of size ", + bias_.sizes(), + " instead"); + } else { + bias_ = at::zeros(output_channels_, at::device(at::kCPU).dtype(at::kFloat)); + } + + // Pad amount (8) comes from make_zero_points_and_scales_tensor + // https://github.com/pytorch/pytorch/blob/f8c1acea1e78573c04cd18893c4abff9eea64b03/aten/src/ATen/native/quantized/cpu/qnnpack_utils.h#L468 + const int64_t output_channels_padded = output_channels_ + 8; + + w_scales_ = at::empty( + {output_channels_padded}, at::device(at::kCPU).dtype(at::kFloat)); + float* w_scales_data_ptr = w_scales_.mutable_data_ptr(); + std::fill_n( + w_scales_data_ptr + output_channels_, + output_channels_padded - output_channels_, + 1); // Pad with 1 + + w_zero_points_ = + std::vector(output_channels_padded, 0); // Pad with 0; + + const float* w_scales_orig_data_ptr = + std::get(serialized).const_data_ptr(); + const int8_t* w_zp_orig_data_ptr = + std::get(serialized).const_data_ptr(); + + const std::function add_128 = [](int8_t v) { + return static_cast(static_cast(v) + 128); + }; + + if (q_scheme_ == at::kPerTensorAffine) { + std::fill_n(w_scales_data_ptr, output_channels_, w_scales_orig_data_ptr[0]); + std::fill_n( + w_zero_points_.begin(), output_channels_, w_zp_orig_data_ptr[0] + 128); + } else if (q_scheme_ == at::kPerChannelAffine) { + std::copy( + w_scales_orig_data_ptr, + w_scales_orig_data_ptr + output_channels_, + w_scales_data_ptr); + std::transform( + w_zp_orig_data_ptr, + w_zp_orig_data_ptr + output_channels_, + w_zero_points_.begin(), + add_128); + } else { + TORCH_CHECK(false, "Unsupported quantization scheme."); + } + + deserialized_bcsr_row_block_indices_ = + std::get(serialized); + deserialized_bcsr_col_block_indices_ = + std::get(serialized); + deserialized_bcsr_weight_values_ = std::get(serialized); + +#define AT_DISPATCH_CASE_BCSR_INDICES_TYPES(...) \ + AT_DISPATCH_CASE(at::ScalarType::Char, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Int, __VA_ARGS__) \ + AT_DISPATCH_CASE(at::ScalarType::Short, __VA_ARGS__) + +#define AT_DISPATCH_BCSR_INDICES_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, NAME, AT_DISPATCH_CASE_BCSR_INDICES_TYPES(__VA_ARGS__)) + + bcsr_matrix_ = AT_DISPATCH_BCSR_INDICES_TYPES( + deserialized_bcsr_row_block_indices_.scalar_type(), + "packed_linear_weight_qnnp_setup_bcsr", + [&] { + using unsigned_t = UnsignedIndicesTypeTrait::t; + return qnnpack::generateBlockCSRMatrix( + reinterpret_cast( + deserialized_bcsr_col_block_indices_.data_ptr()), + reinterpret_cast( + deserialized_bcsr_row_block_indices_.data_ptr()), + deserialized_bcsr_weight_values_.data_ptr(), + deserialized_bcsr_col_block_indices_.numel(), + deserialized_bcsr_row_block_indices_.numel(), + deserialized_bcsr_weight_values_.numel(), + out_features_block_size_, + in_features_block_size_); + }); + +#undef AT_DISPATCH_CASE_BCSR_INDICES_TYPES +#undef AT_DISPATCH_BCSR_INDICES_TYPES +} +#endif // USE_PYTORCH_QNNPACK + +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_dynamic.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_dynamic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ac6fd388c56151866405b7f15d8280e9946029f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_dynamic.cpp @@ -0,0 +1,195 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace ao::sparse { + +#ifdef USE_PYTORCH_QNNPACK +template <> +at::Tensor PackedLinearWeightQnnp::apply_dynamic_impl( + const at::Tensor& input) { + TORCH_INTERNAL_ASSERT( + false, + "Sparse quantized dynamic linear with fused relu is not yet " + "supported on qnnpack backend."); +} + +template <> +at::Tensor PackedLinearWeightQnnp::apply_dynamic_impl( + const at::Tensor& input) { + TORCH_CHECK( + input.dim() >= 2, + "quantized_sparse_linear(): Input tensor rank should be >= 2"); + + const auto rows_input = c10::multiply_integers(input.sizes().begin(), input.sizes().end() - 1); + const auto cols_input = input.size(input.dim() - 1); + TORCH_CHECK( + cols_input == input_channels_, + "quantized_sparse_linear: Input tensor's last and weight tensor's" + " second dimension must match."); + + // On empty input, no output data will be generated, + // so use arbitrary qparams. + float x_min = 0; + float x_max = 0; + // Otherwise... + if (input.numel() > 0) { + x_min = input.min().item(); + x_max = input.max().item(); + } + + auto q_params = quant_utils::ChooseQuantizationParams( + /*min=*/x_min, + /*max=*/x_max, + /*qmin=*/0, + /*qmax=*/255); + + // Quantize input + at::Tensor q_input = at::quantize_per_tensor( + input, q_params.scale, q_params.zero_point, c10::kQUInt8); + + auto q_input_contig = q_input.contiguous(); + if (sparse_linear_op_ == nullptr) { + // We calculate requant scale here as the vector holding the requant scale + // is owned by this module. The pointer is then passed to qnnpack backend. + generate_requantization_scales( + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + w_scales_, q_input_contig.q_scale(), 1.f, requantization_scales_); + input_scale_ = q_input_contig.q_scale(); + pytorch_qnnp_operator_t sparse_linear_op{nullptr}; + pytorch_qnnp_status status = + pytorch_qnnp_create_fully_connected_sparse_dq_nc_q8( + input_channels_, + output_channels_, + q_input_contig.q_zero_point(), + w_zero_points_.data(), + bcsr_matrix_->col_indices_data_ptr(), + bcsr_matrix_->row_values_data_ptr(), + bcsr_matrix_->values.data(), + bcsr_matrix_->row_block_size, /* out_features_block_size */ + bcsr_matrix_->col_block_size, /* in_features_block_size */ + bcsr_matrix_->indices_dtype, + 0, /* output zero point: not used */ + std::numeric_limits::min(), + std::numeric_limits::max(), + 0, /* flags */ + requantization_scales_.data(), + true, /* use prepacking kernel */ + &sparse_linear_op); + TORCH_CHECK( + status == pytorch_qnnp_status_success, + "Failed to create sparse linear operator on" + " qnnpack backend."); + sparse_linear_op_ = + std::unique_ptr( + sparse_linear_op); + } + + // Input on next iteration can be different, thus resulting in + // different input scale. This will require us to recalculate requantization + // scales. + if (input_scale_ != q_input_contig.q_scale()) { + generate_requantization_scales( + // NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions) + w_scales_, q_input_contig.q_scale(), 1.f, requantization_scales_); + } + // Update input related quantization params in the operator. + sparse_linear_op_->dynamic_conv_quantization_params.input_zero_point = + q_input_contig.q_zero_point(); + sparse_linear_op_->dynamic_conv_quantization_params.multipliers = + requantization_scales_.data(); + + std::vector out_sizes = input.sizes().vec(); + out_sizes.back() = output_channels_; + + auto output = at::empty(out_sizes, input.options().dtype(at::kFloat)); + + pytorch_qnnp_status status = + pytorch_qnnp_setup_fully_connected_sparse_dq_nc_q8( + sparse_linear_op_.get(), + rows_input, /* batch size */ + reinterpret_cast(q_input_contig.const_data_ptr()), + cols_input, /* num input channels */ + bias_.const_data_ptr(), + output.data_ptr(), + output_channels_); + TORCH_CHECK( + status == pytorch_qnnp_status_success, + "Failed to setup sparse linear operator on" + " qnnpack backend."); + + status = pytorch_qnnp_run_operator( + sparse_linear_op_.get(), caffe2::pthreadpool_()); + TORCH_CHECK( + status == pytorch_qnnp_status_success, + "Failed to run sparse linear operator on" + " qnnpack backend."); + + return output; +} + +at::Tensor PackedLinearWeightQnnp::apply_dynamic( + const at::Tensor& input) { + return apply_dynamic_impl(input); +} + +at::Tensor PackedLinearWeightQnnp::apply_dynamic_relu( + const at::Tensor& input) { + return apply_dynamic_impl(input); +} + +#endif // USE_PYTORCH_QNNPACK + +namespace { + +template +class QLinearDynamicInt8 final { + public: + static at::Tensor run( + const at::Tensor& input, + const c10::intrusive_ptr& packed_weight) { + auto& ctx = at::globalContext(); +#ifdef USE_PYTORCH_QNNPACK + if (ctx.qEngine() == at::QEngine::QNNPACK) { + if (ReluFused) { + return packed_weight->apply_dynamic_relu(input); + } else { + return packed_weight->apply_dynamic(input); + } + } +#endif + TORCH_CHECK( + false, + "Didn't find engine for operation ao::sparse::qlinear_dynamic", + toString(ctx.qEngine())); + } +}; + +TORCH_LIBRARY_IMPL(sparse, CPU, m) { + m.impl( + TORCH_SELECTIVE_NAME("sparse::qlinear_dynamic"), + TORCH_FN(QLinearDynamicInt8::run)); + m.impl( + TORCH_SELECTIVE_NAME("sparse::qlinear_relu_dynamic"), + TORCH_FN(QLinearDynamicInt8::run)); +} + +} // namespace +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_prepack.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_prepack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44e8180bfa586c4e86cda6af0ee03dc024b3b53a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_prepack.cpp @@ -0,0 +1,247 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +#include + +namespace ao::sparse { + + + +#ifdef USE_FBGEMM +namespace { +// Calculate the column offsets. +// Note this includes the sum of the columns as well as the scalar term +// B_zero_point * K, whereas the row_offsets created by +// packing of activation is only the sum of the A rows. +void calc_col_offsets_transpose( + int K, + int N, + const int8_t* Bint8, + int32_t* B_zero_point, + int32_t* col_offsets, + c10::QScheme qtype) { + for (const auto i : c10::irange(N)) { + int32_t sum = 0; + for (const auto j : c10::irange(K)) { + sum += Bint8[i * K + j]; + } + if (qtype == c10::kPerTensorAffine) { + col_offsets[i] = sum - B_zero_point[0] * K; + } else { + col_offsets[i] = sum - B_zero_point[i] * K; + } + } +} +} // namespace + +c10::intrusive_ptr PackedLinearWeight:: + prepack( + const at::Tensor& weight, + const std::optional& bias, + const int64_t out_features_block_size, + const int64_t in_features_block_size) { + TORCH_CHECK( + weight.dim() == 2, + "The weight tensor for ao::sparse::qlinear_prepack (fbgemm) should" + " be 2-dimensional."); + + TORCH_CHECK( + out_features_block_size == 1 && in_features_block_size == 4, + "The out and in features block sizes for ao::sparse::qlinear_prepack", + " (fbgemm) should be 1 and 4 respectively (got ", out_features_block_size, + " and ", in_features_block_size, ")"); + + auto N = weight.size(0); + auto K = weight.size(1); + + auto weight_contig = weight.contiguous(); + const auto qtype = weight.qscheme(); + std::vector weight_zero_points_int32(1, 0); + if (qtype == c10::kPerTensorAffine) { + weight_zero_points_int32[0] = weight.q_zero_point(); + } else if (qtype == c10::kPerChannelAffine) { + weight_zero_points_int32.resize(N, 0); + for (const auto i : c10::irange(N)) { + weight_zero_points_int32[i] = + weight.q_per_channel_zero_points()[i].item(); + } + } + TORCH_CHECK( + std::all_of( + weight_zero_points_int32.cbegin(), + weight_zero_points_int32.cend(), + [](int32_t i) { return i == 0; }), + "zero point(s) should be 0 for the weight tensor of ao::sparse::qlinear op"); + std::vector weight_scales_float(1, 0.0); + if (qtype == c10::kPerTensorAffine) { + weight_scales_float[0] = weight.q_scale(); + } else if (qtype == c10::kPerChannelAffine) { + weight_scales_float.resize(N, 0.0); + for (const auto i : c10::irange(N)) { + weight_scales_float[i] = weight.q_per_channel_scales()[i].item(); + } + } + + const int8_t* weight_ptr_int8 = + reinterpret_cast(weight_contig.const_data_ptr()); + + std::vector col_offsets(N); + calc_col_offsets_transpose( + /*K=*/K, + /*N=*/N, + /*Bint8=*/weight_ptr_int8, + /*B_zero_point=*/weight_zero_points_int32.data(), + /*col_offsets=*/col_offsets.data(), + /*qtype=*/qtype); + + std::optional bias_contig; + if (bias.has_value()) { + const at::Tensor& bias_vec = bias.value(); + TORCH_CHECK(bias_vec.dim() == 1, "bias should be a vector (1D Tensor)"); + TORCH_CHECK( + bias_vec.size(0) == N, + "bias should have N elements: " + std::to_string(N)); + bias_contig = bias->contiguous(); + } + + auto bcsr = fbgemm::fbgemmDenseToBCSR(N, K, weight_ptr_int8); + auto ret_ptr = c10::make_intrusive( + std::move(bcsr), + bias_contig, + col_offsets, + weight_scales_float, + weight_zero_points_int32, + qtype, + out_features_block_size, + in_features_block_size); + return ret_ptr; +} + +#endif // USE_FBGEMM + +#ifdef USE_PYTORCH_QNNPACK +c10::intrusive_ptr PackedLinearWeightQnnp:: + prepack( + const at::Tensor& weight, + const std::optional& bias, + const int64_t out_features_block_size, + const int64_t in_features_block_size) { + at::native::initQNNPACK(); + return c10::make_intrusive( + weight, bias, out_features_block_size, in_features_block_size); +} + +PackedLinearWeightQnnp::PackedLinearWeightQnnp( + const at::Tensor& weight, + const std::optional& bias, + const int64_t out_features_block_size, + const int64_t in_features_block_size) + : LinearPackedParamsBase(out_features_block_size, in_features_block_size), + orig_bias_(bias), + q_scheme_(weight.qscheme()), + output_channels_(weight.size(0)), + input_channels_(weight.size(1)) { + TORCH_CHECK( + weight.dim() == 2, + "ao::sparse::qlinear (qnnpack): Weight tensor rank should be == 2"); + TORCH_CHECK(out_features_block_size > 0, "Row block size must be > 0."); + TORCH_CHECK(in_features_block_size > 0, "Row block size must be > 0."); + + if (bias.has_value()) { + bias_ = bias.value(); + } else { + bias_ = at::zeros(output_channels_, weight.options().dtype(at::kFloat)); + } + TORCH_CHECK( + (bias_.ndimension() == 1 && bias_.size(0) == output_channels_), + "ao::sparse::qlinear_prepack (qnnpack): Given weight of size ", + weight.sizes(), + ", expected bias to be 1-dimensional with ", + output_channels_, + " elements", + ", but got bias of size ", + bias_.sizes(), + " instead"); + + // Given bias is supposed to be 1 dim, it is already contiguous, + // but the weight might be non-contiguous. + at::Tensor weight_contig = weight.contiguous(); + + std::tie(w_zero_points_, w_scales_) = + make_zero_points_and_scales_tensor(weight_contig); + const float* weight_scales_data = w_scales_.const_data_ptr(); + at::Tensor qnnp_weight = at::_empty_affine_quantized( + weight_contig.sizes(), + at::device(c10::kCPU).dtype(c10::kQUInt8), + weight_scales_data[0], + w_zero_points_[0]); + auto* qnnp_w_data = qnnp_weight.data_ptr(); + auto wt_numel = weight_contig.numel(); + int8_t* w_data = + reinterpret_cast(weight_contig.data_ptr()); + for (const auto i : c10::irange(wt_numel)) { + qnnp_w_data[i] = static_cast(w_data[i] + 128); + } + bcsr_matrix_ = qnnpack::generateBlockCSRMatrix( + reinterpret_cast(qnnp_w_data), + output_channels_, + input_channels_, + out_features_block_size, + in_features_block_size, + w_zero_points_.data()); +} +#endif // USE_PYTORCH_QNNPACK + +namespace { + +class QLinearPackWeightInt8 final { + public: + static c10::intrusive_ptr run( + const at::Tensor& weight, + const std::optional& bias, + const int64_t out_features_block_size, + const int64_t in_features_block_size) { + auto& ctx = at::globalContext(); + +#ifdef USE_FBGEMM + if (ctx.qEngine() == at::QEngine::FBGEMM) { + return PackedLinearWeight::prepack( + weight, bias, out_features_block_size, in_features_block_size); + } +#endif +#ifdef USE_PYTORCH_QNNPACK + if (ctx.qEngine() == at::QEngine::QNNPACK) { + return PackedLinearWeightQnnp::prepack( + weight, bias, out_features_block_size, in_features_block_size); + } +#endif + TORCH_CHECK( + false, + "Didn't find engine for operation ao::sparse::qlinear_prepack ", + toString(ctx.qEngine())); + } +}; + +TORCH_LIBRARY_IMPL(sparse, QuantizedCPU, m) { + register_linear_params(); + m.impl( + TORCH_SELECTIVE_NAME("sparse::qlinear_prepack"), + TORCH_FN(QLinearPackWeightInt8::run)); +} +} // namespace +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_serialize.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_serialize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eeab500cc1db9dc1c69dc90abb22c38e02440221 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_serialize.cpp @@ -0,0 +1,247 @@ +#include + +#ifdef USE_FBGEMM +#include +#endif +#ifdef USE_PYTORCH_QNNPACK +#include + +#include +#endif + +namespace ao::sparse { + +namespace { +/** + - Wrap a vector in a Tensor, copying data into its own data pointer. + - The type of vec is T& (not vector&) so this works with any vector-like + datastructure which has .data() and .size() + */ +template +at::Tensor wrap_vector(T& vec, c10::ScalarType dtype) { + at::Tensor t = at::empty( + {static_cast(vec.size())}, at::device(c10::kCPU).dtype(dtype)); + std::copy( + vec.data(), vec.data() + vec.size(), t.mutable_data_ptr()); + return t; +} + +#ifdef USE_FBGEMM +/** + * Adapted from Fbgemm BCSRMatrix::pack, but with zero points, without tiling, + * and without determining row_offsets + * https://github.com/pytorch/FBGEMM/blob/9d7c48a65419d0350f9e9e72f31e05bfe37e85a4/src/FbgemmSparseDense.cc#L84 + */ +ao::sparse::BCSR pack_bcsr( + const int8_t* src, + const int64_t R, + const int64_t C, + const int64_t RB, + const int64_t CB, + const int8_t* zero_points, + const bool qscheme_per_tensor) { + const size_t ld = C; + std::vector rowBPtr; + std::vector colBIdx; + std::vector values; + rowBPtr.push_back(0); + int64_t nnzb = 0; + int64_t rowBlocks = (R + RB - 1) / RB; + for (int64_t i = 0; i < rowBlocks; ++i) { + int64_t curCols = C; + int64_t curColBlocks = (curCols + CB - 1) / CB; + for (int64_t j = 0; j < curColBlocks; ++j) { + // is the whole block zero? + bool isCurrentBlockNonZero = false; + for (int64_t ib = 0; ib < RB; ++ib) { + // break if already found a non-zero element or + // out of bounds + if (isCurrentBlockNonZero || (i * RB + ib) >= R) { + break; + } + const int64_t curr_row = i * RB + ib; + const int8_t curr_row_zero_point = + qscheme_per_tensor ? zero_points[0] : zero_points[curr_row]; + for (int64_t jb = 0; jb < CB; ++jb) { + // within bound? + if ((j * CB + jb) >= C) { + continue; + } else { + if (src[curr_row * ld + j * CB + jb] != curr_row_zero_point) { + isCurrentBlockNonZero = true; + break; + } + } + } + } + if (isCurrentBlockNonZero) { + for (int64_t ib = 0; ib < RB; ++ib) { + for (int64_t jb = 0; jb < CB; ++jb) { + if ((i * RB + ib) >= R || (j * CB + jb) >= C) { + // zero fill + values.push_back(0); + } else { + int8_t val = src[(i * RB + ib) * ld + j * CB + jb]; + values.push_back(val); + } + } + } + colBIdx.push_back(static_cast(j)); + nnzb++; + } + } + rowBPtr.push_back(static_cast(nnzb)); + } + return ao::sparse::BCSR( + std::move(values), std::move(rowBPtr), std::move(colBIdx)); +} +#endif // USE_FBGEMM +} // namespace + +#ifdef USE_FBGEMM + +BCSRSerializationType PackedLinearWeight::serialize() { + // Get weights, row indices, and col indices in untiled form; + // unpack the tiled bcsr then pack it in untiled form + std::vector dense_weight_values = std::vector(w->R * w->C); + w->unpack(dense_weight_values.data()); + + const bool qscheme_per_tensor = (q_scheme == c10::kPerTensorAffine); + at::Tensor zero_points = wrap_vector(w_zp, c10::kChar); + + ao::sparse::BCSR untiled_bcsr = pack_bcsr( + dense_weight_values.data(), + w->R, + w->C, + w->RB, + w->CB, + zero_points.const_data_ptr(), + qscheme_per_tensor); + + std::vector& packed_weight_values = std::get<0>(untiled_bcsr); + // Add 128 to each weight value. This serialization format is best for + // minimizing memory footprint for QNNPack + + at::Tensor weight_values = at::empty( + {static_cast(packed_weight_values.size())}, + at::device(c10::kCPU).dtype(c10::kByte)); + std::transform( + packed_weight_values.begin(), + packed_weight_values.end(), + weight_values.mutable_data_ptr(), + [](int8_t v) { + return static_cast(static_cast(v) + 128); + }); + + return BCSRSerializationType( + SPARSE_LINEAR_PACKED_PARAM_SERIALIZATION_VERSION, + bias_, + out_features_block_size_, + in_features_block_size_, + wrap_vector(w_scale, c10::kFloat), + // Narrowing from int32_t to int8_t; this is okay because qint8 zero + // points are restricted to fit in bounds of int_8 + std::move(zero_points), + qscheme_per_tensor, + wrap_vector( + std::get<1>(untiled_bcsr), c10::kInt), // Row block indices + wrap_vector( + std::get<2>(untiled_bcsr), c10::kInt), // Col block indices + std::move(weight_values), + w->R, + w->C); +} + +#endif // USE_FBGEMM + +#ifdef USE_PYTORCH_QNNPACK + +BCSRSerializationType PackedLinearWeightQnnp::serialize() { + at::Tensor w_scales_compact; + at::Tensor w_zero_points_compact; + const float* w_scales_data_ptr = w_scales_.const_data_ptr(); + std::function subtract_128 = [](uint8_t v) { + return static_cast(static_cast(v) - 128); + }; + + if (q_scheme_ == at::kPerTensorAffine) { + w_scales_compact = at::empty({1}, at::device(c10::kCPU).dtype(c10::kFloat)); + w_zero_points_compact = + at::empty({1}, at::device(c10::kCPU).dtype(c10::kChar)); + + w_scales_compact.mutable_data_ptr()[0] = w_scales_data_ptr[0]; + w_zero_points_compact.mutable_data_ptr()[0] = + static_cast(static_cast(w_zero_points_[0]) - 128); + } else if (q_scheme_ == at::kPerChannelAffine) { + w_scales_compact = + at::empty({output_channels_}, at::device(c10::kCPU).dtype(c10::kFloat)); + w_zero_points_compact = + at::empty({output_channels_}, at::device(c10::kCPU).dtype(c10::kChar)); + + std::copy( + w_scales_data_ptr, + w_scales_data_ptr + + output_channels_, // Don't go to the end because of padding + w_scales_compact.mutable_data_ptr()); + + // Subtract 128 from each zero point, to reverse addition done during + // prepacking + std::transform( + w_zero_points_.begin(), + w_zero_points_.begin() + + output_channels_, // Don't go to the end because of padding + w_zero_points_compact.mutable_data_ptr(), + std::move(subtract_128)); + } else { + TORCH_CHECK(false, "Unsupported quantization scheme."); + } + + at::Tensor wrapped_row_values; + at::Tensor wrapped_col_indices; + + const uint32_t max_index = bcsr_matrix_->max_index(); + + if (max_index <= std::numeric_limits::max()) { + // Cast from uint8_t range to int8_t + wrapped_row_values = QNNPACK_BCSRMATRIX_DISPATCH_INDICES_DTYPE( + bcsr_matrix_, + { return wrap_vector(typed_bcsr->row_values, c10::kChar); }); + wrapped_col_indices = QNNPACK_BCSRMATRIX_DISPATCH_INDICES_DTYPE( + bcsr_matrix_, + { return wrap_vector(typed_bcsr->col_indices, c10::kChar); }); + } else if (max_index <= std::numeric_limits::max()) { + // Cast from uint16_t range to int16_t + wrapped_row_values = QNNPACK_BCSRMATRIX_DISPATCH_INDICES_DTYPE( + bcsr_matrix_, + { return wrap_vector(typed_bcsr->row_values, c10::kShort); }); + wrapped_col_indices = QNNPACK_BCSRMATRIX_DISPATCH_INDICES_DTYPE( + bcsr_matrix_, + { return wrap_vector(typed_bcsr->col_indices, c10::kShort); }); + } else { + // Cast from uint32_t range to int32_t + wrapped_row_values = QNNPACK_BCSRMATRIX_DISPATCH_INDICES_DTYPE( + bcsr_matrix_, + { return wrap_vector(typed_bcsr->row_values, c10::kInt); }); + wrapped_col_indices = QNNPACK_BCSRMATRIX_DISPATCH_INDICES_DTYPE( + bcsr_matrix_, + { return wrap_vector(typed_bcsr->col_indices, c10::kInt); }); + } + + return BCSRSerializationType( + SPARSE_LINEAR_PACKED_PARAM_SERIALIZATION_VERSION, + orig_bias_, + out_features_block_size_, + in_features_block_size_, + std::move(w_scales_compact), + std::move(w_zero_points_compact), + (q_scheme_ == c10::kPerTensorAffine), + std::move(wrapped_row_values), + std::move(wrapped_col_indices), + wrap_vector(bcsr_matrix_->values, c10::kByte), + output_channels_, + input_channels_); +} + +#endif // USE_PYTORCH_QNNPACK + +} // namespace ao diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_unpack.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_unpack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9331de719529ec265d9d5424afc7df3e5b923192 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qlinear_unpack.cpp @@ -0,0 +1,141 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#include +#endif + +namespace ao::sparse { + + +#ifdef USE_FBGEMM + +LinearPackedSerializationType PackedLinearWeight::unpack() { + auto packW = w.get(); + + const int64_t N = static_cast(packW->R); + const int64_t K = static_cast(packW->C); + + at::Tensor weight_origin; + if (q_scheme == c10::kPerTensorAffine) { + weight_origin = at::_empty_affine_quantized( + {N, K}, at::device(c10::kCPU).dtype(c10::kQInt8), w_scale[0], w_zp[0]); + } else if (q_scheme == c10::kPerChannelAffine) { + at::Tensor scales = at::empty( + {static_cast(w_scale.size())}, + at::device(c10::kCPU).dtype(c10::kFloat)); + std::copy(w_scale.begin(), w_scale.end(), scales.mutable_data_ptr()); + + at::Tensor zero_points = at::empty( + {static_cast(w_zp.size())}, + at::device(c10::kCPU).dtype(c10::kInt)); + std::copy(w_zp.begin(), w_zp.end(), zero_points.mutable_data_ptr()); + + weight_origin = at::_empty_per_channel_affine_quantized( + {N, K}, + scales, + zero_points, + 0, // The output channel axis is 0 + at::device(c10::kCPU).dtype(c10::kQInt8)); + } + + int8_t* weight_ptr_int8 = + reinterpret_cast(weight_origin.data_ptr()); + + packW->unpack(weight_ptr_int8); + + const std::vector block_pattern( + {out_features_block_size_, in_features_block_size_}); + + return std::make_tuple(std::move(weight_origin), bias_, block_pattern); +} + +#endif // USE_FBGEMM + +#ifdef USE_PYTORCH_QNNPACK + +LinearPackedSerializationType PackedLinearWeightQnnp::unpack() { + const int64_t N = output_channels_; + const int64_t K = input_channels_; + + float* w_scales_ptr = w_scales_.data_ptr(); + + at::Tensor weight_origin; + if (q_scheme_ == c10::kPerTensorAffine) { + weight_origin = at::_empty_affine_quantized( + {N, K}, + at::device(c10::kCPU).dtype(c10::kQInt8), + w_scales_ptr[0], + w_zero_points_[0] - 128); + } else if (q_scheme_ == c10::kPerChannelAffine) { + at::Tensor scales = at::empty( + {static_cast(output_channels_)}, + at::device(c10::kCPU).dtype(c10::kFloat)); + std::copy( + w_scales_ptr, + w_scales_ptr + output_channels_, + scales.mutable_data_ptr()); + + at::Tensor zero_points = at::empty( + {static_cast(output_channels_)}, + at::device(c10::kCPU).dtype(c10::kInt)); + std::transform( + w_zero_points_.begin(), + w_zero_points_.begin() + output_channels_, + zero_points.mutable_data_ptr(), + [](uint8_t v) { return static_cast(v) - 128; }); + + weight_origin = at::_empty_per_channel_affine_quantized( + {N, K}, + scales, + zero_points, + 0, // The output channel axis is 0 + at::device(c10::kCPU).dtype(c10::kQInt8)); + } + + int8_t* weight_ptr_int8 = + reinterpret_cast(weight_origin.data_ptr()); + + bcsr_matrix_->unpack( + weight_ptr_int8, + output_channels_, + input_channels_, + w_zero_points_.data()); + + std::vector block_pattern( + {out_features_block_size_, in_features_block_size_}); + + return std::make_tuple( + std::move(weight_origin), bias_, std::move(block_pattern)); +} + +#endif // USE_FBGEMM + +namespace { + +class QLinearUnpackWeightInt8 final { + public: + static LinearPackedSerializationType run( + const c10::intrusive_ptr& packed_weight) { + return packed_weight->unpack(); + } +}; + +TORCH_LIBRARY_IMPL(sparse, CatchAll, m) { + register_linear_params(); + m.impl( + TORCH_SELECTIVE_NAME("sparse::qlinear_unpack"), + TORCH_FN(QLinearUnpackWeightInt8::run)); +} +} // namespace +} // namespace ao::sparse diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qnnpack_utils.h b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qnnpack_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..563a2b26fb9593cd78e0fb7f7e15cc5c2b86a7e0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/ao_sparse/quantized/cpu/qnnpack_utils.h @@ -0,0 +1,90 @@ +#pragma once + +#include +#include + +#ifdef USE_PYTORCH_QNNPACK +// TODO: Refacto QnnpackUtils.h so as to separate code +// needed for quantized op from the generic qnnpack specific +// quantization utilities. +#include +#include +#include + +namespace ao::sparse { + +struct TORCH_API PackedLinearWeightQnnp : public LinearPackedParamsBase { + PackedLinearWeightQnnp(const at::Tensor& weight, const std::optional& bias, const int64_t out_features_block_size /* block sparsity size across output_features */, const int64_t in_features_block_size /* block sparsity size across input_features */); + explicit PackedLinearWeightQnnp(const BCSRSerializationType& serialized); + std::optional orig_bias_; + // Separate copy of bias exist so that we can fill in zeros when + // optional bias does not exist. This is to compy with qnnpack operator that + // expects bias to be present. + // In case bias is present bias_ is just a reference to orig_bias_ + at::Tensor bias_; + c10::QScheme q_scheme_; + double input_scale_{}; + std::unique_ptr bcsr_matrix_; + at::Tensor w_scales_; + std::vector w_zero_points_; + std::vector requantization_scales_; + std::unique_ptr + sparse_linear_op_{nullptr}; + int64_t output_channels_; + int64_t input_channels_; + // Deserialized Tensors are stored to maintain the lifetime of underlying + // BCSR data. + // These are left empty if PackedLinearWeightQnnp is created via prepacking + // rather than deserializing. + at::Tensor deserialized_bcsr_row_block_indices_; + at::Tensor deserialized_bcsr_col_block_indices_; + at::Tensor deserialized_bcsr_weight_values_; + + at::Tensor apply( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override { + TORCH_CHECK( + false, "Static quantized sparse linear unimplemented on QNNPACK"); + } + at::Tensor apply_relu( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point) override { + TORCH_CHECK( + false, "Static quantized sparse linear unimplemented on QNNPACK"); + } + + at::Tensor apply_dynamic(const at::Tensor& input) override; + at::Tensor apply_dynamic_relu(const at::Tensor& input) override; + + LinearPackedSerializationType unpack() override; + + BCSRSerializationType serialize() override; + + static c10::intrusive_ptr deserialize( + const BCSRSerializationType& serialized); + + std::optional bias() override { + return orig_bias_; + } + + static c10::intrusive_ptr prepack( + const at::Tensor& weight, + const std::optional& bias, + const int64_t out_features_block_size, + const int64_t in_features_block_size); + + private: + template + at::Tensor apply_impl( + const at::Tensor& input, + double output_scale, + int64_t output_zero_point); + template + at::Tensor apply_dynamic_impl(const at::Tensor& input); +}; + +} // namespace ao::sparse + +#endif // USE_PYTORCH_QNNPACK diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/batch_norm.h b/western_ai/usa/pytorch/aten/src/ATen/native/batch_norm.h new file mode 100644 index 0000000000000000000000000000000000000000..6ae48a0089cf6e5a65e55f0bb0dcb07fdf202419 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/batch_norm.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +namespace at::native { + +using batch_norm_fn = void (*)(Tensor&, const Tensor&, const Tensor&, + const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, bool, double); +using batch_norm_collect_stats_fn = void (*)(Tensor&, Tensor&, const Tensor&); +using batch_norm_backward_fn = void(*)(Tensor&, Tensor&, Tensor&, const Tensor&, + const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, bool, double); + +DECLARE_DISPATCH(batch_norm_fn, batch_norm_cpu_stub) +DECLARE_DISPATCH(batch_norm_collect_stats_fn, batch_norm_cpu_collect_stats_stub) +DECLARE_DISPATCH(batch_norm_backward_fn, batch_norm_cpu_backward_stub) + +// TensorAccessor when it is defined to work around undefined... +template +static TensorAccessor conditional_accessor_1d(const Tensor& t) { + if (! t.defined()) { + return TensorAccessor(nullptr, nullptr, nullptr); + } + return t.accessor(); +} + +template +static scalar_t* conditional_data_ptr(const Tensor& t) { + if constexpr (std::is_const_v) { + return t.defined() ? t.contiguous().const_data_ptr() + : nullptr; + } else { + return t.defined() ? t.contiguous().data_ptr() + : nullptr; + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Activation.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Activation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81763f5a43153623114ae225df9fcd311bfd710b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Activation.cpp @@ -0,0 +1,1344 @@ +#define TORCH_ASSERT_NO_OPERATORS +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES +#endif + +#include + + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native { + +namespace { + +#if defined(__GNUC__) && __GNUC__ == 14 && defined(__aarch64__) && !defined(__ARM_FEATURE_SVE) +// Workaround for gcc-14.2.0 ICE during RTL pass: expand when compiling for NEON +__attribute__((optimize("no-tree-vectorize"))) +#endif +void log_sigmoid_cpu_kernel(TensorBase &output, TensorBase &buffer, const TensorBase &input) { + if (at::isReducedFloatingType(input.scalar_type())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(input.scalar_type(), "log_sigmoid_cpu", [&]() { + using Vec = Vectorized; + scalar_t* output_data = output.data_ptr(); + scalar_t* buffer_data = buffer.data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + parallel_for(0, input.numel(), 1, [&] (int64_t begin, int64_t end) { + int64_t size = end - begin; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec data_vec = Vec::loadu(input_data + begin+ d); + auto [data_vec0, data_vec1] = convert_to_float(data_vec); + Vectorized min_vec = minimum(data_vec0, Vectorized(float(0))); + Vectorized buffer_vec0 = data_vec0.abs().neg().exp(); + Vectorized output_vec0 = min_vec - buffer_vec0.log1p(); + min_vec = minimum(data_vec1, Vectorized(float(0))); + Vectorized buffer_vec1 = data_vec1.abs().neg().exp(); + Vectorized output_vec1 = min_vec - buffer_vec1.log1p(); + convert_from_float(buffer_vec0, buffer_vec1).store(buffer_data + begin + d); + convert_from_float(output_vec0, output_vec1).store(output_data + begin + d); + } + if (size - d > 0) { + Vec data_vec = Vec::loadu(input_data + begin + d, size - d); + auto [data_vec0, data_vec1] = convert_to_float(data_vec); + Vectorized min_vec = minimum(data_vec0, Vectorized(float(0))); + Vectorized buffer_vec0 = data_vec0.abs().neg().exp(); + Vectorized output_vec0 = min_vec - buffer_vec0.log1p(); + min_vec = minimum(data_vec1, Vectorized(float(0))); + Vectorized buffer_vec1 = data_vec1.abs().neg().exp(); + Vectorized output_vec1 = min_vec - buffer_vec1.log1p(); + convert_from_float(buffer_vec0, buffer_vec1).store(buffer_data + begin + d, size - d); + convert_from_float(output_vec0, output_vec1).store(output_data + begin + d, size - d); + } + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "log_sigmoid_cpu", [&] { + using Vec = Vectorized; + scalar_t* output_data = output.data_ptr(); + scalar_t* buffer_data = buffer.data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + parallel_for(0, input.numel(), 1, [&] (int64_t begin, int64_t end) { + int64_t size = end - begin; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec data_vec = Vec::loadu(input_data + begin+ d); + Vec min_vec = vec::minimum(data_vec, Vec(scalar_t(0))); + Vec buffer_vec = data_vec.abs().neg().exp(); + Vec output_vec = min_vec - buffer_vec.log1p(); + buffer_vec.store(buffer_data + begin + d); + output_vec.store(output_data + begin + d); + } + if (size - d > 0) { + Vec data_vec = Vec::loadu(input_data + begin + d, size - d); + Vec min_vec = vec::minimum(data_vec, Vec(scalar_t(0))); + Vec buffer_vec = data_vec.abs().neg().exp(); + Vec output_vec = min_vec - buffer_vec.log1p(); + buffer_vec.store(buffer_data + begin + d, size - d); + output_vec.store(output_data + begin + d, size - d); + } + }); + }); + } +} + +void log_sigmoid_backward_cpu_kernel(TensorIterator& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "log_sigmoid_backward_cpu", [&]() { + using Vec = Vectorized; + auto zero_val = float(0); + auto zero_vec = Vectorized(zero_val); + auto one_val = float(1); + auto one_vec = Vectorized(one_val); + cpu_kernel_vec(iter, + [=](scalar_t a, scalar_t b, scalar_t c) -> scalar_t { + auto in_negative = float(a) < float(0); + auto max_deriv = in_negative ? float(1) : float(0); + auto sign = in_negative ? float(1) : -float(1); + return (max_deriv - sign * (float(b) / (float(1) + b))) * float(c); + }, + [=](Vec a, Vec b, Vec c) -> Vec { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + auto [c0, c1] = convert_to_float(c); + auto mask = a0 < zero_vec; + auto max_deriv_vec = Vectorized::blendv(zero_vec, one_vec, mask); + auto sign_vec = Vectorized::blendv(one_vec.neg(), one_vec, mask); + a0 = (max_deriv_vec - sign_vec * (b0 / (one_vec + b0))) * c0; + mask = a1 < zero_vec; + max_deriv_vec = Vectorized::blendv(zero_vec, one_vec, mask); + sign_vec = Vectorized::blendv(one_vec.neg(), one_vec, mask); + a1 = (max_deriv_vec - sign_vec * (b1 / (one_vec + b1))) * c1; + return convert_from_float(a0, a1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "log_sigmoid_backward_cpu", [&]() { + using Vec = Vectorized; + auto zero_val = scalar_t(0); + auto zero_vec = Vec(zero_val); + auto one_val = scalar_t(1); + auto one_vec = Vec(one_val); + cpu_kernel_vec(iter, + [=](scalar_t a, scalar_t b, scalar_t c) -> scalar_t { + auto in_negative = a < scalar_t(0); + auto max_deriv = in_negative ? scalar_t(1) : scalar_t(0); + auto sign = in_negative ? scalar_t(1) : -scalar_t(1); + return (max_deriv - sign * (b / (scalar_t(1) + b))) * c; + }, + [=](Vec a, Vec b, Vec c) -> Vec { + auto mask = a < zero_vec; + auto max_deriv_vec = Vec::blendv(zero_vec, one_vec, mask); + auto sign_vec = Vec::blendv(one_vec.neg(), one_vec, mask); + return (max_deriv_vec - sign_vec * (b / (one_vec + b))) * c; + }); + }); + } +} + +void threshold_kernel( + TensorIteratorBase& iter, + const Scalar& threshold_scalar, + const Scalar& value_scalar) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "threshold_cpu", [&]() { + using Vec = Vectorized; + float threshold = threshold_scalar.to(); + Vec threshold_v = Vec(threshold); + scalar_t value = value_scalar.to(); + Vec value_v = Vec(float(value)); + cpu_kernel_vec( + iter, + [&](scalar_t x, scalar_t other) -> scalar_t { + return float(x) <= threshold ? value : other; + }, + [&](Vectorized x, Vectorized other) -> Vectorized { + auto [x0, x1] = convert_to_float(x); + auto [other0, other1] = convert_to_float(other); + return convert_from_float(Vec::blendv(other0, value_v, x0 <= threshold_v), + Vec::blendv(other1, value_v, x1 <= threshold_v)); + }); + }); + } else { + AT_DISPATCH_ALL_TYPES(iter.dtype(), "threshold_cpu", [&] { + using Vec = Vectorized; + scalar_t threshold = threshold_scalar.to(); + Vec threshold_v = Vec(threshold); + scalar_t value = value_scalar.to(); + Vec value_v = Vec(value); + cpu_kernel_vec( + iter, + [&](scalar_t x, scalar_t other) -> scalar_t { + return x <= threshold ? value : other; + }, + [&](Vec x, Vec other) -> Vec { + return Vec::blendv(other, value_v, x <= threshold_v); + }); + }); + } +} + +void elu_kernel(TensorIteratorBase& it, const Scalar& alpha, const Scalar& scale, const Scalar& input_scale) { + if (at::isReducedFloatingType(it.common_dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(it.common_dtype(), "elu_cpu", [&]() { + cpu_kernel_vec( + it, + get_scalar_elu_elementwise_func(alpha.to(), scale.to(), input_scale.to()), + get_vectorized_elu_elementwise_func(alpha.to(), scale.to(), input_scale.to())); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(it.common_dtype(), "elu_cpu", [&]() { + cpu_kernel_vec( + it, + get_scalar_elu_elementwise_func(alpha.to(), scale.to(), input_scale.to()), + get_vectorized_elu_elementwise_func(alpha.to(), scale.to(), input_scale.to())); + }); + } +} + +void elu_backward_kernel(TensorIteratorBase& it, const Scalar& alpha, const Scalar& scale, const Scalar& input_scale, bool is_result) { + if (at::isReducedFloatingType(it.common_dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(it.common_dtype(), "elu_backward_cpu", [&]() { + auto negcoef = alpha.to() * scale.to(); + auto poscoef = scale.to(); + auto negiptcoef = input_scale.to(); + const Vectorized negcoef_vec(negcoef); + const Vectorized negiptcoef_vec(negiptcoef); + const Vectorized poscoef_vec(poscoef); + const Vectorized zero_vec(static_cast(0)); + cpu_kernel_vec( + it, + [negcoef, negiptcoef, poscoef, is_result](scalar_t a, scalar_t b) -> scalar_t { + if (is_result) { + return float(b) <= float(0) ? float(a) * negiptcoef * (float(b) + negcoef) : float(a) * poscoef; + } else { + return float(b) <= float(0) ? float(a) * negiptcoef * negcoef * std::exp(float(b) * negiptcoef): float(a) * poscoef; + } + }, + [&negcoef_vec, &negiptcoef_vec, &poscoef_vec, &zero_vec, is_result](Vectorized a, Vectorized b) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + auto cmp0 = (b0 > zero_vec); + auto cmp1 = (b1 > zero_vec); + auto get_res_masked = [&](Vectorized& cmp, Vectorized& a, Vectorized& b) { + if (is_result) { + return !cmp.zero_mask() ? a * poscoef_vec : + Vectorized::blendv(a * negiptcoef_vec * (b + negcoef_vec), a * poscoef_vec, cmp); + } else { + return Vectorized::blendv(a * negiptcoef_vec * negcoef_vec * (b * negiptcoef_vec).exp(), a * poscoef_vec, cmp); + } + }; + auto res0 = get_res_masked(cmp0, a0, b0); + auto res1 = get_res_masked(cmp1, a1, b1); + return convert_from_float(res0, res1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(it.dtype(), "elu_backward_cpu", [&]() { + using Vec = Vectorized; + auto negcoef = alpha.to() * scale.to(); + auto poscoef = scale.to(); + auto negiptcoef = input_scale.to(); + const Vec negcoef_vec(negcoef); + const Vec negiptcoef_vec(negiptcoef); + const Vec poscoef_vec(poscoef); + const Vec zero_vec(static_cast(0)); + cpu_kernel_vec( + it, + [negcoef, negiptcoef, poscoef, is_result](scalar_t a, scalar_t b) -> scalar_t { + if (is_result) { + return b <= scalar_t(0) ? a * negiptcoef * (b + negcoef) : a * poscoef; + } else { + return b <= scalar_t(0) ? a * negiptcoef * negcoef * std::exp(b * negiptcoef): a * poscoef; + } + }, + [&negcoef_vec, &negiptcoef_vec, &poscoef_vec, &zero_vec, is_result](Vec a, Vec b) -> Vec { + auto cmp = (b > zero_vec); + if (is_result) { + if (!cmp.zero_mask()) { // only a * poscoef (which is very quick) needs to be computed + return a * poscoef_vec; + } else { + return Vec::blendv(a * negiptcoef_vec * (b + negcoef_vec), a * poscoef_vec, cmp); + } + } else { + return Vec::blendv(a * negiptcoef_vec * negcoef_vec * (b * negiptcoef_vec).exp(), a * poscoef_vec, cmp); + } + } + ); + }); + } +} + +// TODO(yangxm): Add another fast kernel using formula +// y = 0.5x * (1 + tanh(sqrt(2/Pi) * (x + 0.044715x^3))) +// and the fast tanh impl from Eigen. +void GeluKernelImpl(TensorIteratorBase& it, GeluType approximate) { + auto grain_size = at::internal::GRAIN_SIZE; + // Numbers based on benchmarking. + // Benchmark: benchmarks/operator_benchmarks/pt/gelu_test.py +#ifdef C10_MOBILE + // Benchmarked on S8 US phone. + // Internal benchmarking that converts operator benchmark into + // a torchscript module and run that on mobile. + // Same benchmark as server side. + constexpr int64_t GELU_MIN_ELEMENTS_FOR_MULTI_THREADING{6144}; +#else + // Benchmarked on i9 8 core 16 thread machine. + // 1 thread: cd benchmark/operator_benchmarks; + // python -m pt.gelu_test --tag_filter long --omp_num_threads 1 + // 2 threads: cd benchmark/operator_benchmarks; + // python -m pt.gelu_test --tag_filter long --omp_num_threads 1 + constexpr int64_t GELU_MIN_ELEMENTS_FOR_MULTI_THREADING{16384}; +#endif + if (it.numel() > GELU_MIN_ELEMENTS_FOR_MULTI_THREADING) { + grain_size = it.numel() / at::get_num_threads(); + } + if (approximate == GeluType::Tanh) { + if (at::isReducedFloatingType(it.common_dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(it.common_dtype(), "GeluKernelImpl", [&]() { + cpu_kernel_vec( + it, + scalar_gelu_approximated_with_tanh, + vectorized_gelu_approximated_with_tanh, + grain_size); + }); + } else { + AT_DISPATCH_FLOATING_TYPES( + it.dtype(), "GeluKernelImpl", [&]() { + cpu_kernel_vec( + it, + scalar_gelu_approximated_with_tanh, + vectorized_gelu_approximated_with_tanh, + grain_size); + }); + } + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::Half, + ScalarType::BFloat16, + it.dtype(), + "GeluKernelImpl", + [&]() { + cpu_kernel_vec( + it, + scalar_gelu, + vectorized_gelu, + grain_size); + }); + } +} + +void GeluBackwardKernelImpl(TensorIteratorBase& it, GeluType approximate) { + if (approximate == GeluType::Tanh) { + if (at::isReducedFloatingType(it.common_dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(it.common_dtype(), "GeluBackwardKernelImpl", [&]() { + auto kBetaVec = Vectorized((float)(M_SQRT2 * M_2_SQRTPI * 0.5)); + auto kKappaVec = Vectorized((float)(0.044715)); + auto kOneVec = Vectorized((float)(1)); + auto kThreeVec = Vectorized((float)(3)); + auto kPointFiveVec = Vectorized((float)(0.5)); + cpu_kernel_vec( + it, + [](scalar_t dy, scalar_t x) -> scalar_t { + const float kBeta = float(M_SQRT2 * M_2_SQRTPI * 0.5); + const float kKappa = float(0.044715); + float x_sq = float(x) * float(x); + float x_cube = x_sq * float(x); + float inner = kBeta * (float(x) + kKappa * x_cube); + float tanh_inner = float(std::tanh(inner)); + + float left = float(0.5) * float(x); + float right = float(1) + tanh_inner; + + float left_derivative = float(0.5) * right; + + float tanh_derivative = float(1) - tanh_inner * tanh_inner; + float inner_derivative = + kBeta * (float(1) + float(3) * kKappa * x_sq); + float right_derivative = left * tanh_derivative * inner_derivative; + + return float(dy) * (left_derivative + right_derivative); + }, + [&](Vectorized dy_vec, Vectorized x_vec) -> Vectorized { + auto [x0_vec, x1_vec] = convert_to_float(x_vec); + auto [dy0_vec, dy1_vec] = convert_to_float(dy_vec); + auto x0_sq = x0_vec * x0_vec; + auto x1_sq = x1_vec * x1_vec; + auto x0_cube = x0_vec * x0_vec * x0_vec; + auto x1_cube = x1_vec * x1_vec * x1_vec; + auto inner_vec0 = kBetaVec * (x0_vec + kKappaVec * x0_cube); + auto inner_vec1 = kBetaVec * (x1_vec + kKappaVec * x1_cube); + auto tanh_inner_vec0 = inner_vec0.tanh(); + auto tanh_inner_vec1 = inner_vec1.tanh(); + + auto left_vec0 = kPointFiveVec * x0_vec; + auto left_vec1 = kPointFiveVec * x1_vec; + auto right_vec0 = kOneVec + tanh_inner_vec0; + auto right_vec1 = kOneVec + tanh_inner_vec1; + + auto left_derivative_vec0 = kPointFiveVec * right_vec0; + auto left_derivative_vec1 = kPointFiveVec * right_vec1; + + auto tanh_derivative_vec0 = kOneVec - tanh_inner_vec0 * tanh_inner_vec0; + auto tanh_derivative_vec1 = kOneVec - tanh_inner_vec1 * tanh_inner_vec1; + auto inner_derivative_vec0 = kBetaVec * (kOneVec + kThreeVec * kKappaVec * x0_sq); + auto inner_derivative_vec1 = kBetaVec * (kOneVec + kThreeVec * kKappaVec * x1_sq); + auto right_derivative_vec0 = left_vec0 * tanh_derivative_vec0 * inner_derivative_vec0; + auto right_derivative_vec1 = left_vec1 * tanh_derivative_vec1 * inner_derivative_vec1; + + auto res0 = dy0_vec * (left_derivative_vec0 + right_derivative_vec0); + auto res1 = dy1_vec * (left_derivative_vec1 + right_derivative_vec1); + return convert_from_float(res0, res1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES( + it.dtype(), "GeluBackwardKernelImpl", [&]() { + using Vec = vec::Vectorized; + const Vec kBetaVec(scalar_t(M_SQRT2 * M_2_SQRTPI * 0.5)); + const Vec kKappaVec(scalar_t(0.044715)); + const Vec kOneVec(scalar_t(1)); + const Vec kThreeVec(scalar_t(3)); + const Vec kPointFiveVec(scalar_t(0.5)); + cpu_kernel_vec( + it, + [](scalar_t dy, scalar_t x) { + const scalar_t kBeta = M_SQRT2 * M_2_SQRTPI * 0.5; + const scalar_t kKappa = 0.044715; + auto x_sq = x * x; + auto x_cube = x_sq * x; + auto inner = kBeta * (x + kKappa * x_cube); + auto tanh_inner = std::tanh(inner); + + auto left = scalar_t(0.5) * x; + auto right = scalar_t(1) + tanh_inner; + + auto left_derivative = scalar_t(0.5) * right; + + auto tanh_derivative = scalar_t(1) - tanh_inner * tanh_inner; + auto inner_derivative = + kBeta * (scalar_t(1) + scalar_t(3) * kKappa * x_sq); + auto right_derivative = left * tanh_derivative * inner_derivative; + + return dy * (left_derivative + right_derivative); + }, + [&](Vec dy_vec, Vec x_vec) { + auto x_sq = x_vec * x_vec; + auto x_cube = x_vec * x_vec * x_vec; + auto inner_vec = + kBetaVec * (x_vec + kKappaVec * x_cube); + auto tanh_inner_vec = inner_vec.tanh(); + + auto left_vec = kPointFiveVec * x_vec; + auto right_vec = kOneVec + tanh_inner_vec; + + auto left_derivative_vec = kPointFiveVec * right_vec; + + auto tanh_derivative_vec = + kOneVec - tanh_inner_vec * tanh_inner_vec; + auto inner_derivative_vec = + kBetaVec * (kOneVec + kThreeVec * kKappaVec * x_sq); + auto right_derivative_vec = + left_vec * tanh_derivative_vec * inner_derivative_vec; + + return dy_vec * (left_derivative_vec + right_derivative_vec); + }); + }); + } + } else { + if (at::isReducedFloatingType(it.common_dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(it.common_dtype(), "GeluBackwardKernelImpl", [&]() { + auto kAlphaVec = Vectorized((float)(M_SQRT1_2)); + auto kBetaVec = Vectorized((float)(M_2_SQRTPI * M_SQRT1_2 * 0.5)); + auto kOneVec = Vectorized((float)(1)); + auto kPointFiveVec = Vectorized((float)(0.5)); + auto kMinusPointFiveVec = Vectorized((float)(-0.5)); + cpu_kernel_vec( + it, + [](scalar_t dy, scalar_t x) -> scalar_t { + const float kAlpha = float(M_SQRT1_2); + const float kBeta = float(M_2_SQRTPI) * float(M_SQRT1_2) * float(0.5); + const float cdf = + float(0.5) * (float(1) + std::erf(float(x) * kAlpha)); + const float pdf = kBeta * std::exp(float(x) * float(x) * float(-0.5)); + return float(dy) * (cdf + float(x) * pdf); + }, + [&](Vectorized dy, Vectorized x) -> Vectorized { + auto [x0, x1] = convert_to_float(x); + auto [dy0, dy1] = convert_to_float(dy); + auto cdf_vec0 = kPointFiveVec * (kOneVec + (x0 * kAlphaVec).erf()); + auto cdf_vec1 = kPointFiveVec * (kOneVec + (x1 * kAlphaVec).erf()); + auto pdf_vec0 = kBetaVec * (x0 * x0 * kMinusPointFiveVec).exp(); + auto pdf_vec1 = kBetaVec * (x1 * x1 * kMinusPointFiveVec).exp(); + auto res0 = dy0 * (cdf_vec0 + x0 * pdf_vec0); + auto res1 = dy1 * (cdf_vec1 + x1 * pdf_vec1); + return convert_from_float(res0, res1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES( + it.dtype(), "GeluBackwardKernelImpl", [&]() { + using Vec = vec::Vectorized; + const Vec kAlphaVec(scalar_t(M_SQRT1_2)); + const Vec kBetaVec(scalar_t(M_2_SQRTPI * M_SQRT1_2 * 0.5)); + const Vec kOneVec(scalar_t(1)); + const Vec kPointFiveVec(scalar_t(0.5)); + const Vec kMinusPointFiveVec(scalar_t(-0.5)); + cpu_kernel_vec( + it, + [](scalar_t dy, scalar_t x) { + const scalar_t kAlpha = scalar_t(M_SQRT1_2); + const scalar_t kBeta = M_2_SQRTPI * M_SQRT1_2 * scalar_t(0.5); + const scalar_t cdf = + scalar_t(0.5) * (scalar_t(1) + std::erf(x * kAlpha)); + const scalar_t pdf = kBeta * std::exp(x * x * scalar_t(-0.5)); + return dy * (cdf + x * pdf); + }, + [&](Vec dy_vec, Vec x_vec) { + const Vec cdf_vec = + kPointFiveVec * (kOneVec + (x_vec * kAlphaVec).erf()); + const Vec pdf_vec = + kBetaVec * (x_vec * x_vec * kMinusPointFiveVec).exp(); + return dy_vec * (cdf_vec + x_vec * pdf_vec); + }); + }); + } + } +} + +void hardsigmoid_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "hardsigmoid_cpu", [&]() { + const float zero(0.0f); + const float three(3.0f); + const float six(6.0f); + using Vec = vec::Vectorized; + const Vec kZeroVec(zero); + const Vec kThreeVec(three); + const Vec kSixVec(six); + cpu_kernel_vec( + iter, + [&](scalar_t self_val) -> scalar_t { + return std::clamp(float(self_val) + three, zero, six) / six; + }, + [&](vec::Vectorized self_val) -> vec::Vectorized { + auto [self_val0, self_val1] = convert_to_float(self_val); + self_val0 = minimum( + maximum(self_val0 + kThreeVec, kZeroVec), + kSixVec + ) / kSixVec; + self_val1 = minimum( + maximum(self_val1 + kThreeVec, kZeroVec), + kSixVec + ) / kSixVec; + return convert_from_float(self_val0, self_val1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "hardsigmoid_cpu", [&] { + const scalar_t zero(0.0f); + const scalar_t three(3.0f); + const scalar_t six(6.0f); + using Vec = vec::Vectorized; + const Vec kZeroVec(zero); + const Vec kThreeVec(three); + const Vec kSixVec(six); + cpu_kernel_vec( + iter, + [&](scalar_t self_val) { + return std::clamp(self_val + three, zero, six) / six; + }, + [&](Vec self_val) { + return vec::minimum( + vec::maximum(self_val + kThreeVec, kZeroVec), + kSixVec + ) / kSixVec; + }); + }); + } +} + +void hardsigmoid_backward_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.common_dtype(), "hardsigmoid_backward", [&]() { + const float zero(0.0f); + const float three(3.0f); + const float neg_three(-3.0f); + const float one_sixth(1.0f / 6.0f); + using Vec = Vectorized; + Vec kZeroVec(0.0f); + Vec kOneSixthVec(1.0f / 6.0f); + cpu_kernel_vec( + iter, + [=](scalar_t grad_val, scalar_t self_val) -> scalar_t { + return (float(self_val) > neg_three && float(self_val) < three) + ? float(grad_val) * one_sixth + : zero; + }, + [=](Vectorized grad_val, Vectorized self_val) -> Vectorized { + auto [self_val0, self_val1] = convert_to_float(self_val); + auto [grad_val0, grad_val1] = convert_to_float(grad_val); + Vec gradNonZeroMask = (self_val0 > neg_three) & (self_val0 < three); + self_val0 = Vec::blendv(kZeroVec, grad_val0 * kOneSixthVec, gradNonZeroMask); + gradNonZeroMask = (self_val1 > neg_three) & (self_val1 < three); + self_val1 = Vec::blendv(kZeroVec, grad_val1 * kOneSixthVec, gradNonZeroMask); + return convert_from_float(self_val0, self_val1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "hardsigmoid_backward", [&] { + const scalar_t zero(0.0f); + const scalar_t three(3.0f); + const scalar_t neg_three(-3.0f); + const scalar_t one_sixth(1.0f / 6.0f); + using Vec = Vectorized; + Vec kZeroVec(0.0f); + Vec kOneSixthVec(1.0f / 6.0f); + cpu_kernel_vec( + iter, + [=](scalar_t grad_val, scalar_t self_val) { + return (self_val > neg_three && self_val < three) + ? grad_val * one_sixth + : zero; + }, + [=](Vec grad_val, Vec self_val) { + Vec gradNonZeroMask = (self_val > neg_three) & (self_val < three); + return Vec::blendv(kZeroVec, grad_val * kOneSixthVec, gradNonZeroMask); + }); + }); + } +} + +void hardshrink_kernel(TensorIteratorBase& iter, const Scalar& lambd) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "hardshrink_cpu", [&] { + auto lambd_val = lambd.to(); + using Vec = Vectorized; + cpu_kernel_vec( + iter, + [=](scalar_t self_val) { + return (self_val >= -lambd_val && self_val <= lambd_val) ? scalar_t(0) + : self_val; + }, + [=](Vec self_val) { + return Vec::blendv(self_val, Vec(0), (self_val >= -lambd_val) & (self_val <= lambd_val)); + }); + }); +} + +void softshrink_kernel(TensorIteratorBase& iter, const Scalar& lambd) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.common_dtype(), "softshrink_cpu", [&]() { + auto lambd_val = lambd.to(); + auto lambdVec = Vectorized(lambd_val); + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { + return float(a) > lambd_val ? a - lambd_val + : (float(a) < -lambd_val ? a + lambd_val : float(a) * float(0)); + }, + [=](Vectorized self_val) -> Vectorized { + auto [self_val0, self_val1] = convert_to_float(self_val); + auto self_val_t0 = convert_from_float( + ((self_val0 > lambdVec) | (self_val0.isnan())) & (self_val0 - lambdVec), + ((self_val1 > lambdVec) | (self_val1.isnan())) & (self_val1 - lambdVec)); + auto self_val_t1 = convert_from_float( + ((self_val0 < -lambd_val) | (self_val0.isnan())) & (self_val0 + lambdVec), + ((self_val1 < -lambd_val) | (self_val1.isnan())) & (self_val1 + lambdVec)); + return (self_val_t0 | self_val_t1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "softshrink_cpu", [&]() { + auto lambd_val = lambd.to(); + auto lambdVec = Vectorized(lambd_val); + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { + return a > lambd_val ? a - lambd_val : (a < -lambd_val ? a + lambd_val : a * scalar_t(0)); + }, + [=](Vectorized self_val) -> Vectorized { + Vectorized self_val_t0, self_val_t1; + self_val_t0 = ((self_val > lambdVec) | (self_val.isnan())) & (self_val - lambdVec); + self_val_t1 = ((self_val < -lambd_val) | (self_val.isnan())) & (self_val + lambdVec); + return (self_val_t0 | self_val_t1); + }); + }); + } +} + +void shrink_backward_kernel(TensorIteratorBase& iter, const Scalar& lambd) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "shrink_backward_cpu", [&] { + auto lambd_val = lambd.to(); + cpu_kernel_vec( + iter, + [=](scalar_t grad_val, scalar_t self_val) { + return (self_val >= -lambd_val && self_val <= lambd_val) ? scalar_t(0) + : grad_val; + }, + [=](Vectorized grad_val, Vectorized self_val) { + return ((self_val < -lambd_val) | (self_val > lambd_val)) & grad_val; + }); + }); +} + +void hardtanh_backward_kernel(TensorIterator& iter, const Scalar& min, const Scalar& max) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "hardshrink_backward_cpu", [&]() { + auto min_val = min.to(); + auto max_val = max.to(); + cpu_kernel_vec( + iter, + [=](scalar_t grad_val, scalar_t self_val) -> scalar_t { + return (float(self_val) <= min_val || float(self_val) >= max_val) ? scalar_t(0) : grad_val; + }, + [=](Vectorized grad_val, Vectorized self_val) -> Vectorized { + auto [grad_val0, grad_val1] = convert_to_float(grad_val); + auto [self_val0, self_val1] = convert_to_float(self_val); + return convert_from_float( + ((self_val0 > min_val) & (self_val0 < max_val)) & grad_val0, + ((self_val1 > min_val) & (self_val1 < max_val)) & grad_val1 + ); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "hardshrink_backward_cpu", [&] { + auto min_val = min.to(); + auto max_val = max.to(); + cpu_kernel_vec( + iter, + [=](scalar_t grad_val, scalar_t self_val) { + return (self_val <= min_val || self_val >= max_val) ? scalar_t(0) : grad_val; + }, + [=](Vectorized grad_val, Vectorized self_val) { + return ((self_val > min_val) & (self_val < max_val)) & grad_val; + }); + }); + } +} + +void hardswish_kernel(TensorIterator& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "hardswish_cpu", [&]() { + const float zero(0.0f); + const float three(3.0f); + const float six(6.0f); + using Vec = vec::Vectorized; + const Vec kZeroVec(zero); + const Vec kThreeVec(three); + const Vec kSixVec(six); + cpu_kernel_vec( + iter, + [&](scalar_t x) -> scalar_t { + return float(x) * std::clamp(float(x) + three, zero, six) / six; + }, + [&](vec::Vectorized x_vec) { + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + x_vec0 = x_vec0 * minimum( + maximum(x_vec0 + kThreeVec, kZeroVec), + kSixVec + ) / kSixVec; + x_vec1 = x_vec1 * minimum( + maximum(x_vec1 + kThreeVec, kZeroVec), + kSixVec + ) / kSixVec; + return convert_from_float(x_vec0, x_vec1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "hardswish_cpu", [&]() { + const scalar_t zero(0.0f); + const scalar_t three(3.0f); + const scalar_t six(6.0f); + using Vec = vec::Vectorized; + const Vec kZeroVec(zero); + const Vec kThreeVec(three); + const Vec kSixVec(six); + cpu_kernel_vec( + iter, + [&](scalar_t x) { + return x * std::clamp(x + three, zero, six) / six; + }, + [&](Vec x_vec) { + return x_vec * vec::minimum( + vec::maximum(x_vec + kThreeVec, kZeroVec), + kSixVec + ) / kSixVec; + } + ); + }); + } +} + +void hardswish_backward_kernel(TensorIterator& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "hardswish_backward_cpu", [&]() { + const float zero(0.0f); + const float three(3.0f); + const float neg_three(-3.0f); + const float one_half(0.5f); + using Vec = vec::Vectorized; + const Vec kZeroVec(zero); + const Vec kThreeVec(three); + const Vec kNegThreeVec(neg_three); + const Vec kOneHalfVec(one_half); + cpu_kernel_vec( + iter, + [&](scalar_t grad_val, scalar_t self_val) -> scalar_t { + if (float(self_val) <= neg_three) { + return zero; + } else if (float(self_val) < three) { + return float(grad_val) * ((float(self_val) / three) + one_half); + } else { + return grad_val; + } + }, + [&](vec::Vectorized grad_val, vec::Vectorized self_val) { + auto [self_val0, self_val1] = convert_to_float(self_val); + auto [grad_val0, grad_val1] = convert_to_float(grad_val); + self_val0 = Vec::blendv( + Vec::blendv( + grad_val0 * ((self_val0 / kThreeVec) + kOneHalfVec), + grad_val0, + self_val0 >= kThreeVec + ), + kZeroVec, + self_val0 <= kNegThreeVec + ); + self_val1 = Vec::blendv( + Vec::blendv( + grad_val1 * ((self_val1 / kThreeVec) + kOneHalfVec), + grad_val1, + self_val1 >= kThreeVec + ), + kZeroVec, + self_val1 <= kNegThreeVec + ); + return convert_from_float(self_val0, self_val1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "hardswish_backward_cpu", [&]() { + const scalar_t zero(0.0f); + const scalar_t three(3.0f); + const scalar_t neg_three(-3.0f); + const scalar_t one_half(0.5f); + using Vec = vec::Vectorized; + const Vec kZeroVec(zero); + const Vec kThreeVec(three); + const Vec kNegThreeVec(neg_three); + const Vec kOneHalfVec(one_half); + cpu_kernel_vec( + iter, + [&](scalar_t grad_val, scalar_t self_val) { + if (self_val <= neg_three) { + return zero; + } else if (self_val < three) { + return grad_val * ((self_val / three) + one_half); + } else { + return grad_val; + } + }, + [&](Vec grad_val, Vec self_val) { + return Vec::blendv( + Vec::blendv( + grad_val * ((self_val / kThreeVec) + kOneHalfVec), + grad_val, + self_val >= kThreeVec + ), + kZeroVec, + self_val <= kNegThreeVec + ); + } + ); + }); + } +} + +void leaky_relu_kernel(TensorIteratorBase& iter, const Scalar& negval_) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "leaky_relu_cpu", [&]() { + auto zero_vec = Vectorized((float)(0)); + auto one_vec = Vectorized((float)(1)); + float negval = negval_.to(); + Vectorized negval_v = Vectorized(negval); + cpu_kernel_vec( + iter, + [&](scalar_t a) -> scalar_t { + return float(a) > float(0) ? float(a) : float(a) * negval; + }, + [&](Vectorized a) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + auto res0 = a0 * (Vectorized::blendv(negval_v, one_vec, a0 > zero_vec)); + auto res1 = a1 * (Vectorized::blendv(negval_v, one_vec, a1 > zero_vec)); + return convert_from_float(res0, res1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "leaky_relu_cpu", [&] { + using Vec = Vectorized; + auto zero_vec = Vec((scalar_t)(0)); + auto one_vec = Vec((scalar_t)(1)); + scalar_t negval = negval_.to(); + Vec negval_v = Vec(negval); + cpu_kernel_vec( + iter, + [&](scalar_t a) -> scalar_t { + return a > scalar_t(0) ? a : a * negval; + }, + [&](Vec a) -> Vec { + auto r = Vec::blendv(negval_v, one_vec, a > zero_vec); + return a * r; + }); + }); + } +} + +void leaky_relu_backward_kernel(TensorIteratorBase& iter, const Scalar& negval_) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "leaky_relu_backward_cpu", [&]() { + auto zero_vec = Vectorized((float)(0)); + auto one_vec = Vectorized((float)(1)); + float negval = negval_.to(); + Vectorized negval_v = Vectorized(negval); + cpu_kernel_vec( + iter, + [&](scalar_t a, scalar_t b) -> scalar_t { + return float(a) > float(0) ? float(b) : float(b) * negval; + }, + [&](Vectorized a, Vectorized b) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + auto res0 = b0 * (Vectorized::blendv(negval_v, one_vec, a0 > zero_vec)); + auto res1 = b1 * (Vectorized::blendv(negval_v, one_vec, a1 > zero_vec)); + return convert_from_float(res0, res1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "leaky_relu_backward_cpu", [&] { + using Vec = Vectorized; + auto zero_vec = Vec((scalar_t)(0)); + auto one_vec = Vec((scalar_t)(1)); + scalar_t negval = negval_.to(); + Vec negval_v = Vec(negval); + cpu_kernel_vec( + iter, + [&](scalar_t a, scalar_t b) -> scalar_t { + return a > scalar_t(0) ? b : b * negval; + }, + [&](Vec a, Vec b) -> Vec { + auto r = Vec::blendv(negval_v, one_vec, a > zero_vec); + return b * r; + }); + }); + } +} + +void softplus_kernel(TensorIteratorBase& iter, const Scalar& beta_, const Scalar& threshold_) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "softplus_cpu", [&]() { + using Vec = Vectorized; + auto beta = beta_.to(); + auto threshold = threshold_.to(); + const Vec beta_vec(beta); + const Vec threshold_vec(threshold); + cpu_kernel_vec( + iter, + [beta, threshold](scalar_t a) -> scalar_t { + return (float(a) * beta) > threshold ? a + : static_cast((std::log1p(std::exp(float(a) * beta))) / beta); + }, + [beta_vec, threshold_vec](Vectorized a) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + a0 = Vec::blendv((a0 * beta_vec).exp().log1p() / beta_vec, a0, (a0 * beta_vec) > threshold_vec); + a1 = Vec::blendv((a1 * beta_vec).exp().log1p() / beta_vec, a1, (a1 * beta_vec) > threshold_vec); + return convert_from_float(a0, a1); + } + ); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "softplus_cpu", [&]() { + using Vec = Vectorized; + auto beta = beta_.to(); + auto threshold = threshold_.to(); + const Vec beta_vec(beta); + const Vec threshold_vec(threshold); + cpu_kernel_vec( + iter, + [beta, threshold](scalar_t a) -> scalar_t { + return (a * beta) > threshold ? a + : static_cast(std::log1p(std::exp(a * beta))) / beta; + }, + [beta_vec, threshold_vec](Vec a) -> Vec { + return Vec::blendv((a * beta_vec).exp().log1p() / beta_vec, a, (a * beta_vec) > threshold_vec); + } + ); + }); + } +} + +void softplus_backward_kernel(TensorIteratorBase& iter, const Scalar& beta_, const Scalar& threshold_) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "softplus_backward_cpu", [&]() { + using Vec = Vectorized; + auto beta = beta_.to(); + auto threshold = threshold_.to(); + const Vec beta_vec(beta); + const Vec threshold_vec(threshold); + const Vec one_vec(1.0f); + cpu_kernel_vec( + iter, + [beta, threshold](scalar_t a, scalar_t b) -> scalar_t { + float z = std::exp(float(b) * beta); + return (float(b) * beta) > threshold ? a : static_cast(float(a) * z / (z + float(1.))); + }, + [beta_vec, one_vec, threshold_vec](Vectorized a, Vectorized b) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + Vec z = (b0 * beta_vec).exp(); + a0 = Vec::blendv(a0 * z / (z + one_vec), a0, (b0 * beta_vec) > threshold_vec); + z = (b1 * beta_vec).exp(); + a1 = Vec::blendv(a1 * z / (z + one_vec), a1, (b1 * beta_vec) > threshold_vec); + return convert_from_float(a0, a1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "softplus_backward_cpu", [&]() { + using Vec = Vectorized; + auto beta = beta_.to(); + auto threshold = threshold_.to(); + const Vec beta_vec(beta); + const Vec threshold_vec(threshold); + const Vec one_vec(static_cast(1.0)); + cpu_kernel_vec( + iter, + [beta, threshold](scalar_t a, scalar_t b) -> scalar_t { + scalar_t z = std::exp(b * beta); + return (b * beta) > threshold ? a : a * z / (z + scalar_t(1.)); + }, + [beta_vec, one_vec, threshold_vec](Vec a, Vec b) -> Vec { + const Vec z = (b * beta_vec).exp(); + return Vec::blendv(a * z / (z + one_vec), a, (b * beta_vec) > threshold_vec); + } + ); + }); + } +} + +void glu_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "glu_cpu", [&]() { + const float float_one_val(1); + const Vectorized float_one_vec(float_one_val); + cpu_kernel_vec( + iter, + [float_one_val](scalar_t a, scalar_t b) -> scalar_t { + return float(a) * (float_one_val / (float_one_val + std::exp(- float(b)))); + }, + [float_one_vec](Vectorized a, Vectorized b) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + return convert_from_float(a0 * (float_one_vec / (float_one_vec + b0.neg().exp())), + a1 * (float_one_vec / (float_one_vec + b1.neg().exp()))); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "glu_cpu", [&] { + using Vec = Vectorized; + const scalar_t one_val(1); + const Vec one_vec(one_val); + cpu_kernel_vec( + iter, + [one_val](scalar_t a, scalar_t b) -> scalar_t { + return a * (one_val / (one_val + std::exp(-b))); + }, + [one_vec](Vec a, Vec b) -> Vec { + return a * (one_vec / (one_vec + b.neg().exp())); + } + ); + }); + } +} + +void glu_jvp_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "glu_jvp_cpu", [&] { + using Vec = Vectorized; + const scalar_t one(1); + const Vec ones(one); + cpu_kernel_vec( + iter, + [one](scalar_t res, scalar_t b, scalar_t da, scalar_t db) -> scalar_t { + const auto sig_b = one / (one + std::exp(-b)); + return da * sig_b + res * (db - sig_b * db); + }, + [ones](Vec res, Vec b, Vec da, Vec db) -> Vec { + const auto sig_b = ones / (ones + b.neg().exp()); + return da * sig_b + res * (db - sig_b * db); + } + ); + }); +} + +void glu_backward_kernel(TensorIterator& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "glu_backward_cpu", [&]() { + const float float_one_val(1); + const Vectorized float_one_vec(float_one_val); + cpu_kernel_vec( + iter, + [float_one_val](scalar_t a, scalar_t b, scalar_t c) -> scalar_t { + return (float_one_val - float(a)) * float(a) * float(b) * float(c); + }, + [float_one_vec](Vectorized a, Vectorized b, Vectorized c) -> Vectorized { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + auto [c0, c1] = convert_to_float(c); + a0 = (float_one_vec - a0) * a0 * b0 * c0; + a1 = (float_one_vec - a1) * a1 * b1 * c1; + return convert_from_float(a0, a1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "glu_backward_cpu", [&] { + using Vec = Vectorized; + const scalar_t one_val(1); + const Vec one_vec(one_val); + cpu_kernel_vec( + iter, + [one_val](scalar_t a, scalar_t b, scalar_t c) -> scalar_t { + return (one_val - a) * a * b * c; + }, + [one_vec](Vec a, Vec b, Vec c) -> Vec { + return (one_vec - a) * a * b * c; + } + ); + }); + } +} + +void silu_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "silu_cpu", [&]() { + const Vectorized kOneVec(1.0f); + cpu_kernel_vec( + iter, + [](scalar_t x) -> scalar_t { + return float(x) / (1.0f + std::exp(-float(x))); + }, + [kOneVec](Vectorized x_vec) -> Vectorized { + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + return convert_from_float( + x_vec0 / (kOneVec + x_vec0.neg().exp()), + x_vec1 / (kOneVec + x_vec1.neg().exp())); + }); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES( + iter.dtype(), "silu_cpu", [&]() { + const Vectorized kOneVec(scalar_t(1)); + cpu_kernel_vec( + iter, + [](scalar_t x) { + return x / (scalar_t(1) + std::exp(-x)); + }, + [kOneVec](Vectorized x_vec) { + return x_vec / (kOneVec + x_vec.neg().exp()); + }); + }); + } +} + +void silu_backward_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "silu_backward_cpu", [&]() { + const Vectorized kOneVec(1.0f); + cpu_kernel_vec( + iter, + [](scalar_t dy, scalar_t x) -> scalar_t { + const float sigmoid = + 1.0f / (1.0f + std::exp(-float(x))); + return dy * sigmoid * (1.0f + x * (1.0f - sigmoid)); + }, + [kOneVec](Vectorized dy_vec, Vectorized x_vec) -> Vectorized { + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + const Vectorized sigmoid0 = + kOneVec / (kOneVec + x_vec0.neg().exp()); + const Vectorized sigmoid1 = + kOneVec / (kOneVec + x_vec1.neg().exp()); + return convert_from_float( + dy_vec0 * sigmoid0 * (kOneVec + x_vec0 * (kOneVec - sigmoid0)), + dy_vec1 * sigmoid1 * (kOneVec + x_vec1 * (kOneVec - sigmoid1))); + }); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES( + iter.dtype(), "silu_backward_cpu", [&]() { + const Vectorized kOneVec(scalar_t(1)); + cpu_kernel_vec( + iter, + [](scalar_t dy, scalar_t x) { + const scalar_t sigmoid = + scalar_t(1) / (scalar_t(1) + std::exp(-x)); + return dy * sigmoid * (scalar_t(1) + x * (scalar_t(1) - sigmoid)); + }, + [kOneVec](Vectorized dy_vec, Vectorized x_vec) { + const Vectorized sigmoid = + kOneVec / (kOneVec + x_vec.neg().exp()); + return dy_vec * sigmoid * (kOneVec + x_vec * (kOneVec - sigmoid)); + }); + }); + } +} + +void mish_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "mish_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t x) -> scalar_t{ + return static_cast(float(x) * std::tanh(std::log1p(std::exp(float(x))))); + }, + [](Vectorized x_vec) -> Vectorized { + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + return convert_from_float( + x_vec0 * x_vec0.exp().log1p().tanh(), + x_vec1 * x_vec1.exp().log1p().tanh() + ); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "mish_cpu", [&]() { + using Vec = Vectorized; + cpu_kernel_vec( + iter, + [](scalar_t x) -> scalar_t{ + return static_cast(x * std::tanh(std::log1p(std::exp(x)))); + }, + [](Vec x_vec) -> Vec { + return x_vec * x_vec.exp().log1p().tanh(); + }); + }); + } +} + +void mish_backward_kernel(TensorIterator& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "mish_backward_cpu", [&]() { + using Vec = Vectorized; + const Vec kOneVec(1.0f); + cpu_kernel_vec( + iter, + [](scalar_t dy, scalar_t x) -> scalar_t { + const float sigmoid = + 1.0f / (1.0f + std::exp(-float(x))); + const float tanh_softplus = std::tanh(std::log1p(std::exp(float(x)))); + return dy * (tanh_softplus + x * sigmoid * (1.0f - tanh_softplus * tanh_softplus)); + }, + [kOneVec](Vectorized dy_vec, Vectorized x_vec) -> Vectorized { + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + const Vec sigmoid0 = kOneVec / (kOneVec + x_vec0.neg().exp()); + const Vec sigmoid1 = kOneVec / (kOneVec + x_vec1.neg().exp()); + const Vec tanh_softplus0 = x_vec0.exp().log1p().tanh(); + const Vec tanh_softplus1 = x_vec1.exp().log1p().tanh(); + return convert_from_float( + dy_vec0 * (tanh_softplus0 + x_vec0 * sigmoid0 * (kOneVec - tanh_softplus0 * tanh_softplus0)), + dy_vec1 * (tanh_softplus1 + x_vec1 * sigmoid1 * (kOneVec - tanh_softplus1 * tanh_softplus1)) + ); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "mish_backward_cpu", [&]() { + using Vec = Vectorized; + const Vec kOneVec(scalar_t(1)); + cpu_kernel_vec( + iter, + [](scalar_t dy, scalar_t x) -> scalar_t { + const scalar_t sigmoid = + scalar_t(1) / (scalar_t(1) + std::exp(-x)); + const scalar_t tanh_softplus = std::tanh(std::log1p(std::exp(x))); + return dy * (tanh_softplus + x * sigmoid * (scalar_t(1) - tanh_softplus * tanh_softplus)); + }, + [kOneVec](Vec dy_vec, Vec x_vec) -> Vec { + const Vec sigmoid = kOneVec / (kOneVec + x_vec.neg().exp()); + const Vec tanh_softplus = x_vec.exp().log1p().tanh(); + return dy_vec * (tanh_softplus + x_vec * sigmoid * (kOneVec - tanh_softplus * tanh_softplus)); + }); + }); + } +} + +void prelu_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "prelu_cpu", [&]() { + using Vec = Vectorized; + cpu_kernel_vec( + iter, + [](scalar_t input, scalar_t weight) { + return (input > scalar_t(0)) ? input : weight * input; + }, + [](Vec input, Vec weight) { + return Vec::blendv(weight * input, input, input > Vec(0)); + }); + }); +} + +void prelu_backward_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "prelu_backward_cpu", [&]() { + cpu_kernel_multiple_outputs(iter, + [](scalar_t input, scalar_t weight, scalar_t grad) -> std::tuple { + auto mask = input > scalar_t{0}; + auto grad_input = mask ? grad : weight * grad; + auto grad_weight = mask ? scalar_t{0} : input * grad; + return {grad_input, grad_weight}; + }); + }); +} + +} // namespace + + +REGISTER_DISPATCH(hardsigmoid_stub, &hardsigmoid_kernel) +REGISTER_DISPATCH(hardsigmoid_backward_stub, &hardsigmoid_backward_kernel) +REGISTER_DISPATCH(threshold_stub, &threshold_kernel) +REGISTER_DISPATCH(leaky_relu_stub, &leaky_relu_kernel) +REGISTER_DISPATCH(leaky_relu_backward_stub, &leaky_relu_backward_kernel) +REGISTER_DISPATCH(prelu_stub, &prelu_kernel) +REGISTER_DISPATCH(prelu_backward_stub, &prelu_backward_kernel) +REGISTER_DISPATCH(hardtanh_backward_stub, &hardtanh_backward_kernel) +REGISTER_DISPATCH(hardshrink_stub, &hardshrink_kernel) +REGISTER_DISPATCH(softshrink_stub, &softshrink_kernel) +REGISTER_DISPATCH(shrink_backward_stub, &shrink_backward_kernel) + +ALSO_REGISTER_AVX512_DISPATCH(log_sigmoid_cpu_stub, &log_sigmoid_cpu_kernel) +ALSO_REGISTER_AVX512_DISPATCH(log_sigmoid_backward_stub, &log_sigmoid_backward_cpu_kernel) +ALSO_REGISTER_AVX512_DISPATCH(glu_stub, &glu_kernel) +ALSO_REGISTER_AVX512_DISPATCH(glu_backward_stub, &glu_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(glu_jvp_stub, &glu_jvp_kernel) +ALSO_REGISTER_AVX512_DISPATCH(elu_stub, &elu_kernel) +ALSO_REGISTER_AVX512_DISPATCH(elu_backward_stub, &elu_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(GeluKernel, &GeluKernelImpl) +ALSO_REGISTER_AVX512_DISPATCH(GeluBackwardKernel, &GeluBackwardKernelImpl) +ALSO_REGISTER_AVX512_DISPATCH(hardswish_stub, &hardswish_kernel) +ALSO_REGISTER_AVX512_DISPATCH(hardswish_backward_stub, &hardswish_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(softplus_stub, &softplus_kernel) +ALSO_REGISTER_AVX512_DISPATCH(softplus_backward_stub, &softplus_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(silu_stub, &silu_kernel) +ALSO_REGISTER_AVX512_DISPATCH(silu_backward_stub, &silu_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(mish_stub, &mish_kernel) +ALSO_REGISTER_AVX512_DISPATCH(mish_backward_stub, &mish_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AdaptiveAvgPoolKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AdaptiveAvgPoolKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5237dd7c20c94cbdd4066a19b1ce028ade5e1fa3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AdaptiveAvgPoolKernel.cpp @@ -0,0 +1,862 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void cpu_adaptive_avg_pool2d( + Tensor& output_, + const Tensor& input_, + IntArrayRef output_size) { + auto input = input_.contiguous(); + auto output = output_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? input.size(0) : input.size(0) * input.size(1); + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + c * input_height * input_width; + scalar_t* output_ptr = output_data + c * output_height * output_width; + + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + // compute local average + accscalar_t sum = 0; + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + sum += accscalar_t(input_ptr[ih * input_width + iw]); + } + } + output_ptr[oh * output_width + ow] = scalar_t(sum / kh / kw); + } + } + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_avg_pool2d_channels_last( + Tensor& output_, + const Tensor& input_, + IntArrayRef output_size) { + auto memory_format = at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + using Vec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t* out = output_data + i * channels; + int64_t size = channels; + + // Note: For ordinary usage scenario, each out lane should + // fit in L1 cache; otherwise consider block dim C. + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec out_vec = Vec(scalar_t(0)); + out_vec.store(out + d1); + } + for (; d1 < size; d1++) { + out[d1] = scalar_t(0); + } + // Pass II: compute local sum + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + const scalar_t* in = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d2) + Vec::loadu(in + d2); + out_vec.store(out + d2); + } + for (; d2 < size; d2++) { + out[d2] += in[d2]; + } + } + } + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < size - (size % Vec::size()); d3 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d3) / Vec(scalar_t(kh * kw)); + out_vec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = out[d3] / kh / kw; + } + + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_avg_pool2d_channels_last( + Tensor& output_, + const Tensor& input_, + IntArrayRef output_size) { + auto memory_format = at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + // temp buffer for sum, use float as accumulation type + // can't reuse output buffer to store sum since it is BFloat16/Half + auto sum_arr = std::make_unique(channels); + float* sum = sum_arr.get(); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t* out = output_data + i * channels; + int64_t size = channels; + + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < size - (size % fVec::size()); d1 += fVec::size()) { + fVec sum_fvec = fVec(float(0)); + sum_fvec.store(sum + d1); + } + for (; d1 < size; d1++) { + sum[d1] = float(0); + } + // Pass II: compute local sum + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + const scalar_t* in = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < size - (size % bVec::size()); d2 += bVec::size()) { + bVec data_bvec = bVec::loadu(in + d2); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + + fVec sum_fvec0 = fVec::loadu(sum + d2) + data_fvec0; + fVec sum_fvec1 = fVec::loadu(sum + d2 + fVec::size()) + data_fvec1; + sum_fvec0.store(sum + d2); + sum_fvec1.store(sum + d2 + fVec::size()); + } + for (; d2 < size; d2++) { + sum[d2] += float(in[d2]); + } + } + } + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < size - (size % bVec::size()); d3 += bVec::size()) { + fVec out_fvec0 = fVec::loadu(sum + d3) / fVec(float(kh * kw)); + fVec out_fvec1 = fVec::loadu(sum + d3 + fVec::size()) / fVec(float(kh * kw)); + + bVec out_bvec = convert_from_float(out_fvec0, out_fvec1); + out_bvec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = scalar_t(sum[d3] / kh / kw); + } + + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +void cpu_adaptive_avg_pool2d_backward( + Tensor& grad_input_, + const Tensor& grad_output_) { + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t ndim = grad_output.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_height * input_width; + const scalar_t* grad_output_ptr = grad_output_data + c * output_height * output_width; + + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t grad_delta = grad_output_ptr[oh * output_width + ow] / kh / kw; + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + grad_input_ptr[ih * input_width + iw] += grad_delta; + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_adaptive_avg_pool2d_backward_channels_last( + Tensor& grad_input_, + const Tensor& grad_output_) { + auto memory_format = at::MemoryFormat::ChannelsLast; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.const_data_ptr(); + + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_height = grad_input.size(2); + int64_t input_width = grad_input.size(3); + int64_t output_height = grad_output.size(2); + int64_t output_width = grad_output.size(3); + + using Vec = vec::Vectorized; + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_height * input_width * channels; + const scalar_t* grad_output_ptr = grad_output_data + n * output_height * output_width * channels; + + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + const scalar_t* gout = grad_output_ptr + oh * output_width * channels + ow * channels; + int64_t size = channels; + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + scalar_t* gin = grad_input_ptr + ih * input_width * channels + iw * channels; + + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec gin_vec = Vec::loadu(gin + d) + Vec::loadu(gout + d) / Vec(scalar_t(kh * kw)); + gin_vec.store(gin + d); + } + for (; d < size; d++) { + gin[d] += gout[d] / kh / kw; + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void adaptive_avg_pool2d_kernel_impl( + Tensor& output, + const Tensor& input, + IntArrayRef output_size) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_avg_pool2d", [&] { + using param_t = at::opmath_type; + cpu_adaptive_avg_pool2d(output, input, output_size); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_avg_pool2d_channels_last", [&]{ + cpu_adaptive_avg_pool2d_channels_last(output, input, output_size); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void adapative_avg_pool2d_backward_kernel_impl( + Tensor& grad_input, + const Tensor& grad_output) { + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_avg_pool2d_backward", [&] { + cpu_adaptive_avg_pool2d_backward(grad_input, grad_output); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_avg_pool2d_backward_channels_last", [&]{ + cpu_adaptive_avg_pool2d_backward_channels_last(grad_input, grad_output); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + + +template +void cpu_adaptive_avg_pool3d( + Tensor& output_, + const Tensor& input_, + IntArrayRef output_size) { + auto input = input_.contiguous(); + auto output = output_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 4 ? input.size(0) : input.size(0) * input.size(1); + int64_t input_depth = input.size(-3); + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_depth = output_size[0]; + int64_t output_height = output_size[1]; + int64_t output_width = output_size[2]; + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + c * input_depth * input_height * input_width; + scalar_t* output_ptr = output_data + c * output_depth * output_height * output_width; + + for (const auto od : c10::irange(output_depth)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + int64_t kd = id1 - id0; + + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + // compute local average + accscalar_t sum = 0; + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + sum += accscalar_t(input_ptr[id * input_height * input_width + ih * input_width + iw]); + } + } + } + output_ptr[od * output_height * output_width + oh * output_width + ow] = scalar_t(sum / kd / kh / kw); + } + } + } + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } +} + + +template +typename std::enable_if_t>, void> +cpu_adaptive_avg_pool3d_channels_last( + Tensor& output_, + const Tensor& input_, + IntArrayRef output_size) { + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = input.size(2); + int64_t input_height = input.size(3); + int64_t input_width = input.size(4); + int64_t output_depth = output_size[0]; + int64_t output_height = output_size[1]; + int64_t output_width = output_size[2]; + + using Vec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + int64_t kd = id1 - id0; + + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t* out = output_data + i * channels; + int64_t size = channels; + + // Note: For ordinary usage scenario, each out lane should + // fit in L1 cache; otherwise consider block dim C. + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec out_vec = Vec(scalar_t(0)); + out_vec.store(out + d1); + } + for (; d1 < size; d1++) { + out[d1] = scalar_t(0); + } + // Pass II: compute local sum + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + const scalar_t* in = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d2) + Vec::loadu(in + d2); + out_vec.store(out + d2); + } + for (; d2 < size; d2++) { + out[d2] += in[d2]; + } + } + } + } + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < size - (size % Vec::size()); d3 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d3) / Vec(scalar_t(kd * kh * kw)); + out_vec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = out[d3] / kd / kh / kw; + } + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_avg_pool3d_channels_last( + Tensor& output_, + const Tensor& input_, + IntArrayRef output_size) { + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = input.size(2); + int64_t input_height = input.size(3); + int64_t input_width = input.size(4); + int64_t output_depth = output_size[0]; + int64_t output_height = output_size[1]; + int64_t output_width = output_size[2]; + + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + // parallel on dim N,D, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + int64_t od = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + // temp buffer for sum, use float as accumulation type + // can't reuse output buffer to store sum since it is BFloat16/Half + auto sum_arr = std::make_unique(channels); + float* sum = sum_arr.get(); + + for (const auto i : c10::irange(begin, end)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + int64_t kd = id1 - id0; + + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t* out = output_data + i * channels; + int64_t size = channels; + + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < size - (size % fVec::size()); d1 += fVec::size()) { + fVec sum_fvec = fVec(float(0)); + sum_fvec.store(sum + d1); + } + for (; d1 < size; d1++) { + sum[d1] = float(0); + } + // Pass II: compute local sum + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + const scalar_t* in = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < size - (size % bVec::size()); d2 += bVec::size()) { + bVec data_bvec = bVec::loadu(in + d2); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + + fVec sum_fvec0 = fVec::loadu(sum + d2) + data_fvec0; + fVec sum_fvec1 = fVec::loadu(sum + d2 + fVec::size()) + data_fvec1; + sum_fvec0.store(sum + d2); + sum_fvec1.store(sum + d2 + fVec::size()); + } + for (; d2 < size; d2++) { + sum[d2] += float(in[d2]); + } + } + } + } + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < size - (size % bVec::size()); d3 += bVec::size()) { + fVec out_fvec0 = fVec::loadu(sum + d3) / fVec(float(kd * kh * kw)); + fVec out_fvec1 = fVec::loadu(sum + d3 + fVec::size()) / fVec(float(kd * kh * kw)); + + bVec out_bvec = convert_from_float(out_fvec0, out_fvec1); + out_bvec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = scalar_t(sum[d3] / kd / kh / kw); + } + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +void cpu_adaptive_avg_pool3d_backward( + Tensor& grad_input_, + const Tensor& grad_output_) { + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t ndim = grad_output.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 4 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + int64_t input_depth = grad_input.size(-3); + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_depth = grad_output.size(-3); + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_depth * input_height * input_width; + scalar_t* grad_output_ptr = grad_output_data + c * output_depth * output_height * output_width; + + for (const auto od : c10::irange(output_depth)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + int64_t kd = id1 - id0; + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t grad_delta = grad_output_ptr[od * output_width * output_height + oh * output_width + ow] / kd / kh / kw; + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + grad_input_ptr[id * input_height * input_width + ih * input_width + iw] += grad_delta; + } + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_adaptive_avg_pool3d_backward_channels_last( + Tensor& grad_input_, + const Tensor& grad_output_) { + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.data_ptr(); + + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_depth = grad_input.size(2); + int64_t input_height = grad_input.size(3); + int64_t input_width = grad_input.size(4); + int64_t output_depth = grad_output.size(2); + int64_t output_height = grad_output.size(3); + int64_t output_width = grad_output.size(4); + + using Vec = vec::Vectorized; + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_depth * input_height * input_width * channels; + scalar_t* grad_output_ptr = grad_output_data + n * output_depth * output_height * output_width * channels; + + for (const auto od : c10::irange(output_depth)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + int64_t kd = id1 - id0; + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + int64_t kh = ih1 - ih0; + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + int64_t kw = iw1 - iw0; + + scalar_t* gout = grad_output_ptr + od * output_depth * channels + oh * output_width * channels + ow * channels; + int64_t size = channels; + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + scalar_t* gin = grad_input_ptr + id * input_width * input_height * channels + ih * input_width * channels + iw * channels; + + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec gin_vec = Vec::loadu(gin + d) + Vec::loadu(gout + d) / Vec(scalar_t(kd * kh * kw)); + gin_vec.store(gin + d); + } + for (; d < size; d++) { + gin[d] += gout[d] / kd / kh / kw; + } + } + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + + +void adaptive_avg_pool3d_kernel_impl( + Tensor& output, + const Tensor& input, + IntArrayRef output_size) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_avg_pool3d", [&] { + using param_t = at::opmath_type; + cpu_adaptive_avg_pool3d(output, input, output_size); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_avg_pool3d_channels_last", [&]{ + cpu_adaptive_avg_pool3d_channels_last(output, input, output_size); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void adapative_avg_pool3d_backward_kernel_impl( + Tensor& grad_input, + const Tensor& grad_output) { + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_avg_pool3d_backward", [&] { + cpu_adaptive_avg_pool3d_backward(grad_input, grad_output); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_avg_pool3d_backward_channels_last", [&]{ + cpu_adaptive_avg_pool3d_backward_channels_last(grad_input, grad_output); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(adaptive_avg_pool2d_kernel, &adaptive_avg_pool2d_kernel_impl) +REGISTER_DISPATCH(adaptive_avg_pool2d_backward_kernel, &adapative_avg_pool2d_backward_kernel_impl) +REGISTER_DISPATCH(adaptive_avg_pool3d_kernel, &adaptive_avg_pool3d_kernel_impl) +REGISTER_DISPATCH(adaptive_avg_pool3d_backward_kernel, &adapative_avg_pool3d_backward_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AdaptiveMaxPoolKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AdaptiveMaxPoolKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b9b734a87075eedc37b7223d46d722fb87c700ad --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AdaptiveMaxPoolKernel.cpp @@ -0,0 +1,988 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void cpu_adaptive_max_pool2d( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef output_size) { + auto input = input_.contiguous(); + auto output = output_.contiguous(); + auto indices = indices_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? input.size(0) : input.size(0) * input.size(1); + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + c * input_height * input_width; + scalar_t* output_ptr = output_data + c * output_height * output_width; + int64_t* indices_ptr = indices_data + c * output_height * output_width; + + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + + // compute local max + int64_t maxindex = ih0 * input_width + iw0; + accscalar_t maxval = -std::numeric_limits::infinity(); + for (int64_t ih = ih0; ih < ih1; ih ++) { + for (int64_t iw = iw0; iw < iw1; iw ++) { + int64_t index = ih * input_width + iw; + scalar_t val = input_ptr[index]; + if ((val > maxval) || std::isnan(val)) { + maxval = val; + maxindex = index; + } + } + } + + // set output to local max and store location of max + output_ptr[oh * output_width + ow] = maxval; + indices_ptr[oh * output_width + ow] = maxindex; + } + } + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } + if (!indices_.is_contiguous()) { + indices_.copy_(indices); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_max_pool2d_channels_last( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef output_size) { + TORCH_CHECK(input_.ndimension() == 4, + "2d adaptive max pooling with channels last format supports tensors with 4 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + using Vec = vec::Vectorized; + using integer_t = vec::int_same_size_t; + using iVec = vec::Vectorized; + // for the convenience of vectorization, use integer of the same size of scalar_t, + // e.g. int32_t for float, int64_t for double + // need to make sure doesn't overflow + TORCH_CHECK(input_height * input_width <= std::numeric_limits::max()); + + // parallel on dim of N, H, W + at::parallel_for(0, nbatch * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + // temp buffer holding index with integer_t + auto index_buffer = std::make_unique(len); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + + scalar_t* out = output_data + i * channels; + int64_t* ind = indices_data + i * channels; + + // Pass I: init out lane + iVec index0_vec = iVec(ih0 * input_width + iw0); + Vec out_vec = Vec(-std::numeric_limits::infinity()); + int64_t d1 = 0; + for (; d1 < len; d1 += Vec::size()) { + index0_vec.store(index_buffer.get() + d1); + out_vec.store(out + d1); + } + for (; d1 < size; d1++) { + ind[d1] = ih0 * input_width + iw0; + out[d1] = -std::numeric_limits::infinity(); + } + // Pass II: compute local max + for (int64_t ih = ih0; ih < ih1; ih ++) { + for (int64_t iw = iw0; iw < iw1; iw ++) { + const scalar_t* in = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += Vec::size()) { + iVec index_vec = iVec(ih * input_width + iw); + Vec val_vec = Vec::loadu(in + d2); + iVec maxindex_vec = iVec::loadu(index_buffer.get() + d2); + Vec maxval_vec = Vec::loadu(out + d2); + + // true = all ones, false = all zeros + Vec mask = (val_vec > maxval_vec) | val_vec.isnan(); + iVec imask = vec::cast(mask); + Vec out_vec = Vec::blendv(maxval_vec, val_vec, mask); + iVec ind_vec = iVec::blendv(maxindex_vec, index_vec, imask); + + out_vec.store(out + d2); + ind_vec.store(index_buffer.get() + d2); + } + for (; d2 < size; d2++) { + int64_t index = ih * input_width + iw; + scalar_t val = in[d2]; + int64_t maxindex = ind[d2]; + scalar_t maxval = out[d2]; + + bool mask = (val > maxval) || std::isnan(val); + out[d2] = mask ? val : maxval; + ind[d2] = mask ? index : maxindex; + } + } + } + // convert indice data type + vec::convert(index_buffer.get(), ind, len); + + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } + if (!indices_.is_contiguous(memory_format)) { + indices_.copy_(indices); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_max_pool2d_channels_last( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef output_size) { + TORCH_CHECK(input_.ndimension() == 4, + "2d adaptive max pooling with channels last format supports tensors with 4 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + using iVec = vec::Vectorized; + // need to make sure doesn't overflow + TORCH_CHECK(input_height * input_width <= std::numeric_limits::max()); + + // parallel on dim of N, H, W + at::parallel_for(0, nbatch * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % bVec::size()); + // temp buffer holding index with integer_t + auto index_buffer = std::make_unique(len); + // temp buffer holding max value with float + auto max_arr = std::make_unique(size); + float* max = max_arr.get(); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + + scalar_t* out = output_data + i * channels; + int64_t* ind = indices_data + i * channels; + + // Pass I: init out lane + iVec index0_ivec = iVec(ih0 * input_width + iw0); + fVec max_fvec = fVec(-std::numeric_limits::infinity()); + int64_t d1 = 0; + for (; d1 < len; d1 += fVec::size()) { + index0_ivec.store(index_buffer.get() + d1); + max_fvec.store(max + d1); + } + for (; d1 < size; d1++) { + ind[d1] = ih0 * input_width + iw0; + max[d1] = -std::numeric_limits::infinity(); + } + // Pass II: compute local max + for (int64_t ih = ih0; ih < ih1; ih ++) { + for (int64_t iw = iw0; iw < iw1; iw ++) { + const scalar_t* in = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += bVec::size()) { + iVec index_ivec = iVec(ih * input_width + iw); + bVec val_bvec = bVec::loadu(in + d2); + auto [val_fvec0, val_fvec1] = convert_to_float(val_bvec); + + iVec maxindex_ivec0 = iVec::loadu(index_buffer.get() + d2); + iVec maxindex_ivec1 = iVec::loadu(index_buffer.get() + d2 + iVec::size()); + fVec maxval_fvec0 = fVec::loadu(max + d2); + fVec maxval_fvec1 = fVec::loadu(max + d2 + fVec::size()); + + // true = all ones, false = all zeros + fVec mask0 = (val_fvec0 > maxval_fvec0) | val_fvec0.isnan(); + fVec mask1 = (val_fvec1 > maxval_fvec1) | val_fvec1.isnan(); + iVec imask0 = vec::cast(mask0); + iVec imask1 = vec::cast(mask1); + + fVec max_fvec0 = fVec::blendv(maxval_fvec0, val_fvec0, mask0); + fVec max_fvec1 = fVec::blendv(maxval_fvec1, val_fvec1, mask1); + iVec ind_ivec0 = iVec::blendv(maxindex_ivec0, index_ivec, imask0); + iVec ind_ivec1 = iVec::blendv(maxindex_ivec1, index_ivec, imask1); + + max_fvec0.store(max + d2); + max_fvec1.store(max + d2 + fVec::size()); + ind_ivec0.store(index_buffer.get() + d2); + ind_ivec1.store(index_buffer.get() + d2 + iVec::size()); + } + for (; d2 < size; d2++) { + int64_t index = ih * input_width + iw; + float val = float(in[d2]); + int64_t maxindex = ind[d2]; + float maxval = max[d2]; + + bool mask = (val > maxval) || std::isnan(val); + max[d2] = mask ? val : maxval; + ind[d2] = mask ? index : maxindex; + } + } + } + // Pass III: convert max values from float to bfloat16/Half + int64_t d3 = 0; + for (; d3 < len; d3 += bVec::size()) { + fVec max_fvec0 = fVec::loadu(max + d3); + fVec max_fvec1 = fVec::loadu(max + d3 + fVec::size()); + bVec max_bvec = convert_from_float(max_fvec0, max_fvec1); + max_bvec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = scalar_t(max[d3]); + } + // convert indice data type + vec::convert(index_buffer.get(), ind, len); + + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } + if (!indices_.is_contiguous(memory_format)) { + indices_.copy_(indices); + } +} + +template +void cpu_adaptive_max_pool2d_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + const Tensor& indices_) { + auto grad_output = grad_output_.contiguous(); + auto indices = indices_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t ndim = grad_output.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_height * input_width; + const scalar_t* grad_output_ptr = grad_output_data + c * output_height * output_width; + const int64_t* indices_ptr = indices_data + c * output_height * output_width; + + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + // retrieve position of max + int64_t index = oh * output_width + ow; + int64_t maxindex = indices_ptr[index]; + + // update gradient + grad_input_ptr[maxindex] += grad_output_ptr[index]; + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_adaptive_max_pool2d_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + const Tensor& indices_) { + TORCH_CHECK(grad_output_.ndimension() == 4, + "2d adaptive max pooling backward with channels last format supports tensors with 4 dims."); + auto memory_format = at::MemoryFormat::ChannelsLast; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_height = grad_input.size(2); + int64_t input_width = grad_input.size(3); + int64_t output_height = grad_output.size(2); + int64_t output_width = grad_output.size(3); + + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_height * input_width * channels; + const scalar_t* grad_output_ptr = grad_output_data + n * output_height * output_width * channels; + const int64_t* indices_ptr = indices_data + n * output_height * output_width * channels; + + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + const scalar_t* gout = grad_output_ptr + oh * output_width * channels + ow * channels; + const int64_t* ind = indices_ptr + oh * output_width * channels + ow * channels; + // TODO: gcc vectorization + for (const auto c : c10::irange(channels)) { + int64_t maxindex = ind[c]; + grad_input_ptr[maxindex * channels + c] += gout[c]; + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void adaptive_max_pool2d_kernel_impl( + const Tensor& output, + const Tensor& indices, + const Tensor& input, + IntArrayRef output_size) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_max_pool2d", [&] { + using param_t = at::opmath_type; + cpu_adaptive_max_pool2d(output, indices, input, output_size); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_max_pool2d_channels_last", [&]{ + cpu_adaptive_max_pool2d_channels_last(output, indices, input, output_size); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void adaptive_max_pool2d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + const Tensor& indices) { + // can't use grad_output memory format to switch here since grad_output might be NC11 + switch (grad_input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_max_pool2d_backward", [&] { + cpu_adaptive_max_pool2d_backward(grad_input, grad_output, indices); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_max_pool2d_backward_channels_last", [&]{ + cpu_adaptive_max_pool2d_backward_channels_last(grad_input, grad_output, indices); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +template +void cpu_adaptive_max_pool3d( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef output_size) { + auto input = input_.contiguous(); + auto output = output_.contiguous(); + auto indices = indices_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 4 ? input.size(0) : input.size(0) * input.size(1); + int64_t input_depth = input.size(-3); + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_depth = output_size[0]; + int64_t output_height = output_size[1]; + int64_t output_width = output_size[2]; + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + c * input_depth * input_height * input_width; + scalar_t* output_ptr = output_data + c * output_depth * output_height * output_width; + int64_t* indices_ptr = indices_data + c * output_depth * output_height * output_width; + + for (const auto od : c10::irange(output_depth)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + + // compute local max + int64_t maxindex = id0 * input_height * input_width + ih0 * input_width + iw0; + accscalar_t maxval = -std::numeric_limits::infinity(); + for (int64_t id = id0; id < id1; id ++) { + for (int64_t ih = ih0; ih < ih1; ih ++) { + for (int64_t iw = iw0; iw < iw1; iw ++) { + int64_t index = id * input_height * input_width + ih * input_width + iw; + scalar_t val = input_ptr[index]; + if ((val > maxval) || std::isnan(val)) { + maxval = val; + maxindex = index; + } + } + } + } + + // set output to local max and store location of max + output_ptr[od * output_height * output_width + oh * output_width + ow] = maxval; + indices_ptr[od * output_height * output_width + oh * output_width + ow] = maxindex; + } + } + } + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } + if (!indices_.is_contiguous()) { + indices_.copy_(indices); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_max_pool3d_channels_last( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef output_size) { + TORCH_CHECK(input_.ndimension() == 5, + "3d adaptive max pooling with channels last format supports tensors with 5 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = input.size(2); + int64_t input_height = input.size(3); + int64_t input_width = input.size(4); + int64_t output_depth = output_size[0]; + int64_t output_height = output_size[1]; + int64_t output_width = output_size[2]; + + using Vec = vec::Vectorized; + using integer_t = vec::int_same_size_t; + using iVec = vec::Vectorized; + // for the convenience of vectorization, use integer of the same size of scalar_t, + // e.g. int32_t for float, int64_t for double + // need to make sure doesn't overflow + TORCH_CHECK(input_height * input_width <= std::numeric_limits::max()); + + // parallel on dim of N, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + // temp buffer holding index with integer_t + auto index_buffer = std::make_unique(len); + + for (const auto i : c10::irange(begin, end)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + + scalar_t* out = output_data + i * channels; + int64_t* ind = indices_data + i * channels; + + // Pass I: init out lane + iVec index0_vec = iVec(id0 * input_height * input_width + ih0 * input_width + iw0); + Vec out_vec = Vec(-std::numeric_limits::infinity()); + int64_t d1 = 0; + for (; d1 < len; d1 += Vec::size()) { + index0_vec.store(index_buffer.get() + d1); + out_vec.store(out + d1); + } + for (; d1 < size; d1++) { + ind[d1] = id0 * input_height * input_width + ih0 * input_width + iw0; + out[d1] = -std::numeric_limits::infinity(); + } + // Pass II: compute local max + for (int64_t id = id0; id < id1; id ++) { + for (int64_t ih = ih0; ih < ih1; ih ++) { + for (int64_t iw = iw0; iw < iw1; iw ++) { + const scalar_t* in = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += Vec::size()) { + iVec index_vec = iVec(id * input_height * input_width + ih * input_width + iw); + Vec val_vec = Vec::loadu(in + d2); + iVec maxindex_vec = iVec::loadu(index_buffer.get() + d2); + Vec maxval_vec = Vec::loadu(out + d2); + + // true = all ones, false = all zeros + Vec mask = (val_vec > maxval_vec) | val_vec.isnan(); + iVec imask = vec::cast(mask); + Vec out_vec = Vec::blendv(maxval_vec, val_vec, mask); + iVec ind_vec = iVec::blendv(maxindex_vec, index_vec, imask); + + out_vec.store(out + d2); + ind_vec.store(index_buffer.get() + d2); + } + for (; d2 < size; d2++) { + int64_t index = id * input_height * input_width + ih * input_width + iw; + scalar_t val = in[d2]; + int64_t maxindex = ind[d2]; + scalar_t maxval = out[d2]; + + bool mask = (val > maxval) || std::isnan(val); + out[d2] = mask ? val : maxval; + ind[d2] = mask ? index : maxindex; + } + } + } + } + // convert indice data type + vec::convert(index_buffer.get(), ind, len); + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } + if (!indices_.is_contiguous(memory_format)) { + indices_.copy_(indices); + } +} + +template +typename std::enable_if_t>, void> +cpu_adaptive_max_pool3d_channels_last( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef output_size) { + TORCH_CHECK(input_.ndimension() == 5, + "3d adaptive max pooling with channels last format supports tensors with 5 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = input.size(2); + int64_t input_height = input.size(3); + int64_t input_width = input.size(4); + int64_t output_depth = output_size[0]; + int64_t output_height = output_size[1]; + int64_t output_width = output_size[2]; + + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + using iVec = vec::Vectorized; + // need to make sure doesn't overflow + TORCH_CHECK(input_height * input_width <= std::numeric_limits::max()); + + // parallel on dim of N, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % bVec::size()); + // temp buffer holding index with integer_t + auto index_buffer = std::make_unique(len); + // temp buffer holding max value with float + auto max_arr = std::make_unique(size); + float* max = max_arr.get(); + + for (const auto i : c10::irange(begin, end)) { + int64_t id0 = start_index(od, output_depth, input_depth); + int64_t id1 = end_index(od, output_depth, input_depth); + + int64_t ih0 = start_index(oh, output_height, input_height); + int64_t ih1 = end_index(oh, output_height, input_height); + + int64_t iw0 = start_index(ow, output_width, input_width); + int64_t iw1 = end_index(ow, output_width, input_width); + + BFloat16* out = output_data + i * channels; + int64_t* ind = indices_data + i * channels; + + // Pass I: init out lane + iVec index0_ivec = iVec(id0 * input_height * input_width + ih0 * input_width + iw0); + fVec max_fvec = fVec(-std::numeric_limits::infinity()); + int64_t d1 = 0; + for (; d1 < len; d1 += fVec::size()) { + index0_ivec.store(index_buffer.get() + d1); + max_fvec.store(max + d1); + } + for (; d1 < size; d1++) { + ind[d1] = id0 * input_height * input_width + ih0 * input_width + iw0; + max[d1] = -std::numeric_limits::infinity(); + } + // Pass II: compute local max + for (int64_t id = id0; id < id1; id ++) { + for (int64_t ih = ih0; ih < ih1; ih ++) { + for (int64_t iw = iw0; iw < iw1; iw ++) { + const BFloat16* in = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += bVec::size()) { + iVec index_ivec = iVec(id * input_height * input_width + ih * input_width + iw); + bVec val_bvec = bVec::loadu(in + d2); + auto [val_fvec0, val_fvec1] = convert_bfloat16_float(val_bvec); + + iVec maxindex_ivec0 = iVec::loadu(index_buffer.get() + d2); + iVec maxindex_ivec1 = iVec::loadu(index_buffer.get() + d2 + iVec::size()); + fVec maxval_fvec0 = fVec::loadu(max + d2); + fVec maxval_fvec1 = fVec::loadu(max + d2 + fVec::size()); + + // true = all ones, false = all zeros + fVec mask0 = (val_fvec0 > maxval_fvec0) | val_fvec0.isnan(); + fVec mask1 = (val_fvec1 > maxval_fvec1) | val_fvec1.isnan(); + iVec imask0 = vec::cast(mask0); + iVec imask1 = vec::cast(mask1); + + fVec max_fvec0 = fVec::blendv(maxval_fvec0, val_fvec0, mask0); + fVec max_fvec1 = fVec::blendv(maxval_fvec1, val_fvec1, mask1); + iVec ind_ivec0 = iVec::blendv(maxindex_ivec0, index_ivec, imask0); + iVec ind_ivec1 = iVec::blendv(maxindex_ivec1, index_ivec, imask1); + + max_fvec0.store(max + d2); + max_fvec1.store(max + d2 + fVec::size()); + ind_ivec0.store(index_buffer.get() + d2); + ind_ivec1.store(index_buffer.get() + d2 + iVec::size()); + } + for (; d2 < size; d2++) { + int64_t index = id * input_height * input_width + ih * input_width + iw; + float val = float(in[d2]); + int64_t maxindex = ind[d2]; + float maxval = max[d2]; + + bool mask = (val > maxval) || std::isnan(val); + max[d2] = mask ? val : maxval; + ind[d2] = mask ? index : maxindex; + } + } + } + } + // Pass III: convert max values from float to bfloat16 + int64_t d3 = 0; + for (; d3 < len; d3 += bVec::size()) { + fVec max_fvec0 = fVec::loadu(max + d3); + fVec max_fvec1 = fVec::loadu(max + d3 + fVec::size()); + bVec max_bvec = convert_float_bfloat16(max_fvec0, max_fvec1); + max_bvec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = BFloat16(max[d3]); + } + // convert indice data type + vec::convert(index_buffer.get(), ind, len); + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } + if (!indices_.is_contiguous(memory_format)) { + indices_.copy_(indices); + } +} + +template +void cpu_adaptive_max_pool3d_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + const Tensor& indices_) { + auto grad_output = grad_output_.contiguous(); + auto indices = indices_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.data_ptr(); + auto indices_data = indices.data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t ndim = grad_output.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + int64_t input_depth = grad_input.size(-3); + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_depth = grad_output.size(-3); + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_depth * input_height * input_width; + scalar_t* grad_output_ptr = grad_output_data + c * output_depth * output_height * output_width; + int64_t* indices_ptr = indices_data + c * output_depth * output_height * output_width; + + for (const auto od : c10::irange(output_depth)) { + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + // retrieve position of max + int64_t index = od * output_height * output_width + oh * output_width + ow; + int64_t maxindex = indices_ptr[index]; + + // update gradient + grad_input_ptr[maxindex] += grad_output_ptr[index]; + } + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_adaptive_max_pool3d_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + const Tensor& indices_) { + TORCH_CHECK(grad_output_.ndimension() == 5, + "3d adaptive max pooling backward with channels last format supports tensors with 5 dims."); + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_depth = grad_input.size(2); + int64_t input_height = grad_input.size(3); + int64_t input_width = grad_input.size(4); + int64_t output_depth = grad_output.size(2); + int64_t output_height = grad_output.size(3); + int64_t output_width = grad_output.size(4); + + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_depth * input_height * input_width * channels; + scalar_t* grad_output_ptr = grad_output_data + n * output_depth * output_height * output_width * channels; + int64_t* indices_ptr = indices_data + n * output_depth * output_height * output_width * channels; + + for (const auto od : c10::irange(output_depth)) { + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + scalar_t* gout = grad_output_ptr + od * output_height * output_width * channels + oh * output_width * channels + ow * channels; + int64_t* ind = indices_ptr + od * output_height * output_width * channels + oh * output_width * channels + ow * channels; + // TODO: gcc vectorization + for (const auto c : c10::irange(channels)) { + int64_t maxindex = ind[c]; + grad_input_ptr[maxindex * channels + c] += gout[c]; + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void adaptive_max_pool3d_kernel_impl( + const Tensor& output, + const Tensor& indices, + const Tensor& input, + IntArrayRef output_size) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_max_pool3d", [&] { + using param_t = at::opmath_type; + cpu_adaptive_max_pool3d(output, indices, input, output_size); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "adaptive_max_pool3d_channels_last", [&]{ + cpu_adaptive_max_pool3d_channels_last(output, indices, input, output_size); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void adaptive_max_pool3d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + const Tensor& indices) { + // can't use grad_output memory format to switch here since grad_output might be NC11 + switch (grad_input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_max_pool3d_backward", [&] { + cpu_adaptive_max_pool3d_backward(grad_input, grad_output, indices); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "adaptive_max_pool3d_backward_channels_last", [&]{ + cpu_adaptive_max_pool3d_backward_channels_last(grad_input, grad_output, indices); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(adaptive_max_pool2d_kernel, &adaptive_max_pool2d_kernel_impl) +REGISTER_DISPATCH(adaptive_max_pool2d_backward_kernel, &adaptive_max_pool2d_backward_kernel_impl) +REGISTER_DISPATCH(adaptive_max_pool3d_kernel, &adaptive_max_pool3d_kernel_impl) +REGISTER_DISPATCH(adaptive_max_pool3d_backward_kernel, &adaptive_max_pool3d_backward_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AmpGradScalerKernels.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AmpGradScalerKernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a18429ed61d0abd4f07b1aabf7d3e382ff04016b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AmpGradScalerKernels.cpp @@ -0,0 +1,198 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { +// Follow the implementations of CUDA. +// Multiplies each tensor in scaled_grads by inv_scale in-place. +// If any element of any tensor in scaled_grads is inf or NaN, sets found_inf +// to 1.0. +// +// Args: +// scaled_grads: A TensorList of scaled gradient tensors. May contain infs or +// NaNs. found_inf: A single-element float tensor to which 1.0 will be written +// if any gradient contain infs/nans. +// Pre-zeroing found_inf, if appropriate, is the responsibility of +// the caller. +// inv_scale: The inverse of the scale factor by which scaled_grads are +// currently multiplied. +void _amp_foreach_non_finite_check_and_unscale_cpu_kernel( + TensorList scaled_grads, + at::Tensor& found_inf, + const at::Tensor& inv_scale) { + if (scaled_grads.empty()) { + return; + } + + TORCH_CHECK(inv_scale.is_cpu(), "inv_scale must be a CPU tensor."); + TORCH_CHECK(found_inf.is_cpu(), "found_inf must be a CPU tensor."); + TORCH_CHECK(inv_scale.numel() == 1, "inv_scale must be a 1-element tensor."); + TORCH_CHECK(found_inf.numel() == 1, "found_inf must be a 1-element tensor."); + TORCH_CHECK( + inv_scale.scalar_type() == at::ScalarType::Float, + "inv_scale must be a float tensor."); + TORCH_CHECK( + found_inf.scalar_type() == at::ScalarType::Float, + "found_inf must be a float tensor."); + + // Ensures client code (GradScaler) filtered scaled_grads by dtype. + at::native::check_foreach_api_restrictions(scaled_grads); + for (const at::Tensor& t : scaled_grads) { + TORCH_CHECK(t.is_cpu(), "one of scaled_grads was not a CPU tensor."); + TORCH_CHECK( + t.layout() == at::kStrided, + "one of scaled_grads was not a strided tensor."); + auto iter = at::TensorIterator::unary_op( + const_cast(t), t); + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES( + iter.dtype(), + "_amp_foreach_non_finite_check_and_unscale_cpu", + [&iter, &found_inf, &inv_scale] { + auto* found_inf_ptr = found_inf.data_ptr(); + const auto* inv_scale_ptr = inv_scale.const_data_ptr(); + + using opmath_t = at::opmath_type; + + at::native::cpu_kernel_vec( + iter, + [found_inf_ptr, inv_scale_ptr](scalar_t val_in) -> scalar_t { + auto val = static_cast(val_in); + if (!std::isfinite(val)) { + *found_inf_ptr = 1.f; + } + // Every thread accesses inv_scale, but it will hit in cache. + const auto inv_scale_val = *inv_scale_ptr; + return static_cast( + inv_scale_val == 1.f ? val : val * inv_scale_val); + }, + [found_inf_ptr, inv_scale_ptr](Vectorized val_vec) -> Vectorized{ + auto [val_vec0, val_vec1] = convert_to_float(val_vec); + if (val_vec0.has_inf_nan() || val_vec1.has_inf_nan()) { + *found_inf_ptr = 1.f; + } + // Every thread accesses inv_scale, but it will hit in cache. + const auto inv_scale_val = *inv_scale_ptr; + val_vec0 = inv_scale_val == 1.f ? val_vec0 : val_vec0 * Vectorized(inv_scale_val); + val_vec1 = inv_scale_val == 1.f ? val_vec1 : val_vec1 * Vectorized(inv_scale_val); + return convert_from_float(val_vec0, val_vec1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES( + iter.dtype(), + "_amp_foreach_non_finite_check_and_unscale_cpu", + [&iter, &found_inf, &inv_scale] { + auto* found_inf_ptr = found_inf.data_ptr(); + const auto* inv_scale_ptr = inv_scale.const_data_ptr(); + at::native::cpu_kernel_vec( + iter, + [found_inf_ptr, inv_scale_ptr](scalar_t val_in) -> scalar_t { + if (!std::isfinite(val_in)) { + *found_inf_ptr = 1.f; + } + // Every thread accesses inv_scale, but it will hit in cache. + const auto inv_scale_val = *inv_scale_ptr; + return static_cast( + inv_scale_val == 1.f ? val_in : val_in * inv_scale_val); + }, + [found_inf_ptr, inv_scale_ptr](Vectorized val_vec) -> Vectorized{ + if (val_vec.has_inf_nan()) { + *found_inf_ptr = 1.f; + } + // Every thread accesses inv_scale, but it will hit in cache. + const auto inv_scale_val = *inv_scale_ptr; + return inv_scale_val == 1.f ? val_vec : val_vec * Vectorized(inv_scale_val); + }); + }); + } + } +} + +// _amp_update_scale_cpu updates the scale tensor in place. +// +// Args: +// current_scale: A one-element float tensor containing the scale value. +// growth_tracker: A one-element IntTensor containing the number of recent +// consecutive unskipped steps. found_inf: A one-element float tensor. If > 0, +// indicates that infs/nans were found by the relevant +// prior _amp_non_finite_check_and_unscale_cpu call, and 0 if no +// infs/nans were found. +// growth_factor: Multiplier if no infs/NaNs were found (typically slightly > +// 1). backoff_factor: Multiplier if infs/NaNs were found (typically 0.5). +// growth_interval: Number of consecutive unskipped steps that must occur for +// current_scale to be multiplied by +// growth_factor. +// +// Returns: +// current_scale +at::Tensor& _amp_update_scale_cpu_kernel( + at::Tensor& current_scale, + at::Tensor& growth_tracker, + const at::Tensor& found_inf, + double growth_factor, + double backoff_factor, + int64_t growth_interval) { + TORCH_CHECK(growth_tracker.is_cpu(), "growth_tracker must be a CPU tensor."); + TORCH_CHECK(current_scale.is_cpu(), "current_scale must be a CPU tensor."); + TORCH_CHECK(found_inf.is_cpu(), "found_inf must be a CPU tensor."); + TORCH_CHECK( + growth_tracker.numel() == 1, + "growth_tracker must be a 1-element tensor."); + TORCH_CHECK( + current_scale.numel() == 1, "current_scale must be a 1-element tensor."); + TORCH_CHECK(found_inf.numel() == 1, "found_inf must be a 1-element tensor."); + TORCH_CHECK( + growth_tracker.scalar_type() == at::ScalarType::Int, + "growth_tracker must be an int tensor."); + TORCH_CHECK( + current_scale.scalar_type() == at::ScalarType::Float, + "current_scale must be a float tensor."); + TORCH_CHECK( + found_inf.scalar_type() == at::ScalarType::Float, + "found_inf must be a float tensor."); + + float* current_scale_ptr = current_scale.data_ptr(); + int* growth_tracker_ptr = growth_tracker.data_ptr(); + const float* found_inf_ptr = found_inf.const_data_ptr(); + + if (*found_inf_ptr) { + *current_scale_ptr = (*current_scale_ptr) * backoff_factor; + *growth_tracker_ptr = 0; + } else { + // Entering this branch means we just carried out a successful step, + // so growth_tracker is incremented before comparing to growth_interval. + auto successful = (*growth_tracker_ptr) + 1; + if (successful == growth_interval) { + auto new_scale = static_cast((*current_scale_ptr) * growth_factor); + // Do not grow the scale past fp32 bounds to inf. + if (std::isfinite(new_scale)) { + *current_scale_ptr = new_scale; + } + *growth_tracker_ptr = 0; + } else { + *growth_tracker_ptr = successful; + } + } + + return current_scale; +} + +} // namespace + +REGISTER_DISPATCH(_amp_foreach_non_finite_check_and_unscale_cpu_stub, &_amp_foreach_non_finite_check_and_unscale_cpu_kernel) +REGISTER_DISPATCH(_amp_update_scale_cpu_stub, &_amp_update_scale_cpu_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AtomicAddFloat.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AtomicAddFloat.h new file mode 100644 index 0000000000000000000000000000000000000000..b0e88d392f4a67c6c8cdd7ec5dbf02e8f452392e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AtomicAddFloat.h @@ -0,0 +1,31 @@ +#ifndef ATOMIC_ADD_FLOAT +#define ATOMIC_ADD_FLOAT + +#if (defined(__x86_64__) || defined(__i386__) || defined(__aarch64__)) +#include +#else +#define _mm_pause() +#endif + +#include + +static inline void cpu_atomic_add_float(float* dst, float fvalue) +{ +#if defined(__cpp_lib_atomic_ref) && __cpp_lib_atomic_ref >= 201806L + std::atomic_ref atomic_dst(*dst); +#else + auto& atomic_dst = *reinterpret_cast*>(dst); +#endif + float old_value = atomic_dst.load(); + float new_value = old_value + fvalue; + while (!atomic_dst.compare_exchange_weak(old_value, new_value)) { +#ifdef __aarch64__ + __asm__ __volatile__("yield;" : : : "memory"); +#else + _mm_pause(); +#endif + new_value = old_value + fvalue; + } +} + +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AvgPoolKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AvgPoolKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0b7927161f498be93962fa846ce4b1723e8fa25 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/AvgPoolKernel.cpp @@ -0,0 +1,1138 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void cpu_avg_pool2d( + const Tensor& output_, + const Tensor& input_, + int64_t kW, int64_t kH, + int64_t dW, int64_t dH, + int64_t padW, int64_t padH, + bool count_include_pad, + std::optional divisor_override) { + using acc_t = at::opmath_type; + + auto input = input_.contiguous(); + auto output = output_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t numel = output.numel(); + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? input.size(0) : input.size(0) * input.size(1); + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_height = output.size(-2); + int64_t output_width = output.size(-1); + + // parallel on dim N, C, H, W + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t c = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, c, channels, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + output_data[i] = static_cast(0); + + // local pointers + const scalar_t* input_ptr = input_data + c * input_height * input_width; + + // compute the mean of the input image... + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (ih1 - ih0) * (iw1 - iw0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + if (ih0 >= ih1 || iw0 >= iw1) { + // move on to next output index + data_index_step(c, channels, oh, output_height, ow, output_width); + continue; + } + + acc_t sum = 0; + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (ih1 - ih0) * (iw1 - iw0); + } + } + + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + sum += input_ptr[ih * input_width + iw]; + } + } + output_data[i] += scalar_t(sum / divide_factor); + + // move on to next output index + data_index_step(c, channels, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } +} + +template ::value, int> = 0> +void cpu_avg_pool2d_channels_last( + const Tensor& output_, + const Tensor& input_, + int64_t kW, int64_t kH, + int64_t dW, int64_t dH, + int64_t padW, int64_t padH, + bool count_include_pad, + std::optional divisor_override) { + TORCH_CHECK(input_.ndimension() == 4, + "2d average pooling with channels last format supports tensors with 4 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output.size(2); + int64_t output_width = output.size(3); + + using Vec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + for (const auto i : c10::irange(begin, end)) { + // compute the mean of the input image... + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (ih1 - ih0) * (iw1 - iw0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (ih1 - ih0) * (iw1 - iw0); + } + } + + scalar_t* out = output_data + i * channels; + + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < len; d1 += Vec::size()) { + Vec out_vec = Vec(scalar_t(0)); + out_vec.store(out + d1); + } + for (; d1 < size; d1++) { + out[d1] = scalar_t(0); + } + + if (ih0 >= ih1 || iw0 >= iw1) { + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + continue; + } + + // Pass II: compute local sum + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + const scalar_t* in = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d2) + Vec::loadu(in + d2); + out_vec.store(out + d2); + } + for (; d2 < size; d2++) { + out[d2] += in[d2]; + } + } + } + + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < len; d3 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d3) / Vec(scalar_t(divide_factor)); + out_vec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = out[d3] / divide_factor; + } + + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template ::value, int> = 0> +void cpu_avg_pool2d_channels_last( + const Tensor& output_, + const Tensor& input_, + int64_t kW, int64_t kH, + int64_t dW, int64_t dH, + int64_t padW, int64_t padH, + bool count_include_pad, + std::optional divisor_override) { + TORCH_CHECK(input_.ndimension() == 4, + "2d average pooling with channels last format supports tensors with 4 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output.size(2); + int64_t output_width = output.size(3); + + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + // temp buffer for sum, use float as accumulation type + // can't reuse output buffer to store sum since it is BFloat16/Half + auto sum_arr = std::make_unique(channels); + float* sum = sum_arr.get(); + + int64_t size = channels; + for (const auto i : c10::irange(begin, end)) { + // compute the mean of the input image... + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (ih1 - ih0) * (iw1 - iw0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (ih1 - ih0) * (iw1 - iw0); + } + } + + scalar_t* out = output_data + i * channels; + + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < size - (size % fVec::size()); d1 += fVec::size()) { + fVec sum_fvec = fVec(float(0)); + sum_fvec.store(sum + d1); + } + for (; d1 < size; d1++) { + sum[d1] = float(0); + } + + if (ih0 >= ih1 || iw0 >= iw1) { + // since we are not directly using output as the accumulation buffer, + // in case the kernel window is out of range, need to zero the output buffer here. + for (int64_t k = 0; k < size; k++) { + out[k] = 0; + } + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + continue; + } + + // Pass II: compute local sum + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + const scalar_t* in = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < size - (size % bVec::size()); d2 += bVec::size()) { + bVec data_bvec = bVec::loadu(in + d2); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + + fVec sum_fvec0 = fVec::loadu(sum + d2) + data_fvec0; + fVec sum_fvec1 = fVec::loadu(sum + d2 + fVec::size()) + data_fvec1; + sum_fvec0.store(sum + d2); + sum_fvec1.store(sum + d2 + fVec::size()); + } + for (; d2 < size; d2++) { + sum[d2] += float(in[d2]); + } + } + } + + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < size - (size % bVec::size()); d3 += bVec::size()) { + fVec out_fvec0 = fVec::loadu(sum + d3) / fVec(float(divide_factor)); + fVec out_fvec1 = fVec::loadu(sum + d3 + fVec::size()) / fVec(float(divide_factor)); + + bVec out_bvec = convert_from_float(out_fvec0, out_fvec1); + out_bvec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = scalar_t(sum[d3] / divide_factor); + } + + // move on to next output index + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +void cpu_avg_pool2d_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + int kW, int kH, + int dW, int dH, + int padW, int padH, + bool count_include_pad, + std::optional divisor_override) { + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t ndim = grad_output.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 3 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_height * input_width; + const scalar_t* grad_output_ptr = grad_output_data + c * output_height * output_width; + + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (ih1 - ih0) * (iw1 - iw0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (ih1 - ih0) * (iw1 - iw0); + } + } + + scalar_t grad_delta = grad_output_ptr[oh * output_width + ow] / divide_factor; + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + grad_input_ptr[ih * input_width + iw] += grad_delta; + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_avg_pool2d_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + int kW, int kH, + int dW, int dH, + int padW, int padH, + bool count_include_pad, + std::optional divisor_override) { + auto memory_format = at::MemoryFormat::ChannelsLast; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.const_data_ptr(); + + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_height = grad_input.size(2); + int64_t input_width = grad_input.size(3); + int64_t output_height = grad_output.size(2); + int64_t output_width = grad_output.size(3); + + using Vec = vec::Vectorized; + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_height * input_width * channels; + const scalar_t* grad_output_ptr = grad_output_data + n * output_height * output_width * channels; + + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (ih1 - ih0) * (iw1 - iw0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (ih1 - ih0) * (iw1 - iw0); + } + } + + const scalar_t* gout = grad_output_ptr + oh * output_width * channels + ow * channels; + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + scalar_t* gin = grad_input_ptr + ih * input_width * channels + iw * channels; + + int64_t d = 0; + for (; d < len; d += Vec::size()) { + Vec gin_vec = Vec::loadu(gin + d) + Vec::loadu(gout + d) / Vec(scalar_t(divide_factor)); + gin_vec.store(gin + d); + } + for (; d < size; d++) { + gin[d] += gout[d] / divide_factor; + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void avg_pool2d_kernel_impl( + const Tensor& output, + const Tensor& input, + int64_t kW, int64_t kH, + int64_t dW, int64_t dH, + int64_t padW, int64_t padH, + bool count_include_pad, + std::optional divisor_override) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, input.scalar_type(), "avg_pool2d", [&] { + cpu_avg_pool2d(output, input, kW, kH, dW, dH, padW, padH, count_include_pad, divisor_override); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, input.scalar_type(), "avg_pool2d_channels_last", [&] { + cpu_avg_pool2d_channels_last(output, input, kW, kH, dW, dH, padW, padH, count_include_pad, divisor_override); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void avg_pool2d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + int kW, int kH, + int dW, int dH, + int padW, int padH, + bool count_include_pad, + std::optional divisor_override) { + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, grad_output.scalar_type(), "avg_pool2d_backward", [&] { + cpu_avg_pool2d_backward(grad_input, grad_output, kW, kH, dW, dH, padW, padH, count_include_pad, divisor_override); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, grad_output.scalar_type(), "avg_pool2d_backward_channels_last", [&] { + cpu_avg_pool2d_backward_channels_last(grad_input, grad_output, kW, kH, dW, dH, padW, padH, count_include_pad, divisor_override); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + + +template +void cpu_avg_pool3d( + const Tensor& output_, + const Tensor& input_, + int64_t kW, int64_t kH, int64_t kD, + int64_t dW, int64_t dH, int64_t dD, + int64_t padW, int64_t padH, int64_t padD, + bool count_include_pad, + std::optional divisor_override) { + using acc_t = at::opmath_type; + + auto input = input_.contiguous(); + auto output = output_.contiguous(); + + auto input_data = input.data_ptr(); + auto output_data = output.data_ptr(); + + int64_t numel = output.numel(); + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 4 ? input.size(0) : input.size(0) * input.size(1); + int64_t input_depth = input.size(-3); + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_depth = output.size(-3); + int64_t output_height = output.size(-2); + int64_t output_width = output.size(-1); + + // parallel on dim N, C, D, H, W + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t c = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, c, channels, od, output_depth, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + output_data[i] = static_cast(0); + + // local pointers + scalar_t* input_ptr = input_data + c * input_depth * input_height * input_width; + + // compute the mean of the input image... + int64_t id0 = od * dD - padD; + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t id1 = std::min(id0 + kD, input_depth + padD); + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + id0 = std::max(id0, (int64_t) 0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + id1 = std::min(id1, input_depth); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + if (id0 >= id1 || ih0 >= ih1 || iw0 >= iw1) { + // move on to next output index + data_index_step(c, channels, od, output_depth, oh, output_height, ow, output_width); + continue; + } + + acc_t sum = 0; + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + } + } + + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + sum += input_ptr[id * input_height * input_width + ih * input_width + iw]; + } + } + } + output_data[i] += scalar_t(sum / divide_factor); + + // move on to next output index + data_index_step(c, channels, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } +} + +template ::value, int> = 0> +void cpu_avg_pool3d_channels_last( + const Tensor& output_, + const Tensor& input_, + int64_t kW, int64_t kH, int64_t kD, + int64_t dW, int64_t dH, int64_t dD, + int64_t padW, int64_t padH, int64_t padD, + bool count_include_pad, + std::optional divisor_override) { + TORCH_CHECK(input_.ndimension() == 5, + "3d average pooling with channels last format supports tensors with 5 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = input.size(2); + int64_t input_height = input.size(3); + int64_t input_width = input.size(4); + int64_t output_depth = output.size(2); + int64_t output_height = output.size(3); + int64_t output_width = output.size(4); + + using Vec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + for (const auto i : c10::irange(begin, end)) { + // compute the mean of the input image... + int64_t id0 = od * dD - padD; + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t id1 = std::min(id0 + kD, input_depth + padD); + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + id0 = std::max(id0, (int64_t) 0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + id1 = std::min(id1, input_depth); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + } + } + + scalar_t* out = output_data + i * channels; + + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < len; d1 += Vec::size()) { + Vec out_vec = Vec(scalar_t(0)); + out_vec.store(out + d1); + } + for (; d1 < size; d1++) { + out[d1] = scalar_t(0); + } + + if (id0 >= id1 || ih0 >= ih1 || iw0 >= iw1) { + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + continue; + } + + // Pass II: compute local sum + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + scalar_t* in = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d2) + Vec::loadu(in + d2); + out_vec.store(out + d2); + } + for (; d2 < size; d2++) { + out[d2] += in[d2]; + } + } + } + } + + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < len; d3 += Vec::size()) { + Vec out_vec = Vec::loadu(out + d3) / Vec(scalar_t(divide_factor)); + out_vec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = out[d3] / divide_factor; + } + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template ::value, int> = 0> +void cpu_avg_pool3d_channels_last( + const Tensor& output_, + const Tensor& input_, + int64_t kW, int64_t kH, int64_t kD, + int64_t dW, int64_t dH, int64_t dD, + int64_t padW, int64_t padH, int64_t padD, + bool count_include_pad, + std::optional divisor_override) { + TORCH_CHECK(input_.ndimension() == 5, + "3d average pooling with channels last format supports tensors with 5 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = input.size(2); + int64_t input_height = input.size(3); + int64_t input_width = input.size(4); + int64_t output_depth = output.size(2); + int64_t output_height = output.size(3); + int64_t output_width = output.size(4); + + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + // parallel on dim N, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + // temp buffer for sum, use float as accumulation type + // can't reuse output buffer to store sum since it is BFloat16 + auto sum_arr = std::make_unique(channels); + float* sum = sum_arr.get(); + + int64_t size = channels; + for (const auto i : c10::irange(begin, end)) { + // compute the mean of the input image... + int64_t id0 = od * dD - padD; + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t id1 = std::min(id0 + kD, input_depth + padD); + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + id0 = std::max(id0, (int64_t) 0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + id1 = std::min(id1, input_depth); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + } + } + + BFloat16* out = output_data + i * channels; + + // Pass I: zero the out lane + int64_t d1 = 0; + for (; d1 < size - (size % fVec::size()); d1 += fVec::size()) { + fVec sum_fvec = fVec(float(0)); + sum_fvec.store(sum + d1); + } + for (; d1 < size; d1++) { + sum[d1] = float(0); + } + + if (id0 >= id1 || ih0 >= ih1 || iw0 >= iw1) { + // since we are not directly using output as the accumulation buffer, + // in case the kernel window is out of range, need to zero the output buffer here. + for (int64_t k = 0; k < size; k++) { + out[k] = 0; + } + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + continue; + } + + // Pass II: compute local sum + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + BFloat16* in = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + ih * input_width * channels + iw * channels; + + int64_t d2 = 0; + for (; d2 < size - (size % bVec::size()); d2 += bVec::size()) { + bVec data_bvec = bVec::loadu(in + d2); + auto [data_fvec0, data_fvec1] = convert_bfloat16_float(data_bvec); + + fVec sum_fvec0 = fVec::loadu(sum + d2) + data_fvec0; + fVec sum_fvec1 = fVec::loadu(sum + d2 + fVec::size()) + data_fvec1; + sum_fvec0.store(sum + d2); + sum_fvec1.store(sum + d2 + fVec::size()); + } + for (; d2 < size; d2++) { + sum[d2] += float(in[d2]); + } + } + } + } + + // Pass III: compute local average + int64_t d3 = 0; + for (; d3 < size - (size % bVec::size()); d3 += bVec::size()) { + fVec out_fvec0 = fVec::loadu(sum + d3) / fVec(float(divide_factor)); + fVec out_fvec1 = fVec::loadu(sum + d3 + fVec::size()) / fVec(float(divide_factor)); + + bVec out_bvec = convert_float_bfloat16(out_fvec0, out_fvec1); + out_bvec.store(out + d3); + } + for (; d3 < size; d3++) { + out[d3] = BFloat16(sum[d3] / divide_factor); + } + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +void cpu_avg_pool3d_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + int kW, int kH, int kD, + int dW, int dH, int dD, + int padW, int padH, int padD, + bool count_include_pad, + std::optional divisor_override) { + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t ndim = grad_output.ndimension(); + // treat batch size and channels as one dimension + int64_t channels = ndim == 4 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + int64_t input_depth = grad_input.size(-3); + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_depth = grad_output.size(-3); + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_depth * input_height * input_width; + scalar_t* grad_output_ptr = grad_output_data + c * output_depth * output_height * output_width; + + for (const auto od : c10::irange(output_depth)) { + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + int64_t id0 = od * dD - padD; + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t id1 = std::min(id0 + kD, input_depth + padD); + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + id0 = std::max(id0, (int64_t) 0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + } + } + + scalar_t grad_delta = grad_output_ptr[od * output_height * output_width + oh * output_width + ow] / divide_factor; + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + grad_input_ptr[id * input_height * input_width + ih * input_width + iw] += grad_delta; + } + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_avg_pool3d_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + int kW, int kH, int kD, + int dW, int dH, int dD, + int padW, int padH, int padD, + bool count_include_pad, + std::optional divisor_override) { + auto memory_format = at::MemoryFormat::ChannelsLast3d; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.data_ptr(); + + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_depth = grad_input.size(2); + int64_t input_height = grad_input.size(3); + int64_t input_width = grad_input.size(4); + int64_t output_depth = grad_output.size(2); + int64_t output_height = grad_output.size(3); + int64_t output_width = grad_output.size(4); + + using Vec = vec::Vectorized; + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_depth * input_height * input_width * channels; + scalar_t* grad_output_ptr = grad_output_data + n * output_depth * output_height * output_width * channels; + + for (const auto od : c10::irange(output_depth)) { + for (const auto oh : c10::irange(output_height)) { + for (const auto ow : c10::irange(output_width)) { + int64_t id0 = od * dD - padD; + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t id1 = std::min(id0 + kD, input_depth + padD); + int64_t ih1 = std::min(ih0 + kH, input_height + padH); + int64_t iw1 = std::min(iw0 + kW, input_width + padW); + int64_t pool_size = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + id0 = std::max(id0, (int64_t) 0); + ih0 = std::max(ih0, (int64_t) 0); + iw0 = std::max(iw0, (int64_t) 0); + id1 = std::min(id1, input_depth); + ih1 = std::min(ih1, input_height); + iw1 = std::min(iw1, input_width); + + int64_t divide_factor = 0; + if (divisor_override.has_value()) { + divide_factor = divisor_override.value(); + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (id1 - id0) * (ih1 - ih0) * (iw1 - iw0); + } + } + + scalar_t* gout = grad_output_ptr + od * output_height * output_width * channels + oh * output_width * channels + ow * channels; + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + for (const auto id : c10::irange(id0, id1)) { + for (const auto ih : c10::irange(ih0, ih1)) { + for (const auto iw : c10::irange(iw0, iw1)) { + scalar_t* gin = grad_input_ptr + id * input_height * input_width * channels + ih * input_width * channels + iw * channels; + + int64_t d = 0; + for (; d < len; d += Vec::size()) { + Vec gin_vec = Vec::loadu(gin + d) + Vec::loadu(gout + d) / Vec(scalar_t(divide_factor)); + gin_vec.store(gin + d); + } + for (; d < size; d++) { + gin[d] += gout[d] / divide_factor; + } + } + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + + + +void avg_pool3d_kernel_impl( + const Tensor& output, + const Tensor& input, + int64_t kW, int64_t kH, int64_t kD, + int64_t dW, int64_t dH, int64_t dD, + int64_t padW, int64_t padH, int64_t padD, + bool count_include_pad, + std::optional divisor_override) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, input.scalar_type(), "avg_pool3d", [&] { + cpu_avg_pool3d(output, input, kW, kH, kD, dW, dH, dD, padW, padH, padD, count_include_pad, divisor_override); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, input.scalar_type(), "avg_pool3d_channels_last", [&] { + cpu_avg_pool3d_channels_last(output, input, kW, kH, kD, dW, dH, dD, padW, padH, padD, count_include_pad, divisor_override); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + + +void avg_pool3d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + int kW, int kH, int kD, + int dW, int dH, int dD, + int padW, int padH, int padD, + bool count_include_pad, + std::optional divisor_override) { + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, grad_output.scalar_type(), "avg_pool3d_backward", [&] { + cpu_avg_pool3d_backward(grad_input, grad_output, kW, kH, kD, dW, dH, dD, padW, padH, padD, count_include_pad, divisor_override); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND3(kLong, kBFloat16, kHalf, grad_output.scalar_type(), "avg_pool3d_backward_channels_last", [&] { + cpu_avg_pool3d_backward_channels_last(grad_input, grad_output, kW, kH, kD, dW, dH, dD, padW, padH, padD, count_include_pad, divisor_override); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + + +} // anonymous namespace + +REGISTER_DISPATCH(avg_pool2d_kernel, &avg_pool2d_kernel_impl) +REGISTER_DISPATCH(avg_pool2d_backward_kernel, &avg_pool2d_backward_kernel_impl) +REGISTER_DISPATCH(avg_pool3d_kernel, &avg_pool3d_kernel_impl) +REGISTER_DISPATCH(avg_pool3d_backward_kernel, &avg_pool3d_backward_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/BinaryOpsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/BinaryOpsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9099decaaecf903b5d8ef7893988eaa101cac420 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/BinaryOpsKernel.cpp @@ -0,0 +1,1516 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +using namespace vec; + +template < + typename scalar_t, + typename Op, + typename opmath_t = at::opmath_type, + typename std::enable_if_t, int> = 0> +inline Vectorized binary_op_scalar( + const Vectorized& a, + opmath_t b, + const Op& op) { + Vectorized vec_b(b); + auto [a0, a1] = convert_to_float(a); + return convert_from_float(op(a0, vec_b), op(a1, vec_b)); +} + +void add_clamp_kernel( + TensorIterator& iter, + const Scalar& alpha_scalar, + const Scalar& min_val, + const Scalar& max_val) { + AT_DISPATCH_ALL_TYPES(iter.dtype(), "add_clamp_cpu", [&]() { + auto alpha = alpha_scalar.to(); + auto alpha_vec = Vectorized(alpha); + auto min_scalar = min_val.to(); + auto min_vec = Vectorized(min_scalar); + auto max_scalar = max_val.to(); + auto max_vec = Vectorized(max_scalar); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) __ubsan_ignore_undefined__ -> scalar_t { + return std::min( + max_scalar, + std::max(min_scalar, static_cast(a + alpha * b))); + }, + [=](Vectorized a, Vectorized b) + __ubsan_ignore_undefined__ { + auto add_clamp_res = vec::fmadd(b, alpha_vec, a); + add_clamp_res = vec::clamp_min(add_clamp_res, min_vec); + add_clamp_res = vec::clamp_max(add_clamp_res, max_vec); + return add_clamp_res; + }); + }); +} + +void atan2_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.dtype(), "atan2_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return std::atan2(a, b); + }, + [=](Vectorized a, Vectorized b) { + return a.atan2(b); + }); + }); +} + +#if !defined(C10_MOBILE) +#define _AT_DISPATCH_INTEGRAL_TYPES_V2(TYPE, NAME, ...) \ + AT_DISPATCH_V2( \ + TYPE, \ + NAME, \ + AT_WRAP(__VA_ARGS__), \ + AT_EXPAND(AT_INTEGRAL_TYPES_V2)) +#define _AT_DISPATCH_ALL_TYPES_AND_BOOL(TYPE, NAME, ...) \ + AT_DISPATCH_V2( \ + TYPE, \ + NAME, \ + AT_WRAP(__VA_ARGS__), \ + kComplexHalf, \ + kHalf, \ + kBool, \ + kBFloat16, \ + AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)) +#define _AT_DISPATCH_ALL_TYPES_NO_BOOL(TYPE, NAME, ...) \ + AT_DISPATCH_V2( \ + TYPE, \ + NAME, \ + AT_WRAP(__VA_ARGS__), \ + kComplexHalf, \ + kHalf, \ + kBFloat16, \ + AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)) +#define _AT_DISPATCH_MUL_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_V2(TYPE, NAME, AT_WRAP(__VA_ARGS__), \ + kHalf, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)) +#else +#define _AT_DISPATCH_INTEGRAL_TYPES_V2(TYPE, NAME, ...) \ + AT_DISPATCH_INTEGRAL_TYPES(TYPE, NAME, __VA_ARGS__) +#define _AT_DISPATCH_ALL_TYPES_AND_BOOL(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND4( \ + kComplexHalf, kHalf, kBool, kBFloat16, TYPE, NAME, __VA_ARGS__) +#define _AT_DISPATCH_ALL_TYPES_NO_BOOL(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( \ + kComplexHalf, kHalf, kBFloat16, TYPE, NAME, __VA_ARGS__) +#define _AT_DISPATCH_MUL_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( \ + kHalf, kBFloat16, TYPE, NAME, __VA_ARGS__) +#endif + +void mul_kernel(TensorIteratorBase& iter) { + auto dtype = iter.common_dtype(); + if (dtype == ScalarType::Bool) { + cpu_kernel(iter, [=](bool a, bool b) -> bool { return a && b; }); + } else if (dtype == kComplexHalf) { + cpu_kernel( + iter, + [=](c10::complex a, + c10::complex b) -> c10::complex { + using comp_t = c10::complex; + return comp_t{a} * comp_t{b}; + }); + } else if (iter.is_scalar(2) && iter.data_ptr(2) != nullptr && at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(dtype, "mul_cpu_reduced_float", [&]() { + using opmath_t = at::opmath_type; + opmath_t b = iter.original_scalar_value(2); + iter.remove_operand(2); + cpu_kernel_vec( + iter, + [=](scalar_t a) __ubsan_ignore_undefined__ -> scalar_t { + return static_cast(a) * b; + }, + [=](Vectorized a) __ubsan_ignore_undefined__ { + return binary_op_scalar( + a, + b, + [](const Vectorized& x, + const Vectorized& y) { return x * y; }); + }); + }); + } else { + _AT_DISPATCH_MUL_TYPES(dtype, "mul_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) + __ubsan_ignore_undefined__ -> scalar_t { return a * b; }, + [=](Vectorized a, Vectorized b) + __ubsan_ignore_undefined__ { return a * b; }); + }); + } +} + +void div_true_kernel(TensorIteratorBase& iter) { + const auto dtype = iter.common_dtype(); + if (iter.is_scalar(2) && iter.data_ptr(2) != nullptr && at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(dtype, "div_cpu_reduced_float", [&]() { + using opmath_t = at::opmath_type; + opmath_t b = iter.original_scalar_value(2); + iter.remove_operand(2); + cpu_kernel_vec( + iter, + [=](scalar_t a) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return static_cast(a) / b; + }, + [=](Vectorized a) { + return binary_op_scalar( + a, + b, + [](const Vectorized& x, + const Vectorized& y) { return x / y; }); + }); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + kBFloat16, kHalf, dtype, "div_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) + __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return a / b; + }, + [](Vectorized a, Vectorized b) { + return a / b; + }); + }); + } +} + +void div_trunc_kernel(TensorIteratorBase& iter) { + const auto dtype = iter.common_dtype(); + if (isIntegralType(dtype, /*includeBool*/ false)) { + // There's no SIMD integer division, so don't try to vectorize it. + // TODO: if the divisor is a scalar, rewrite as multiplication by a + // constant. + AT_DISPATCH_INTEGRAL_TYPES(dtype, "div_trunc_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + TORCH_CHECK(b != 0, "ZeroDivisionError"); + return a / b; + }); + }); + } else if (iter.is_scalar(2) && iter.data_ptr(2) != nullptr && at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES( + dtype, "div_trunc_cpu_reduced_float", [&]() { + using opmath_t = at::opmath_type; + opmath_t b = iter.original_scalar_value(2); + iter.remove_operand(2); + cpu_kernel_vec( + iter, + [=](scalar_t a) + __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return std::trunc(static_cast(a) / b); + }, + [=](Vectorized a) { + return binary_op_scalar( + a, + b, + [](const Vectorized& x, + const Vectorized& y) { + return (x / y).trunc(); + }); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, dtype, "div_trunc_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) + __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return std::trunc(a / b); + }, + [](Vectorized a, Vectorized b) { + return (a / b).trunc(); + }); + }); + } +} + +template +inline Vectorized div_floor_floating_vec( + const Vectorized& a, + const Vectorized& b) { + using vec_t = Vectorized; + const auto basic_div = a / b; + vec_t inf(std::numeric_limits::infinity()); + auto mod = a.fmod(b); + // Fixup for a case that isn't properly handled by Sleef_fmod + auto floor = vec_t::blendv(a - mod, a, (basic_div.abs() == inf) & (a.abs() != inf)); + auto div = floor / b; + const auto zero = vec_t(0); + auto mask = (mod != zero) & ((b < zero) ^ (mod < zero)); + const auto one = vec_t(1); + div = vec_t::blendv(div, div - one, mask); + auto floordiv = div.floor(); + mask = (div - floordiv) > vec_t(0.5); + floordiv = vec_t::blendv(floordiv, floordiv + one, mask); + floordiv = vec_t::blendv(floordiv, zero.copysign(basic_div), div == zero); + floordiv = vec_t::blendv(floordiv, basic_div, b == zero); + return floordiv; +} + +#if defined(CPU_CAPABILITY_SVE256) && defined(__ARM_FEATURE_BF16) + +// Since sve lacks sufficient bf16 intrinsics, do the calculations in f32 to +// avoid rounding errors. This should not cause performance issues as +// most of the used instructions would be cast to f32 vectors anyway. +template<> +inline Vectorized div_floor_floating_vec( + const Vectorized& a, + const Vectorized& b) { + auto [a1, a2] = convert_bfloat16_float(a); + auto [b1, b2] = convert_bfloat16_float(b); + + auto res1 = div_floor_floating_vec(a1, b1); + auto res2 = div_floor_floating_vec(a2, b2); + + return convert_float_bfloat16(res1, res2); +} + +#endif + +void div_floor_kernel(TensorIteratorBase& iter) { + const auto dtype = iter.common_dtype(); + if (dtype == kByte) { + // In the special case of unsigned integer division, floor division is + // equivalent to truncation division (since the signs of the divisor and + // dividend are always the same) + div_trunc_kernel(iter); + return; + } else if (isIntegralType(dtype, /*includeBool*/ false)) { + // There's no SIMD integer division, so don't try to vectorize it. + AT_DISPATCH_INTEGRAL_TYPES(dtype, "div_floor_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + TORCH_CHECK(b != 0, "ZeroDivisionError"); + return c10::div_floor_integer(a, b); + }); + }); + } else { + // See NOTE: [Floor Division in Python] + if (iter.is_scalar(2) && iter.data_ptr(2) != nullptr && at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES( + dtype, "div_floor_cpu_reduced_float", [&]() { + using opmath_t = at::opmath_type; + opmath_t b = iter.original_scalar_value(2); + iter.remove_operand(2); + using vec_t = Vectorized; + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { + return c10::div_floor_floating(static_cast(a), b); + }, + [=](Vectorized a) { + return binary_op_scalar( + a, b, [](const vec_t& x, const vec_t& y) { + return div_floor_floating_vec(x, y); + }); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, dtype, "div_floor_cpu", [&]() { + using vec_t = Vectorized; + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + return c10::div_floor_floating(a, b); + }, + [](vec_t a, vec_t b) -> vec_t { + return div_floor_floating_vec(a, b); + }); + }); + } + } +} + +void remainder_kernel(TensorIteratorBase& iter) { + if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "remainder_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + TORCH_CHECK(b != 0, "ZeroDivisionError"); + if (a == std::numeric_limits::min() && b == scalar_t(-1)) { + return 0; + } + scalar_t r = a % b; + if ((r != 0) && (c10::is_negative(r) != c10::is_negative(b))) { + r += b; + } + return r; + }); + }); + } else if (iter.common_dtype() == kBFloat16) { + cpu_kernel_vec( + iter, + [=](BFloat16 a, BFloat16 b) + __ubsan_ignore_float_divide_by_zero__ -> BFloat16 { + float a0 = static_cast(a); + float b0 = static_cast(b); + float mod0 = std::fmod(a0, b0); + if ((mod0 != 0) && ((b0 < 0) != (mod0 < 0))) { + mod0 += b0; + } + return mod0; + }, + [=](Vectorized a, Vectorized b) { + auto [a0, a1] = convert_bfloat16_float(a); + auto [b0, b1] = convert_bfloat16_float(b); + auto mod0 = a0.fmod(b0); + auto mod1 = a1.fmod(b1); + const auto zero = Vectorized(0); + auto mask0 = (mod0 != zero) & ((b0 < zero) ^ (mod0 < zero)); + auto mask1 = (mod1 != zero) & ((b1 < zero) ^ (mod1 < zero)); + a0 = Vectorized::blendv(mod0, mod0 + b0, mask0); + a1 = Vectorized::blendv(mod1, mod1 + b1, mask1); + return convert_float_bfloat16(a0, a1); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + iter.common_dtype(), "remainder_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) + __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + scalar_t mod = std::fmod(a, b); + if ((mod != 0) && ((b < 0) != (mod < 0))) + mod += b; + return mod; + }, + [=](Vectorized a, Vectorized b) { + auto mod = a.fmod(b); + const auto zero = Vectorized(0); + auto mask = (mod != zero) & ((b < zero) ^ (mod < zero)); + return Vectorized::blendv(mod, mod + b, mask); + }); + }); + } +} + +void bitwise_and_kernel(TensorIteratorBase& iter) { + if (iter.dtype() == ScalarType::Bool) { + cpu_kernel(iter, [](bool a, bool b) { return a && b; }); + } else { + _AT_DISPATCH_INTEGRAL_TYPES_V2(iter.dtype(), "bitwise_and_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a & b; }, + [](Vectorized a, Vectorized b) { return a & b; }); + }); + } +} + +void bitwise_or_kernel(TensorIteratorBase& iter) { + if (iter.dtype() == ScalarType::Bool) { + cpu_kernel(iter, [](bool a, bool b) { return a || b; }); + } else { + _AT_DISPATCH_INTEGRAL_TYPES_V2(iter.dtype(), "bitwise_or_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a | b; }, + [](Vectorized a, Vectorized b) { return a | b; }); + }); + } +} + +void bitwise_xor_kernel(TensorIteratorBase& iter) { + if (iter.dtype() == ScalarType::Bool) { + // Boolean type does not work with ^ (bitwise XOR) in C++. bitwise_xor wraps + // this operation for both Boolean and integral types. + cpu_kernel(iter, [](bool a, bool b) { return a != b; }); + } else { + _AT_DISPATCH_INTEGRAL_TYPES_V2(iter.dtype(), "bitwise_xor_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a ^ b; }, + [](Vectorized a, Vectorized b) { return a ^ b; }); + }); + } +} + +void lshift_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "lshift_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + constexpr scalar_t max_shift = sizeof(scalar_t) * CHAR_BIT; + if ((static_cast>(b) < 0) || + (b >= max_shift)) { + return 0; + } + return static_cast>(a) << b; + }, + [](Vectorized a, Vectorized b) { return a << b; }); + }); +} + +void logical_and_kernel(TensorIterator& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "logical_and_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t a, scalar_t b) -> bool { return a && b; }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( + kBFloat16, kHalf, iter.common_dtype(), "logical_and_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return static_cast(a && b); + }); + }); + } +} + +void logical_or_kernel(TensorIterator& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "logical_or_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t a, scalar_t b) -> bool { return a || b; }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "logical_or_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return static_cast(a || b); + }); + }); + } +} + +void logical_xor_kernel(TensorIterator& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "logical_xor_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> bool { + return bool(a) != bool(b); + }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( + kBFloat16, kHalf, iter.common_dtype(), "logical_xor_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return static_cast(bool(a) != bool(b)); + }); + }); + } +} + +void rshift_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "rshift_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + // right shift value to retain sign bit for signed and no bits for + // unsigned + constexpr scalar_t max_shift = + sizeof(scalar_t) * CHAR_BIT - std::is_signed_v; + if ((static_cast>(b) < 0) || + (b >= max_shift)) { + return a >> max_shift; + } + return a >> b; + }, + [](Vectorized a, Vectorized b) { return a >> b; }); + }); +} + +void lt_kernel(TensorIteratorBase& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "lt_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t a, scalar_t b) -> bool { return a < b; }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "lt_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a < b; }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.lt(b); }); + }); + } +} + +void le_kernel(TensorIteratorBase& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "le_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t a, scalar_t b) -> bool { return a <= b; }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "le_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a <= b; }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.le(b); }); + }); + } +} + +void gt_kernel(TensorIteratorBase& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "gt_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t a, scalar_t b) -> bool { return a > b; }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "gt_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a > b; }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.gt(b); }); + }); + } +} + +void ge_kernel(TensorIteratorBase& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_ALL_TYPES_AND3( + kBool, kBFloat16, kHalf, iter.common_dtype(), "ge_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t a, scalar_t b) -> bool { return a >= b; }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "ge_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return a >= b; }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.ge(b); }); + }); + } +} + +void eq_kernel(TensorIteratorBase& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_V2(iter.common_dtype(), "eq_cpu", AT_WRAP([&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> bool { return a == b; }); + }), kComplexHalf, kBComplex32, kHalf, kBool, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), kFloat4_e2m1fn_x2); + } else { + AT_DISPATCH_V2(iter.common_dtype(), "eq_cpu", AT_WRAP([&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + return static_cast(a == b); + }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.eq(b); }); + }), kComplexHalf, kHalf, kBComplex32, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), kFloat4_e2m1fn_x2); + } +} + +void ne_kernel(TensorIteratorBase& iter) { + // See Note [special-case bool outputs] + if (iter.dtype() == ScalarType::Bool) { + AT_DISPATCH_V2(iter.common_dtype(), "ne_cpu", AT_WRAP([&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> bool { return a != b; }); + }), kComplexHalf, kBComplex32, kHalf, kBool, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), kFloat4_e2m1fn_x2); + } else { + AT_DISPATCH_V2(iter.common_dtype(), "ne_cpu", AT_WRAP([&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + return static_cast(a != b); + }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.ne(b); }); + }), kComplexHalf, kHalf, kBComplex32, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), kFloat4_e2m1fn_x2); + } +} + +void maximum_kernel(TensorIteratorBase& iter) { + if (iter.dtype() == ScalarType::Bool) { + cpu_kernel(iter, [](bool a, bool b) -> bool { return a || b; }); + } else if (isIntegralType(iter.dtype(), /*includeBool=*/false)) { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "maximum_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return std::max(a, b); }, + [](Vectorized a, Vectorized b) { + return at::vec::maximum(a, b); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "maximum_cpu", + [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + if (a != a || b != b) { + return std::numeric_limits::quiet_NaN(); + } else { + return std::max(a, b); + } + }, + [](Vectorized a, Vectorized b) { + return at::vec::maximum(a, b); + }); + }); + } +} + +void minimum_kernel(TensorIteratorBase& iter) { + if (iter.dtype() == ScalarType::Bool) { + cpu_kernel(iter, [](bool a, bool b) -> bool { return a && b; }); + } else if (isIntegralType(iter.dtype(), /*includeBool=*/false)) { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "minimum_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return std::min(a, b); }, + [](Vectorized a, Vectorized b) { + return at::vec::minimum(a, b); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "minimum_cpu", + [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + if (a != a || b != b) { + return std::numeric_limits::quiet_NaN(); + } else { + return std::min(a, b); + } + }, + [](Vectorized a, Vectorized b) { + return at::vec::minimum(a, b); + }); + }); + } +} + +void fmax_kernel(TensorIteratorBase& iter) { + if (isFloatingType(iter.common_dtype())) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.common_dtype(), + "fmax_cpu", + [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return std::fmax(a, b); + }); + }); + } else { + maximum_kernel(iter); + } +} + +void fmin_kernel(TensorIteratorBase& iter) { + if (isFloatingType(iter.common_dtype())) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.common_dtype(), + "fmin_cpu", + [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return std::fmin(a, b); + }); + }); + } else { + minimum_kernel(iter); + } +} + +void smooth_l1_kernel(TensorIteratorBase& iter, double beta) { + if (iter.dtype() == kBFloat16) { + const float beta_val(static_cast(beta)); + const Vectorized beta_val_vec(beta_val); + const Vectorized point_five_vec(static_cast(0.5)); + cpu_kernel_vec( + iter, + [&beta_val](BFloat16 a, BFloat16 b) -> BFloat16 { + auto z = std::abs(float(a) - float(b)); + return z < beta_val ? static_cast(0.5) * z * z / beta_val + : z - static_cast(0.5) * beta_val; + }, + [&beta_val_vec, &point_five_vec]( + Vectorized a, Vectorized b) { + auto [a0, a1] = convert_bfloat16_float(a); + auto [b0, b1] = convert_bfloat16_float(b); + auto z = (a0 - b0).abs(); + a0 = Vectorized::blendv( + point_five_vec * z * z / beta_val_vec, + z - point_five_vec * beta_val_vec, + z >= beta_val_vec); + z = (a1 - b1).abs(); + a1 = Vectorized::blendv( + point_five_vec * z * z / beta_val_vec, + z - point_five_vec * beta_val_vec, + z >= beta_val_vec); + return convert_float_bfloat16(a0, a1); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND(kHalf, iter.dtype(), "smooth_l1_cpu", [&]() { + using Vec = Vectorized; + const scalar_t beta_val(beta); + const Vec beta_val_vec(beta_val); + const Vec point_five_vec(static_cast(0.5)); + cpu_kernel_vec( + iter, + [&beta_val](scalar_t a, scalar_t b) -> scalar_t { + auto z = std::abs(a - b); + return z < beta_val ? static_cast(0.5) * z * z / beta_val + : z - static_cast(0.5) * beta_val; + }, + [&beta_val_vec, &point_five_vec](Vec a, Vec b) { + auto z = (a - b).abs(); + return Vec::blendv( + point_five_vec * z * z / beta_val_vec, + z - point_five_vec * beta_val_vec, + z >= beta_val_vec); + }); + }); + } +} + +void huber_kernel(TensorIterator& iter, double delta) { + // Special-case kHalf: compute in float for numerical stability + if (iter.dtype() == kHalf) { + const float delta_val(static_cast(delta)); + const Vectorized delta_vec(static_cast(delta)); + const Vectorized point_five_vec(static_cast(0.5)); + cpu_kernel_vec( + iter, + // scalar lambda: convert half -> float, compute in float, cast back to half + [&delta_val] (at::Half a, at::Half b) -> at::Half { + float af = static_cast(a); + float bf = static_cast(b); + float z = std::abs(af - bf); + float out = z < delta_val + ? 0.5f * z * z + : delta_val * (z - 0.5f * delta_val); + return static_cast(out); + }, + [&delta_vec, &point_five_vec] (Vectorized a, Vectorized b) { + auto [a0, a1] = convert_half_float(a); + auto [b0, b1] = convert_half_float(b); + auto z = (a0 - b0).abs(); + a0 = Vectorized::blendv( + point_five_vec * z * z, + delta_vec * (z - point_five_vec * delta_vec), + z >= delta_vec); + z = (a1 - b1).abs(); + a1 = Vectorized::blendv( + point_five_vec * z * z, + delta_vec * (z - point_five_vec * delta_vec), + z >= delta_vec); + return convert_float_half(a0, a1); + } + ); + return; + } + else { + AT_DISPATCH_FLOATING_TYPES_AND(kBFloat16, iter.dtype(), "huber_cpu", [&]() { + using Vec = Vectorized; + const scalar_t delta_val(delta); + const Vec delta_val_vec(delta_val); + const Vec point_five_vec(static_cast(0.5)); + cpu_kernel_vec( + iter, + [&delta_val](scalar_t a, scalar_t b) -> scalar_t { + auto z = std::abs(a - b); + return z < delta_val + ? static_cast(0.5) * z * z + : delta_val * (z - static_cast(0.5) * delta_val); + }, + [&delta_val_vec, &point_five_vec](Vec a, Vec b) { + auto z = (a - b).abs(); + return Vec::blendv( + point_five_vec * z * z, + delta_val_vec * (z - point_five_vec * delta_val_vec), + z >= delta_val_vec); + }); + }); + } +} + +void sigmoid_backward_kernel(TensorIteratorBase& iter) { + if (isComplexType(iter.dtype())) { + AT_DISPATCH_COMPLEX_TYPES(iter.dtype(), "sigmoid_backward_cpu", [&]() { + auto one_vec = Vectorized(scalar_t{1}); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return a * std::conj((scalar_t(1) - b) * b); + }, + [=](Vectorized a, Vectorized b) { + return a * ((one_vec - b) * b).conj(); + }); + }); + } else if (iter.dtype() == kBFloat16) { + auto one_vec = Vectorized((float)1); + cpu_kernel_vec( + iter, + [=](BFloat16 a, BFloat16 b) -> BFloat16 { + float a0 = static_cast(a); + float b0 = static_cast(b); + return a0 * (float(1) - b0) * b0; + }, + [=](Vectorized a, Vectorized b) { + auto [a0, a1] = convert_bfloat16_float(a); + auto [b0, b1] = convert_bfloat16_float(b); + a0 = a0 * (one_vec - b0) * b0; + a1 = a1 * (one_vec - b1) * b1; + return convert_float_bfloat16(a0, a1); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND( + kHalf, iter.dtype(), "sigmoid_backward_cpu", [&]() { + auto one_vec = Vectorized((scalar_t)(1)); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return a * (scalar_t(1) - b) * b; + }, + [=](Vectorized a, Vectorized b) { + return a * (one_vec - b) * b; + }); + }); + } +} + +void logit_backward_kernel(TensorIteratorBase& iter, const Scalar& eps_scalar) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.dtype(), "logit_backward_cpu", [&]() { + const scalar_t eps = eps_scalar.to(); + const Vectorized kZeroVec(scalar_t(0)); + const Vectorized kOneVec(scalar_t(1)); + if (eps < scalar_t(0)) { + const Vectorized kNanVec( + std::numeric_limits::quiet_NaN()); + cpu_kernel_vec( + iter, + [](scalar_t dy, scalar_t x) { + return (x < scalar_t(0) || x > scalar_t(1)) + ? std::numeric_limits::quiet_NaN() + : ((x == scalar_t(0) || x == scalar_t(1)) + ? (dy * std::numeric_limits::infinity()) + : (dy / (x * (scalar_t(1) - x)))); + }, + [kZeroVec, kOneVec, kNanVec]( + Vectorized dy_vec, Vectorized x_vec) { + return Vectorized::blendv( + kNanVec, + dy_vec / (x_vec * (kOneVec - x_vec)), + (x_vec >= kZeroVec) & (x_vec <= kOneVec)); + }); + } else { + const scalar_t lo = eps; + const scalar_t hi = scalar_t(1) - eps; + const Vectorized lo_vec(lo); + const Vectorized hi_vec(hi); + cpu_kernel_vec( + iter, + [lo, hi](scalar_t dy, scalar_t x) { + return (x < lo || x > hi) + ? scalar_t(0) + : ((x == scalar_t(0) || x == scalar_t(1)) + ? dy * std::numeric_limits::infinity() + : dy / (x * (scalar_t(1) - x))); + }, + [kZeroVec, kOneVec, lo_vec, hi_vec]( + Vectorized dy_vec, Vectorized x_vec) { + return Vectorized::blendv( + kZeroVec, + dy_vec / (x_vec * (kOneVec - x_vec)), + (x_vec >= lo_vec) & (x_vec <= hi_vec)); + }); + } + }); +} + +void tanh_backward_kernel(TensorIteratorBase& iter) { + if (isComplexType(iter.dtype())) { + AT_DISPATCH_COMPLEX_TYPES(iter.dtype(), "tanh_backward_cpu", [&]() { + auto one_vec = Vectorized(scalar_t{1}); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return a * std::conj(scalar_t{1} - b * b); + }, + [=](Vectorized a, Vectorized b) { + return a * (one_vec - b * b).conj(); + }); + }); + } else if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES( + iter.dtype(), "tanh_backward_cpu", [&]() { + auto one_vec = Vectorized(float{1}); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + float a0 = float(a); + float b0 = float(b); + return a0 * (float{1} - b0 * b0); + }, + [=](Vectorized a, Vectorized b) { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + a0 = a0 * (one_vec - b0 * b0); + a1 = a1 * (one_vec - b1 * b1); + return convert_from_float(a0, a1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "tanh_backward_cpu", [&]() { + auto one_vec = Vectorized(scalar_t{1}); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return a * (scalar_t{1} - b * b); + }, + [=](Vectorized a, Vectorized b) { + return a * (one_vec - b * b); + }); + }); + } +} + +void mse_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "mse_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + auto diff = a - b; + return diff * diff; + }, + [=](Vectorized a, Vectorized b) { + auto diff = a - b; + return diff * diff; + }); + }); +} + +void fmod_kernel(TensorIteratorBase& iter) { + if (isIntegralType(iter.common_dtype(), /*includeBool=*/false)) { + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "fmod_cpu", [&]() { + cpu_kernel(iter, [=](scalar_t x, scalar_t d) -> scalar_t { + TORCH_CHECK(d != 0, "ZeroDivisionError"); + if (x == std::numeric_limits::min() && d == scalar_t(-1)) { + return 0; + } + return x % d; + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "fmod_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t x, scalar_t d) -> scalar_t { + return std::fmod(x, d); + }, + [](Vectorized x, Vectorized d) { + return x.fmod(d); + }); + }); + } +} + +void logaddexp_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "logaddexp_cpu", [&]() { + using Vec = Vectorized; + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + float a0 = static_cast(a); + float b0 = static_cast(b); + if (std::isinf(a0) && a0 == b0) { + return a0; + } else { + float m0 = std::max(a0, b0); + return m0 + std::log1p(std::exp(-std::abs(a0 - b0))); + } + }, + [=](Vec a, Vec b) -> Vec { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + Vectorized inf(std::numeric_limits::infinity()); + Vectorized m0 = maximum(a0, b0); + Vectorized m1 = maximum(a1, b1); + a0 = Vectorized::blendv( + m0 + (a0 - b0).abs().neg().exp().log1p(), + a0, + (a0 == b0) & (a0.abs() == inf)); + a1 = Vectorized::blendv( + m1 + (a1 - b1).abs().neg().exp().log1p(), + a1, + (a1 == b1) & (a1.abs() == inf)); + return convert_from_float(a0, a1); + }); + }); + } else if (isComplexType(iter.dtype())) { + AT_DISPATCH_COMPLEX_TYPES(iter.dtype(), "logaddexp_cpu", [&]() { + cpu_kernel(iter, [=](scalar_t a, scalar_t b) -> scalar_t { + return _log_add_exp_helper(a, b); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "logaddexp_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + if (std::isinf(a) && a == b) { + return a; + } else { + scalar_t m = std::max(a, b); + return m + std::log1p(std::exp(-std::abs(a - b))); + } + }, + [=](Vectorized a, Vectorized b) { + Vectorized inf(std::numeric_limits::infinity()); + Vectorized m = maximum(a, b); + return Vectorized::blendv( + m + (a - b).abs().neg().exp().log1p(), + a, + (a == b) & (a.abs() == inf)); + }); + }); + } +} + +void logaddexp2_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "logaddexp2_cpu", [&]() { + using Vec = Vectorized; + constexpr auto inv_log_2 = static_cast(1.0 / c10::ln_2); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + float a0 = static_cast(a); + float b0 = static_cast(b); + if (std::isinf(a0) && a0 == b0) { + return a0; + } else { + float m0 = std::max(a0, b0); + return m0 + std::log1p(std::exp2(-std::abs(a0 - b0))) * inv_log_2; + } + }, + [=](Vec a, Vec b) -> Vec { + auto [a0, a1] = convert_to_float(a); + auto [b0, b1] = convert_to_float(b); + Vectorized inf(std::numeric_limits::infinity()); + Vectorized inv_log_2_vec(inv_log_2); + Vectorized m0 = maximum(a0, b0); + Vectorized m1 = maximum(a1, b1); + a0 = Vectorized::blendv( + m0 + (a0 - b0).abs().neg().exp2().log1p() * inv_log_2_vec, + a0, + (a0 == b0) & (a0.abs() == inf)); + a1 = Vectorized::blendv( + m1 + (a1 - b1).abs().neg().exp2().log1p() * inv_log_2_vec, + a1, + (a1 == b1) & (a1.abs() == inf)); + return convert_from_float(a0, a1); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.dtype(), "logaddexp2_cpu", [&]() { + constexpr auto inv_log_2 = static_cast(1.0 / c10::ln_2); + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + if (std::isinf(a) && a == b) { + return a; + } else { + scalar_t m = std::max(a, b); + return m + std::log1p(std::exp2(-std::abs(a - b))) * inv_log_2; + } + }, + [=](Vectorized a, Vectorized b) { + Vectorized inf(std::numeric_limits::infinity()); + Vectorized inv_log_2_vec(inv_log_2); + Vectorized m = maximum(a, b); + return Vectorized::blendv( + m + (a - b).abs().neg().exp2().log1p() * inv_log_2_vec, + a, + (a == b) & (a.abs() == inf)); + }); + }); + } +} + +void gcd_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "gcd_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return calc_gcd(a, b); + }); + }); +} + +void lcm_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "lcm_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + scalar_t g = calc_gcd(a, b); + return (g == 0) ? 0 : std::abs(a / g * b); + }); + }); +} + +void hypot_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.dtype(), "hypot_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return std::hypot(a, b); + }, + [=](Vectorized a, Vectorized b) { + return a.hypot(b); + }); + }); +} + +void igamma_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.dtype(), "igamma_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return calc_igamma(a, b); + }, + [=](Vectorized a, Vectorized b) { + return a.igamma(b); + }); + }); +} + +void igammac_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.dtype(), "igammac_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return calc_igammac(a, b); + }, + [=](Vectorized a, Vectorized b) { + return a.igammac(b); + }); + }); +} + +void nextafter_kernel(TensorIteratorBase& iter) { + if (at::isReducedFloatingType(iter.common_dtype())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(), "nextafter_cpu", [&]() { + cpu_kernel(iter, [=](scalar_t a, scalar_t b) -> scalar_t { + return std::nextafter(a, b); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(iter.common_dtype(), "nextafter_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a, scalar_t b) -> scalar_t { + return std::nextafter(a, b); + }, + [=](Vectorized a, Vectorized b) { + return a.nextafter(b); + }); + }); + } +} + +void heaviside_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_ALL_TYPES_AND3( + kHalf, kBool, kBFloat16, iter.dtype(), "heaviside_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a, scalar_t b) -> scalar_t { + return a == 0 ? b : static_cast(a > 0); + }); + }); +} + +void copysign_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "copysign_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { + return c10::copysign(a, b); + }, + [](Vectorized a, Vectorized b) + -> Vectorized { return a.copysign(b); }); + }); +} + +void xlogy_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "xlogy_cpu", [&]() { + cpu_kernel(iter, [](scalar_t x, scalar_t y) -> scalar_t { + if (at::_isnan(y)) { + return NAN; + } + if (x == 0) { + return 0; + } + return x * std::log(y); + }); + }); +} + +void xlog1py_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "xlog1py_cpu", [&]() { + cpu_kernel(iter, [](scalar_t x, scalar_t y) -> scalar_t { + if (at::_isnan(y)) { + return NAN; + } + if (x == 0) { + return 0; + } + return x * std::log1p(y); + }); + }); +} + +void zeta_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES(iter.common_dtype(), "zeta_cpu", [&]() { + cpu_kernel( + iter, [](scalar_t x, scalar_t q) -> scalar_t { return zeta(x, q); }); + }); +} + +void chebyshev_polynomial_t_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "chebyshev_polynomial_t_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return chebyshev_polynomial_t_forward(x, n); + }); + }); +} // chebyshev_polynomial_t_kernel(TensorIteratorBase& iterator) + +void chebyshev_polynomial_u_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "chebyshev_polynomial_u_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return chebyshev_polynomial_u_forward(x, n); + }); + }); +} // chebyshev_polynomial_u_kernel(TensorIteratorBase& iterator) + +void chebyshev_polynomial_v_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "chebyshev_polynomial_v_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return chebyshev_polynomial_v_forward(x, n); + }); + }); +} // chebyshev_polynomial_v_kernel(TensorIteratorBase& iterator) + +void chebyshev_polynomial_w_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "chebyshev_polynomial_w_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return chebyshev_polynomial_w_forward(x, n); + }); + }); +} // chebyshev_polynomial_w_kernel(TensorIteratorBase& iterator) + +void hermite_polynomial_h_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "hermite_polynomial_h_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return hermite_polynomial_h_forward(x, n); + }); + }); +} // hermite_polynomial_h_kernel(TensorIteratorBase& iterator) + +void hermite_polynomial_he_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "hermite_polynomial_he_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return hermite_polynomial_he_forward(x, n); + }); + }); +} // hermite_polynomial_he_kernel(TensorIteratorBase& iterator) + +void laguerre_polynomial_l_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "laguerre_polynomial_l_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return laguerre_polynomial_l_forward(x, n); + }); + }); +} // laguerre_polynomial_l_kernel(TensorIteratorBase& iterator) + +void legendre_polynomial_p_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "legendre_polynomial_p_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return legendre_polynomial_p_forward(x, n); + }); + }); +} // legendre_polynomial_p_kernel(TensorIteratorBase& iterator) + +void shifted_chebyshev_polynomial_t_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "shifted_chebyshev_polynomial_t_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return shifted_chebyshev_polynomial_t_forward(x, n); + }); + }); +} // shifted_chebyshev_polynomial_t_kernel(TensorIteratorBase& iterator) + +void shifted_chebyshev_polynomial_u_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "shifted_chebyshev_polynomial_u_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return shifted_chebyshev_polynomial_u_forward(x, n); + }); + }); +} // shifted_chebyshev_polynomial_u_kernel(TensorIteratorBase& iterator) + +void shifted_chebyshev_polynomial_v_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "shifted_chebyshev_polynomial_v_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return shifted_chebyshev_polynomial_v_forward(x, n); + }); + }); +} // shifted_chebyshev_polynomial_v_kernel(TensorIteratorBase& iterator) + +void shifted_chebyshev_polynomial_w_kernel(TensorIteratorBase& iterator) { + AT_DISPATCH_FLOATING_TYPES( + iterator.common_dtype(), "shifted_chebyshev_polynomial_w_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x, scalar_t n) -> scalar_t { + return shifted_chebyshev_polynomial_w_forward(x, n); + }); + }); +} // shifted_chebyshev_polynomial_w_kernel(TensorIteratorBase& iterator) + +void ldexp_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.input_dtype(0), "ldexp_cpu", [&] { + using float_t = scalar_t; + AT_DISPATCH_INTEGRAL_TYPES(iter.input_dtype(1), "ldexp_cpu_exp", [&] { + using int_t = scalar_t; + cpu_kernel(iter, [](float_t x, int_t exp) -> float_t { + return static_cast(std::ldexp(static_cast(x), exp)); + }); + }); + }); +} + +} // namespace + +REGISTER_DISPATCH(add_clamp_stub, &add_clamp_kernel) +REGISTER_DISPATCH(mul_stub, &mul_kernel) +REGISTER_DISPATCH(div_true_stub, &div_true_kernel) +REGISTER_DISPATCH(div_trunc_stub, &div_trunc_kernel) +REGISTER_DISPATCH(div_floor_stub, &div_floor_kernel) +REGISTER_DISPATCH(bitwise_and_stub, &bitwise_and_kernel) +REGISTER_DISPATCH(bitwise_or_stub, &bitwise_or_kernel) +REGISTER_DISPATCH(bitwise_xor_stub, &bitwise_xor_kernel) +REGISTER_DISPATCH(lshift_stub, &lshift_kernel) +REGISTER_DISPATCH(rshift_stub, &rshift_kernel) +REGISTER_DISPATCH(logical_xor_stub, &logical_xor_kernel) +REGISTER_DISPATCH(logical_and_stub, &logical_and_kernel) +REGISTER_DISPATCH(logical_or_stub, &logical_or_kernel) +REGISTER_DISPATCH(lt_stub, <_kernel) +REGISTER_DISPATCH(le_stub, &le_kernel) +REGISTER_DISPATCH(gt_stub, >_kernel) +REGISTER_DISPATCH(ge_stub, &ge_kernel) +REGISTER_DISPATCH(eq_stub, &eq_kernel) +REGISTER_DISPATCH(ne_stub, &ne_kernel) +REGISTER_DISPATCH(maximum_stub, &maximum_kernel) +REGISTER_DISPATCH(minimum_stub, &minimum_kernel) +REGISTER_DISPATCH(fmax_stub, &fmax_kernel) +REGISTER_DISPATCH(fmin_stub, &fmin_kernel) +REGISTER_DISPATCH(copysign_stub, ©sign_kernel) +REGISTER_DISPATCH(remainder_stub, &remainder_kernel) +REGISTER_DISPATCH(fmod_stub, &fmod_kernel) +REGISTER_DISPATCH(gcd_stub, &gcd_kernel) +REGISTER_DISPATCH(lcm_stub, &lcm_kernel) +REGISTER_DISPATCH(xlogy_stub, &xlogy_kernel) +REGISTER_DISPATCH(xlog1py_stub, &xlog1py_kernel) +REGISTER_DISPATCH(zeta_stub, &zeta_kernel) +REGISTER_DISPATCH(nextafter_stub, &nextafter_kernel) +REGISTER_DISPATCH(heaviside_stub, &heaviside_kernel) +REGISTER_DISPATCH(chebyshev_polynomial_t_stub, &chebyshev_polynomial_t_kernel) +REGISTER_DISPATCH(chebyshev_polynomial_v_stub, &chebyshev_polynomial_v_kernel) +REGISTER_DISPATCH(chebyshev_polynomial_w_stub, &chebyshev_polynomial_w_kernel) +REGISTER_DISPATCH(laguerre_polynomial_l_stub, &laguerre_polynomial_l_kernel) +REGISTER_DISPATCH(legendre_polynomial_p_stub, &legendre_polynomial_p_kernel) +REGISTER_DISPATCH( + shifted_chebyshev_polynomial_t_stub, + &shifted_chebyshev_polynomial_t_kernel) +REGISTER_DISPATCH( + shifted_chebyshev_polynomial_u_stub, + &shifted_chebyshev_polynomial_u_kernel) +REGISTER_DISPATCH( + shifted_chebyshev_polynomial_v_stub, + &shifted_chebyshev_polynomial_v_kernel) +REGISTER_DISPATCH( + shifted_chebyshev_polynomial_w_stub, + &shifted_chebyshev_polynomial_w_kernel) +// Might enable AVX512 dispatch after enabling explicit vectorization for them. +REGISTER_DISPATCH(chebyshev_polynomial_u_stub, &chebyshev_polynomial_u_kernel) +REGISTER_DISPATCH(hermite_polynomial_h_stub, &hermite_polynomial_h_kernel) +REGISTER_DISPATCH(hermite_polynomial_he_stub, &hermite_polynomial_he_kernel) +REGISTER_DISPATCH(ldexp_stub, ldexp_kernel) + +ALSO_REGISTER_AVX512_DISPATCH(atan2_stub, &atan2_kernel) +ALSO_REGISTER_AVX512_DISPATCH(smooth_l1_stub, &smooth_l1_kernel) +ALSO_REGISTER_AVX512_DISPATCH(huber_stub, &huber_kernel) +ALSO_REGISTER_AVX512_DISPATCH(sigmoid_backward_stub, &sigmoid_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(logit_backward_stub, &logit_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(tanh_backward_stub, &tanh_backward_kernel) +ALSO_REGISTER_AVX512_DISPATCH(mse_stub, &mse_kernel) +ALSO_REGISTER_AVX512_DISPATCH(logaddexp_stub, &logaddexp_kernel) +ALSO_REGISTER_AVX512_DISPATCH(logaddexp2_stub, &logaddexp2_kernel) +ALSO_REGISTER_AVX512_DISPATCH(hypot_stub, &hypot_kernel) +ALSO_REGISTER_AVX512_DISPATCH(igamma_stub, &igamma_kernel) +ALSO_REGISTER_AVX512_DISPATCH(igammac_stub, &igammac_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/BlasKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/BlasKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fe9637e01b405d6d485ec6624639587cd871528 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/BlasKernel.cpp @@ -0,0 +1,561 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#if !defined(C10_MOBILE) +namespace at::native::blas_impl { +void fp16_gemv_trans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy); + +float fp16_dot_with_fp32_arith( + const Half* x, + const Half* a, + int64_t len); + +float bf16_dot_with_fp32_arith( + const at::BFloat16* x, + const at::BFloat16* a, + int64_t len); +} // namespace at::native::blas_impl +#endif +#if defined(__aarch64__) && !defined(C10_MOBILE) +#include + +namespace at::native::blas_impl { +void fp16_gemv_notrans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy); +} // namespace at::native::blas_impl +#endif + +namespace at::native { +namespace cpublas { +namespace { + +template +void scale_(int64_t m, int64_t n, opmath_t alpha, scalar_t *a, int64_t lda) { + if (alpha == opmath_t(1)) { + return; // identity + } + + if (alpha == opmath_t(0)) { + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + a[j * lda + i] = scalar_t(0); + } + } + return; + } + + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + a[j * lda + i] *= alpha; + } + } +} + +template +auto sum(int64_t N, Func f) { + constexpr int ilp_factor = 4; + using acc_t = decltype(f(0)); + + // Calculate independent partial sums then add together at the end + std::array partial_sums{}; + + int64_t i = 0; + for (; i + ilp_factor <= N; i += ilp_factor) { + c10::ForcedUnroll{}([&](int k) { + partial_sums[k] += f(i + k); + }); + } + for (; i < N; ++i) { + partial_sums[0] += f(i); + } + for (int k = 1; k < ilp_factor; ++k) { + partial_sums[0] += partial_sums[k]; + } + return partial_sums[0]; +} + +template +__ubsan_ignore_signed_int_overflow__ +std::enable_if_t, void> +gemm_notrans_( + int64_t m, + int64_t n, + int64_t k, + opmath_t alpha, + const scalar_t* a, + int64_t lda, + const scalar_t* b, + int64_t ldb, + opmath_t beta, + out_t* c, + int64_t ldc) { + // c *= beta + scale_(m, n, beta, c, ldc); + + // c += alpha * (a @ b) + const uint64_t unsigned_m = m; + const uint64_t i_m = unsigned_m / 4; + for (const uint64_t l : c10::irange(k)) { + for (const uint64_t j : c10::irange(n)) { + opmath_t val = b[l + j * ldb] * alpha; + for (const auto i_i : c10::irange(i_m)) { + c[j * ldc + i_i * 4 + 0] += a[i_i * 4 + 0 + l * lda] * val; + c[j * ldc + i_i * 4 + 1] += a[i_i * 4 + 1 + l * lda] * val; + c[j * ldc + i_i * 4 + 2] += a[i_i * 4 + 2 + l * lda] * val; + c[j * ldc + i_i * 4 + 3] += a[i_i * 4 + 3 + l * lda] * val; + } + uint64_t i = i_m * 4; + for (; i < unsigned_m; i++) + c[j * ldc + i] += a[i + l * lda] * val; + } + } +} + +// std::is_same || std::is_same +template +std::enable_if_t, void> +gemm_notrans_( + int64_t m, + int64_t n, + int64_t k, + opmath_t alpha, + const scalar_t* a, + int64_t lda, + const scalar_t* b, + int64_t ldb, + opmath_t beta, + out_t* c, + int64_t ldc) { + // c += alpha * (a @ b) + for (const auto i : c10::irange(m)) { + for (const auto j : c10::irange(n)) { + const auto dot = sum(k, [&](int64_t l) -> opmath_t { + return static_cast(a[l * lda + i]) * + static_cast(b[j * ldb + l]); + }); + if (beta == opmath_t(0)) { + c[j * ldc + i] = alpha * dot; + } else { + c[j * ldc + i] = beta * c[j * ldc + i] + alpha * dot; + } + } + } +} + +template +void gemm_transa_( + TransposeType transa, + int64_t m, int64_t n, int64_t k, + opmath_t alpha, + const scalar_t *a, int64_t lda, + const scalar_t *b, int64_t ldb, + opmath_t beta, + out_t *c, int64_t ldc) { + // c = alpha * (a.T @ b) + beta * c + const scalar_t *a_ = a; + for (const auto i : c10::irange(m)) { + const scalar_t *b_ = b; + for (const auto j : c10::irange(n)) { + const auto dot = sum(k, [&](int64_t l) -> opmath_t { + return static_cast(transa == TransposeType::ConjTranspose ? conj_impl(a_[l]) : a_[l]) * static_cast(b_[l]); + }); + b_ += ldb; + if (beta == opmath_t(0)) { + c[j*ldc+i] = alpha*dot; + } else { + c[j*ldc+i] = beta*c[j*ldc+i]+alpha*dot; + } + } + a_ += lda; + } +} + +template +void gemm_transb_impl( + TransposeType transb, + int64_t m, + int64_t n, + int64_t k, + opmath_t alpha, + const scalar_t* a, + int64_t lda, + const scalar_t* b, + int64_t ldb, + /* we expect pre-applied beta */ + opmath_t* c, + int64_t ldc) { + // c += alpha * (a @ b.T) + for (const auto l : c10::irange(k)) { + for (const auto j : c10::irange(n)) { + opmath_t val = (transb == TransposeType::ConjTranspose ? conj_impl(b[j + l * ldb]) : b[j + l * ldb]) * alpha; + int64_t i_m = m / 4; + for (const auto i_i : c10::irange(i_m)) { + c[j * ldc + i_i * 4 + 0] += a[i_i * 4 + 0 + l * lda] * val; + c[j * ldc + i_i * 4 + 1] += a[i_i * 4 + 1 + l * lda] * val; + c[j * ldc + i_i * 4 + 2] += a[i_i * 4 + 2 + l * lda] * val; + c[j * ldc + i_i * 4 + 3] += a[i_i * 4 + 3 + l * lda] * val; + } + int64_t i = i_m * 4; + for (; i < m; i++) + c[j * ldc + i] += a[i + l * lda] * val; + } + } +} + +// in this case, scalar_t == opmath_t == out_t so out_t template param is not needed +template +std::enable_if_t, void> +gemm_transb_( + TransposeType transb, + int64_t m, + int64_t n, + int64_t k, + opmath_t alpha, + const scalar_t* a, + int64_t lda, + const scalar_t* b, + int64_t ldb, + opmath_t beta, + scalar_t* c, + int64_t ldc) { + // c *= beta + scale_(m, n, beta, c, ldc); + + gemm_transb_impl(transb, m, n, k, alpha, a, lda, b, ldb, c, ldc); +} + +// std::is_same || std::is_same +template +std::enable_if_t, void> +gemm_transb_( + TransposeType transb, + int64_t m, + int64_t n, + int64_t k, + opmath_t alpha, + const scalar_t* a, + int64_t lda, + const scalar_t* b, + int64_t ldb, + opmath_t beta, + out_t* c, + int64_t ldc) { + // We need to calculate full-precision dot products for correctness; + // users notice error accumulation with reduced-width types (e.g., + // https://github.com/pytorch/pytorch/issues/95125 and + // https://github.com/pytorch/pytorch/issues/83863, which were filed + // when we used gemm_transb_impl naively, accumulating into + // float16/bfloat16). The straightforward way to do this is to use + // the vector dot column algorithm anyway, but this gives terrible + // performance because of the non-contiguous matrix + // access. Therefore, we instead elect to allocate temporary space + // to hold the output at higher-precision so that we can accumulate + // into it using the above cache-friendly "load one vector element, + // FMA it with an entire matrix row into the entire result vector" + // algorithm instead. + const auto c_size = m * n; + auto c_accum = std::make_unique(c_size); + if (beta == 1) { + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + c_accum[j * m + i] = c[j * ldc + i]; + } + } + } else if (beta == 0) { + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + c_accum[j * m + i] = 0; + } + } + } else { + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + c_accum[j * m + i] = beta * c[j * ldc + i]; + } + } + } + gemm_transb_impl(transb, m, n, k, alpha, a, lda, b, ldb, c_accum.get(), m); + for (const auto j : c10::irange(n)) { + for (const auto i : c10::irange(m)) { + c[j * ldc + i] = c_accum[j * m + i]; + } + } +} + +template +void gemm_transab_( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + opmath_t alpha, + const scalar_t *a, int64_t lda, + const scalar_t *b, int64_t ldb, + opmath_t beta, + out_t *c, int64_t ldc) { + // c = beta * c + alpha * (a.T @ b.T) + for (const auto i : c10::irange(m)) { + for (const auto j : c10::irange(n)) { + const auto dot = sum(k, [&](int64_t l) -> opmath_t { + return static_cast(transa == TransposeType::ConjTranspose ? conj_impl(a[i * lda + l]) : a[i * lda + l]) * + static_cast(transb == TransposeType::ConjTranspose ? conj_impl(b[l * ldb + j]) : b[l * ldb + j]); + }); + + if (beta == opmath_t(0)) { + c[j * ldc + i] = alpha * dot; + } else { + c[j * ldc + i] = beta * c[j * ldc + i] + alpha * dot; + } + } + } +} + +#if defined(__aarch64__) && !defined(C10_MOBILE) +template <> +void gemm_notrans_( + int64_t m, + int64_t n, + int64_t k, + float alpha, + const at::Half* a, + int64_t lda, + const at::Half* b, + int64_t ldb, + float beta, + at::Half* c, + int64_t ldc) { + // c += alpha * (a @ b) + if (n == 1 && beta == 0.0 && alpha == 1.0) { + at::native::blas_impl::fp16_gemv_notrans(m, k, 1.0, a, lda, b, 1, 0.0, c, 1); + return; + } + for (const auto i : c10::irange(m)) { + for (const auto j : c10::irange(n)) { + const auto dot = sum(k, [&](int64_t l) -> float { + return float(c10::detail::fp16_from_bits(a[l * lda + i].x)) * + float(c10::detail::fp16_from_bits(b[j * ldb + l].x)); + }); + if (beta == 0) { + c[j * ldc + i] = alpha * dot; + } else { + c[j * ldc + i] = beta * c[j * ldc + i] + alpha * dot; + } + } + } +} +#endif // defined(__aarch64__) && !defined(C10_MOBILE) + +#if !defined(C10_MOBILE) +float compute_dot(const at::Half* a, const at::Half* b, int64_t len) { + return at::native::CPU_CAPABILITY::fp16_dot_with_fp32_arith( + a, b, len); +} + +template <> +void gemm_transa_( + TransposeType transa, + int64_t m, int64_t n, int64_t k, + float alpha, + const at::Half *a, int64_t lda, + const at::Half *b, int64_t ldb, + float beta, + at::Half *c, int64_t ldc) { + // c = alpha * (a.T @ b) + beta * c + if (n == 1 && alpha == 1.0) { + at::native::blas_impl::fp16_gemv_trans(k, m, 1.0, a, lda, b, 1, beta, c, 1); + return; + } + parallel_for(0, m, 1, [&](int64_t begin, int64_t end) { + const auto *a_ = a + begin * lda; + for (const auto i : c10::irange(begin, end)) { + const auto *b_ = b; + for (const auto j : c10::irange(n)) { + const auto dot = compute_dot(a_, b_, k); + b_ += ldb; + if (beta == 0) { + c[j*ldc+i] = alpha*dot; + } else { + c[j*ldc+i] = beta*c[j*ldc+i]+alpha*dot; + } + } + a_ += lda; + } + }); +} + +float compute_dot(const at::BFloat16* a, const at::BFloat16* b, int64_t len) { + return at::native::CPU_CAPABILITY::bf16_dot_with_fp32_arith(a, b, len); +} + +template <> +void gemm_transa_( + TransposeType transa, + int64_t m, int64_t n, int64_t k, + float alpha, + const at::BFloat16 *a, int64_t lda, + const at::BFloat16 *b, int64_t ldb, + float beta, + at::BFloat16 *c, int64_t ldc) { + // c = alpha * (a.T @ b) + beta * c + parallel_for(0, m, 1, [&](int64_t begin, int64_t end) { + const auto *a_ = a + begin * lda; + for (const auto i : c10::irange(begin, end)) { + const auto *b_ = b; + for (const auto j : c10::irange(n)) { + const auto dot = compute_dot(a_, b_, k); + b_ += ldb; + if (beta == 0) { + c[j*ldc+i] = alpha*dot; + } else { + c[j*ldc+i] = beta*c[j*ldc+i]+alpha*dot; + } + } + a_ += lda; + } + }); +} +#endif // !defined(C10_MOBILE) + +template +void gemm_core_( + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + opmath_t alpha, + const scalar_t *a, int64_t lda, + const scalar_t *b, int64_t ldb, + opmath_t beta, + out_t *c, int64_t ldc) { + if (transa == TransposeType::NoTranspose && + transb == TransposeType::NoTranspose) { + return gemm_notrans_(m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else if ( + transa != TransposeType::NoTranspose && + transb == TransposeType::NoTranspose) { + gemm_transa_(transa, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else if ( + transa == TransposeType::NoTranspose && + transb != TransposeType::NoTranspose) { + gemm_transb_(transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } else { + gemm_transab_(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); + } +} + +#if !defined(C10_MOBILE) +#define _AT_DISPATCH_GEMM_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND6( \ + kHalf, kBFloat16, kFloat8_e5m2, kFloat8_e4m3fn, kFloat8_e5m2fnuz, kFloat8_e4m3fnuz, \ + TYPE, NAME, __VA_ARGS__) +#else +#define _AT_DISPATCH_GEMM_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( \ + kHalf, kBFloat16, \ + TYPE, NAME, __VA_ARGS__) +#endif +void cpublas_gemm_impl( + at::ScalarType type, + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const Scalar& alpha, + const void *a, int64_t lda, + const void *b, int64_t ldb, + const Scalar& beta, + void *c, int64_t ldc) { + _AT_DISPATCH_GEMM_TYPES(type, "cpublas_gemm_impl", [&]{ + using opmath_t = at::opmath_type; + gemm_core_( + transa, transb, m, n, k, + alpha.to(), + static_cast(a), lda, + static_cast(b), ldb, + beta.to(), + static_cast(c), ldc); + }); +} + +void cpublas_gemm_no_downcast_impl( + at::ScalarType type, + TransposeType transa, TransposeType transb, + int64_t m, int64_t n, int64_t k, + const Scalar& alpha, + const void *a, int64_t lda, + const void *b, int64_t ldb, + const Scalar& beta, + void *c, int64_t ldc) { +_AT_DISPATCH_GEMM_TYPES(type, "cpublas_gemm_no_downcast_impl", [&]{ + using opmath_t = at::opmath_type; + gemm_core_( + transa, transb, m, n, k, + alpha.to(), + static_cast(a), lda, + static_cast(b), ldb, + beta.to(), + static_cast(c), ldc); + }); +} + +void cpublas_axpy_impl(at::ScalarType type, int64_t n, const Scalar& _a, const void *_x, int64_t incx, void *_y, int64_t incy){ + if (type == at::kBool) { + auto a = _a.to(); + auto x = static_cast(_x); + auto y = static_cast(_y); + int64_t i; + for(i = 0; i < n; i++) + y[i*incy] |= a & x[i*incx]; + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(at::kHalf, at::kBFloat16, type, "cpublas_axpy_impl", + [&] { + using opmath_t = at::opmath_type; + auto a = _a.to(); + auto x = static_cast(_x); + auto y = static_cast(_y); + int64_t i; + for(i = 0; i < n; i++) + y[i*incy] += a*x[i*incx]; + }); + } +} + +void cpublas_copy_impl(at::ScalarType type, int64_t n, const void *_x, int64_t incx, void *_y, int64_t incy){ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND4(at::kComplexHalf, at::kHalf, at::kBFloat16, at::kBool, type, "cpublas_copy_impl", + [&] { + auto x = static_cast(_x); + auto y = static_cast(_y); + int64_t i; + for(i = 0; i < n; i++) + y[i*incy] = x[i*incx]; + }); +} + +}} // namespace cpublas::(anonymous) + + +REGISTER_DISPATCH(cpublas::gemm_stub, &cpublas::cpublas_gemm_impl) +REGISTER_DISPATCH(cpublas::gemm_no_downcast_stub, &cpublas::cpublas_gemm_no_downcast_impl) +REGISTER_DISPATCH(cpublas::axpy_stub, &cpublas::cpublas_axpy_impl) +REGISTER_DISPATCH(cpublas::copy_stub, &cpublas::cpublas_copy_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CatKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CatKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83bede65b474a3beff7129fd06fa5ab3ca35216e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CatKernel.cpp @@ -0,0 +1,83 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +struct InputMeta { + const void* data_ptr; + int64_t inner_size; + + InputMeta(const Tensor& t, int64_t dim, int64_t inner) + : data_ptr(t.const_data_ptr()), inner_size(t.sizes()[dim] * inner) {} +}; + +template +void cat_serial_kernel_impl( + const Tensor& result, + const MaterializedITensorListRef& tensors, + int64_t dim) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + dim >= 0 && dim < result.dim(), + "dim out of range in cat_serial_kernel_impl"); + int64_t outer = + result.numel() / (result.sizes()[dim] * result.strides()[dim]); + scalar_t* result_data = result.data_ptr(); + int64_t ninputs = static_cast(tensors.size()); + std::vector inputs; + inputs.reserve(ninputs); + for (const Tensor& tensor : tensors) { + inputs.emplace_back(tensor, dim, result.strides()[dim]); + } + + using Vec = vec::Vectorized; + scalar_t* result_ptr = result_data; + for (const auto i : c10::irange(outer)) { + for (const auto j : c10::irange(ninputs)) { + int64_t local_inner = inputs[j].inner_size; + const scalar_t* input_ptr = + (const scalar_t*)(inputs[j].data_ptr) + i * local_inner; + int64_t d = 0; + for (; d < local_inner - (local_inner % Vec::size()); d += Vec::size()) { + Vec in_vec = Vec::loadu(input_ptr + d); + in_vec.store(result_ptr + d); + } +#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) +#pragma unroll +#endif + for (; d < local_inner; d++) { + result_ptr[d] = input_ptr[d]; + } + result_ptr += local_inner; + } + } +} + +void cat_serial_kernel( + const Tensor& result, + const MaterializedITensorListRef& tensors, + int64_t dim) { + AT_DISPATCH_V2( + result.scalar_type(), + "cat_serial_kernel", + AT_WRAP( + [&]() { cat_serial_kernel_impl(result, tensors, dim); }), + AT_EXPAND(AT_FLOATING_TYPES), + kBFloat16, + kHalf, + AT_EXPAND(AT_FLOAT8_TYPES)); +} + +} // anonymous namespace + +REGISTER_DISPATCH(cat_serial_stub, &cat_serial_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CatKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CatKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..e4f43b4624c9eeb6a4de8039db8546e1c261ae25 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CatKernel.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include +#include + +namespace at::native { + +using cat_serial_fn = void(*)(const Tensor &, const MaterializedITensorListRef&, int64_t); +DECLARE_DISPATCH(cat_serial_fn, cat_serial_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ChannelShuffleKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ChannelShuffleKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bbeade56eac3fee4857820ff76a9513d447026a1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ChannelShuffleKernel.cpp @@ -0,0 +1,116 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void cpu_channel_shuffle( + TensorBase& output, + const TensorBase& input, + int64_t groups) { + auto input_data = input.data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t channels_per_group = channels / groups; + int64_t image_size = input.numel() / nbatch / channels; + + // treat input tensor as shape of [n, g, oc, ...] + // output tensor as shape of [n, oc, g, ...] + // + // 3d, 4d, 5d: parallel on dimension of n, c + using Vec = vec::Vectorized; + int64_t inner_size = image_size - (image_size % Vec::size()); + at::parallel_for (0, nbatch * /* oc*g */channels, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oc = 0; + int64_t g = 0; + data_index_init(begin, n, nbatch, oc, channels_per_group, g, groups); + + for (const auto i : c10::irange(begin, end)) { + scalar_t* output_ptr = output_data + i * image_size; + scalar_t* input_ptr = input_data + n * channels * image_size + + g * channels_per_group * image_size + oc * image_size; + + int64_t d = 0; + for (; d < inner_size; d += Vec::size()) { + Vec data_vec = Vec::loadu(input_ptr + d); + data_vec.store(output_ptr + d); + } + for (; d < image_size; d++) { + output_ptr[d] = c10::load(&(input_ptr[d])); + } + + // move on to next output index + data_index_step(n, nbatch, oc, channels_per_group, g, groups); + } + }); +} + +template +void cpu_channel_shuffle_cl( + TensorBase& output, + const TensorBase& input, + int64_t groups) { + auto input_data = input.data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t channels_per_group = channels / groups; + int64_t image_size = input.numel() / nbatch / channels; + + // 4d: parallel on dimension of n, h, w + // 5d: parallel on dimension of n, d, h, w + at::parallel_for(0, nbatch * image_size, 0, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + scalar_t* output_ptr = output_data + i * channels; + scalar_t* input_ptr = input_data + i * channels; + + // transpose each channel lane: + // from [groups, channels_per_group] to [channels_per_group, groups] + utils::transpose(groups, channels_per_group, input_ptr, channels_per_group, output_ptr, groups); + } + }); +} + +void channel_shuffle_kernel_impl( + TensorBase& output, + const TensorBase& input, + int64_t groups) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, + input.scalar_type(), "channel_shuffle", [&] { + cpu_channel_shuffle(output, input, groups); + }); + break; + } + case at::MemoryFormat::ChannelsLast: + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, + input.scalar_type(), "channel_shuffle_cl", [&] { + cpu_channel_shuffle_cl(output, input, groups); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, ChannelsLast3d, Contiguous"); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(channel_shuffle_kernel, &channel_shuffle_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ChannelShuffleKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ChannelShuffleKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..355d27bb306c490a84c4cf293a3f2c56e3829248 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ChannelShuffleKernel.h @@ -0,0 +1,14 @@ +#pragma once +#include +#include + +namespace at { +class TensorBase; +} + +namespace at::native { + +using channel_shuffle_fn = void(*)(TensorBase&, const TensorBase&, int64_t); +DECLARE_DISPATCH(channel_shuffle_fn, channel_shuffle_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ComplexKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ComplexKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..062bcd795627ad79410f53cc6230387d39f3e3b3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ComplexKernel.cpp @@ -0,0 +1,31 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +namespace at::native { +namespace { + +void complex_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND(kHalf, iter.input_dtype(), "complex_cpu", [&]() { + cpu_kernel(iter, [=](scalar_t a, scalar_t b) -> c10::complex { + return c10::complex(a, b); + }); + }); +} + +void polar_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES(iter.input_dtype(), "polar_cpu", [&]() { + cpu_kernel(iter, [=](scalar_t a, scalar_t b) -> c10::complex { + return c10::complex(a * std::cos(b), a * std::sin(b)); + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(complex_stub, &complex_kernel) +ALSO_REGISTER_AVX512_DISPATCH(polar_stub, &polar_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CopyKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CopyKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09075a314a13c0924ebcf03dfb9ac53ce536ad35 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CopyKernel.cpp @@ -0,0 +1,330 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace at::native { +inline namespace CPU_CAPABILITY { + +namespace { +bool reduced_input(ScalarType input_t, ScalarType output_t) { + return !at::isFloat8Type(input_t) && at::isReducedFloatingType(input_t) && + output_t == kFloat; +} + +bool reduced_output(ScalarType input_t, ScalarType output_t) { + return !at::isFloat8Type(output_t) && at::isReducedFloatingType(output_t) && + input_t == kFloat; +} +} // namespace + +static bool reduced_float_type_copy( + bool requires_conj, + TensorIteratorBase& iter) { + auto strides_out = iter.strides(0); + auto strides_in = iter.strides(1); + + // Check whether input is in BFloat16/Half data type and output is in float + // data type, or input is in float data type and output is in BFloat16/Half + // data type. In addition, input and output need contiguous parts to utilize + // vectorization. + return ( + !requires_conj && + ((reduced_input(iter.dtype(1), iter.dtype(0)) && + sizeof(float) == strides_out[0] && + (static_cast(elementSize(iter.dtype(1))) == strides_in[0] || + strides_in[0] == 0)) || + (reduced_output(iter.dtype(1), iter.dtype(0)) && + static_cast(elementSize(iter.dtype(0))) == strides_out[0] && + (sizeof(float) == strides_in[0] || strides_in[0] == 0)))); +} + +static void reduced_float_copy_kernel(TensorIteratorBase &iter, bool requires_neg) { + auto strides_out = iter.strides(0); + auto strides_in = iter.strides(1); + auto shape = iter.shape(); + c10::SmallBuffer strides(2 * std::max(iter.ndim(), 2)); + auto get_strides = [](int64_t* strides, IntArrayRef strides_out, IntArrayRef strides_in, int64_t ndim) { + for (const auto dim : c10::irange(ndim)) { + for (const auto arg : c10::irange(2)) { + *strides++ = arg == 0? strides_out[dim] : strides_in[dim]; + } + } + // Always at least 2d strides to support 2d for_each loops + if (ndim < 2) { + std::fill_n(strides, (2 - ndim) * 2, 0); + } + }; + get_strides(strides.data(), strides_out, strides_in, iter.ndim()); + if (reduced_input(iter.dtype(1), iter.dtype(0))) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(1), "copy_kernel", [&]() { + using dest_t = float; + using Vecd = Vectorized; + using Vecs = Vectorized; + c10::SmallBuffer ptrs(2); + dest_t* output_data = iter.tensor_base(0).data_ptr(); + scalar_t* input_data = const_cast(iter.tensor_base(1).const_data_ptr()); + ptrs[0] = reinterpret_cast(output_data); + ptrs[1] = reinterpret_cast(input_data); + + int64_t grain_size = at::internal::GRAIN_SIZE; + + auto loop = [strides_in, requires_neg](char** data, const int64_t* strides, int64_t size0, int64_t size1) { + const int64_t *outer_strides = &strides[2]; + + for ([[maybe_unused]] const auto it : c10::irange(size1)) { + Vecd dst_s; + if (strides_in[0] == 0) { + dst_s = Vecd(dest_t(*((scalar_t*)data[1]))); + if (requires_neg) { + dst_s = dst_s.neg(); + } + } + int64_t i = 0; + for (; i <= size0 - Vecs::size(); i += Vecs::size()) { + if (strides_in[0] != 0) { + Vecs data_vec = Vecs::loadu(data[1] + i * sizeof(scalar_t)); + auto [data_vec0, data_vec1] = convert_to_float(data_vec); + if (requires_neg) { + data_vec0 = data_vec0.neg(); + data_vec1 = data_vec1.neg(); + } + data_vec0.store(data[0] + i * sizeof(dest_t)); + data_vec1.store(data[0] + (i + Vecd::size()) * sizeof(dest_t)); + } else { + dst_s.store(data[0] + i * sizeof(dest_t)); + dst_s.store(data[0] + (i + Vecd::size()) * sizeof(dest_t)); + } + } + if (i < size0) { + if (strides_in[0] != 0) { + Vecs data_vec = Vecs::loadu(data[1] + i * sizeof(scalar_t), size0 - i); + auto [data_vec0, data_vec1] = convert_to_float(data_vec); + if (requires_neg) { + data_vec0 = data_vec0.neg(); + data_vec1 = data_vec1.neg(); + } + data_vec0.store(data[0] + i * sizeof(dest_t), ((size0 - i) > Vecd::size())? Vecd::size() : (size0 - i)); + data_vec1.store(data[0] + (i + Vecd::size()) * sizeof(dest_t), ((size0 - i) > Vecd::size())? (size0 - i - Vecd::size()) : 0); + } else { + dst_s.store(data[0] + i * sizeof(dest_t), ((size0 - i) > Vecd::size())? Vecd::size() : (size0 - i)); + dst_s.store(data[0] + (i + Vecd::size()) * sizeof(dest_t), ((size0 - i) > Vecd::size())? (size0 - i - Vecd::size()) : 0); + } + } + data[0] += outer_strides[0]; + data[1] += outer_strides[1]; + } + + }; + + parallel_for(0, iter.numel(), grain_size, [&] (int64_t begin, int64_t end) { + at::internal::serial_for_each(shape, strides, ptrs.data(), 2, loop, {begin, end}); + }); + }); + } else if (reduced_output(iter.dtype(1), iter.dtype(0))) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(iter.dtype(0), "copy_kernel", [&]() { + using dest_t = scalar_t; + using source_t = float; + using Vecd = Vectorized; + using Vecs = Vectorized; + c10::SmallBuffer ptrs(2); + dest_t* output_data = iter.tensor_base(0).data_ptr(); + source_t* input_data = const_cast(iter.tensor_base(1).const_data_ptr()); + + ptrs[0] = reinterpret_cast(output_data); + ptrs[1] = reinterpret_cast(input_data); + + int64_t grain_size = at::internal::GRAIN_SIZE; + + auto loop = [strides_in, requires_neg](char** data, const int64_t* strides, int64_t size0, int64_t size1) { + const int64_t *outer_strides = &strides[2]; + + for ([[maybe_unused]] const auto it : c10::irange(size1)) { + Vecd dst_s; + if (strides_in[0] == 0) { + dst_s = Vecd(dest_t(*((source_t*)data[1]))); + if (requires_neg) { + dst_s = dst_s.neg(); + } + } + int64_t i = 0; + for (; i <= size0 - 2 * Vecs::size(); i += 2 * Vecs::size()) { + if (strides_in[0] != 0) { + Vecs data_vec0 = Vecs::loadu(data[1] + i * sizeof(source_t)); + Vecs data_vec1 = Vecs::loadu(data[1] + (i + Vecs::size()) * sizeof(source_t)); + auto data_vec = convert_from_float(data_vec0, data_vec1); + if (requires_neg) { + data_vec = data_vec.neg(); + } + data_vec.store(data[0] + i * sizeof(dest_t)); + } else { + dst_s.store(data[0] + i * sizeof(dest_t)); + } + + } + if (i < size0) { + if (strides_in[0] != 0) { + Vecs data_vec0 = Vecs::loadu(data[1] + i * sizeof(source_t), ((size0 - i) > Vecs::size())? Vecs::size() : (size0 - i)); + Vecs data_vec1 = Vecs::loadu(data[1] + (i + Vecs::size()) * sizeof(source_t), ((size0 - i) > Vecs::size())? (size0 - i - Vecs::size()) : 0); + auto data_vec = convert_from_float(data_vec0, data_vec1); + if (requires_neg) { + data_vec = data_vec.neg(); + } + data_vec.store(data[0] + i * sizeof(dest_t), size0 - i); + } else { + dst_s.store(data[0] + i * sizeof(dest_t), size0 - i); + } + } + data[0] += outer_strides[0]; + data[1] += outer_strides[1]; + } + + }; + parallel_for(0, iter.numel(), grain_size, [&] (int64_t begin, int64_t end) { + at::internal::serial_for_each(shape, strides, ptrs.data(), 2, loop, {begin, end}); + }); + }); + + } +} + +#if !defined(C10_MOBILE) +#define _AT_DISPATCH_ALL_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_V2(TYPE, NAME, AT_WRAP(__VA_ARGS__), \ + kComplexHalf, kBComplex32, kHalf, kBool, \ + kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), \ + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)) +#define _AT_DISPATCH_ALL_TYPES_NO_CF(TYPE, NAME, ...) \ + AT_DISPATCH_V2(TYPE, NAME, AT_WRAP(__VA_ARGS__), \ + kBool, kHalf, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), \ + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)) +#else +#define _AT_DISPATCH_ALL_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5( \ + ScalarType::ComplexHalf, ScalarType::BComplex32, ScalarType::Half, ScalarType::Bool,ScalarType::BFloat16, \ + TYPE, NAME, __VA_ARGS__) +#define _AT_DISPATCH_ALL_TYPES_NO_CF(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( \ + kBool, kHalf, kBFloat16, \ + TYPE, NAME, __VA_ARGS__) +#endif + +void direct_copy_kernel(TensorIteratorBase &iter) { + // TODO: we don't actually need separate instantiations per dtype; + // we only need a separate instantiation per dtype size. This would + // probably save us a little bit of code size here + // TODO: not sure if optimizer is able to compile two levels of + // conditionals into a single jump table. We should have a + // single jump table here; might be worth just writing out the + // dispatch statement by hand instead of using AT_DISPATCH + ScalarType dtype = iter.dtype(0); + if (isQIntType(dtype)) { + AT_DISPATCH_QINT_TYPES(dtype, "copy_kernel", [&] { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return a; }, + [=](Vectorized a) -> Vectorized { return a; }); + }); + } else if (dtype == ScalarType::ComplexHalf) { + cpu_kernel(iter, [=](c10::complex a) -> c10::complex { return a; }); + } else if (dtype == ScalarType::BComplex32) { + cpu_kernel(iter, [=](c10::complex a) -> c10::complex { return a; }); + } else if (dtype == ScalarType::Float4_e2m1fn_x2) { + cpu_kernel(iter, [=](Float4_e2m1fn_x2 a) -> Float4_e2m1fn_x2 { return a; }); + } else if (isBitsType(dtype)) { + AT_DISPATCH_BIT_TYPES(dtype, "copy_kernel", [&] { + cpu_kernel( + iter, + [=](scalar_t a) -> scalar_t { return a; }); + }); + } else { + _AT_DISPATCH_ALL_TYPES_NO_CF(dtype, "copy_kernel", [&] { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return a; }, + [=](Vectorized a) -> Vectorized { return a; }); + }); + } +} + +static void neg_conj_kernel(TensorIteratorBase &iter) { + // fused a = b.neg().conj_physical() + AT_DISPATCH_COMPLEX_TYPES(iter.common_dtype(), "neg_conj_cpu", [&] { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return -conj_impl(a); }, + [=](Vectorized a) -> Vectorized { return a.neg().conj(); }); + }); +} + +static void copy_same_dtype(TensorIteratorBase &iter, bool requires_conj, bool requires_neg) { + if (requires_neg) { + // This case should never actually happen since currently there's no way to get a complex tensor + // with negative bit. + if (requires_conj) { + neg_conj_kernel(iter); + } else { + neg_kernel(iter); + } + } else { + if (requires_conj) { + conj_kernel(iter); + } else { + direct_copy_kernel(iter); + } + } +} + +void copy_kernel(TensorIterator& iter, bool /*non_blocking*/) { + ScalarType dtype = iter.dtype(0); + const bool requires_conj = ( + isComplexType(dtype) && (iter.tensor_base(0).is_conj() != iter.tensor_base(1).is_conj())); + const bool requires_neg = (iter.tensor_base(0).is_neg() != iter.tensor_base(1).is_neg()); + + if (dtype == iter.dtype(1)) { + copy_same_dtype(iter, requires_conj, requires_neg); + } else if (reduced_float_type_copy(requires_conj, iter)) { + reduced_float_copy_kernel(iter, requires_neg); + } else { + _AT_DISPATCH_ALL_TYPES(dtype, "copy_", [&] { + using dest_t = scalar_t; + _AT_DISPATCH_ALL_TYPES(iter.dtype(1), "copy_", [&] { + if (iter.has_contiguous_first_dim()) { + TORCH_INTERNAL_ASSERT(iter.ninputs() == 1); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + + iter.for_each([](char **data, const int64_t *strides, int64_t size) { + auto src = reinterpret_cast(data[1]); + auto dst = reinterpret_cast(data[0]); + at::vec::convert(src, dst, size); + }); + } else { + cpu_kernel(iter, [](scalar_t x) -> dest_t { + return c10::convert(x); + }); + } + }); + }); + + if (requires_conj || requires_neg) { + // This inplace "copy" will perform any missing neg or conj operations + auto self = iter.tensor_base(0); + auto iter = TensorIterator::unary_op(self, self); + copy_same_dtype(iter, requires_conj, requires_neg); + } + } +} + +} // namespace CPU_CAPABILITY + +REGISTER_DISPATCH(copy_stub, ©_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CopyKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CopyKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..469f399ca637ae886fa93cf584d6b8c3b44f681f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CopyKernel.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace at { +struct TensorIteratorBase; + +namespace native { +inline namespace CPU_CAPABILITY { + +void direct_copy_kernel(TensorIteratorBase &iter); +void copy_kernel(TensorIterator& iter, bool /*non_blocking*/); + +}}} // namespace at::native::CPU_CAPABILITY diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CrossKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CrossKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd9d13f2311366f0c869259439a0d5858902d8ba --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/CrossKernel.cpp @@ -0,0 +1,81 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +namespace at::native { +namespace { + +template +void apply_cross(const Tensor& result, const Tensor& a, const Tensor& b, const int64_t dim) { + int64_t total = a.numel() / 3; + int64_t a_stride = a.stride(dim); + int64_t b_stride = b.stride(dim); + int64_t r_stride = result.stride(dim); + + const scalar_t *a_ptr = a.const_data_ptr(); + const scalar_t *b_ptr = b.const_data_ptr(); + scalar_t *r_ptr = result.data_ptr(); + + parallel_for(0, total, internal::GRAIN_SIZE, [&](int64_t s, int64_t e) { + const int64_t a_dim = a.dim(); + std::vector position_in_dims(a_dim); + int64_t index_in_curr_dim = s; + int64_t a_start = 0; + int64_t b_start = 0; + int64_t r_start = 0; + for (const auto i : c10::irange(a.dim())) { + if (i == dim) continue; + position_in_dims[i] = index_in_curr_dim % a.size(i); + a_start += (index_in_curr_dim % a.size(i)) * a.stride(i); + b_start += (index_in_curr_dim % b.size(i)) * b.stride(i); + r_start += (index_in_curr_dim % result.size(i)) * result.stride(i); + index_in_curr_dim = index_in_curr_dim / a.size(i); + } + + while (s < e) { + r_ptr[r_start+0*r_stride] = a_ptr[a_start+1*a_stride]*b_ptr[b_start+2*b_stride] - a_ptr[a_start+2*a_stride]*b_ptr[b_start+1*b_stride]; + r_ptr[r_start+1*r_stride] = a_ptr[a_start+2*a_stride]*b_ptr[b_start+0*b_stride] - a_ptr[a_start+0*a_stride]*b_ptr[b_start+2*b_stride]; + r_ptr[r_start+2*r_stride] = a_ptr[a_start+0*a_stride]*b_ptr[b_start+1*b_stride] - a_ptr[a_start+1*a_stride]*b_ptr[b_start+0*b_stride]; + s++; + + for (const auto i : c10::irange(a.dim())) { + if (i == dim) { + continue; + } + position_in_dims[i]++; + a_start += a.stride(i); + b_start += b.stride(i); + r_start += result.stride(i); + if (position_in_dims[i] == a.size(i) && i != a.dim()-1) { + a_start -= position_in_dims[i] * a.stride(i); + b_start -= position_in_dims[i] * b.stride(i); + r_start -= position_in_dims[i] * result.stride(i); + position_in_dims[i] = 0; + } else { + break; + } + } + } + }); +} + +void cross_kernel_impl(const Tensor& result, const Tensor& a, const Tensor& b, const int64_t dim) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, result.scalar_type(), "cross", [&]() { + apply_cross(result, a, b, dim); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(cross_stub, &cross_kernel_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DepthwiseConvKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DepthwiseConvKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50f82bcd5b7d0fb8db5fc6c4fb9c5e0e580321fa --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DepthwiseConvKernel.cpp @@ -0,0 +1,546 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +#ifdef __ARM_NEON__ +#include +#elif defined(__riscv_v_intrinsic) && __riscv_v_intrinsic>=12000 +#include +#endif + +namespace at::native { +namespace { + +struct Arguments final { + // Input layer dimensions + int64_t batch; + int64_t in_rows; + int64_t in_cols; + int64_t stride; + int64_t pad_rows; + int64_t pad_cols; + + // Output layer dimensions + int64_t out_rows; + int64_t out_cols; + int64_t out_channels; +}; + +inline std::vector calculate_conv_output_size( + const IntArrayRef input_size, + const IntArrayRef weight_size, + const IntArrayRef stride, + const IntArrayRef padding) { + const auto calc_output_dimension = []( + const int64_t input, const int64_t kernel, const int64_t stride, const int64_t padding) { + return 1 + (input - kernel + 2 * padding) / stride; + }; + + return std::vector { + input_size[0], + weight_size[0], + calc_output_dimension(input_size[2], weight_size[2], stride[0], padding[0]), + calc_output_dimension(input_size[3], weight_size[3], stride[1], padding[1]), + }; +} + +#ifdef __ARM_NEON__ + +inline void winograd_f2k3_input_transform_inplace__neon( + float32x4_t* const d0, + float32x4_t* const d1, + float32x4_t* const d2, + float32x4_t* const d3) { + const float32x4_t wd0 = *d0 - *d2; + const float32x4_t wd1 = *d1 + *d2; + const float32x4_t wd2 = -*d1 + *d2; + const float32x4_t wd3 = *d1 - *d3; + *d0 = wd0; + *d1 = wd1; + *d2 = wd2; + *d3 = wd3; +} + +inline void winograd_f2k3_output_transform_inplace__neon( + float32x4_t* const m0, + float32x4_t* const m1, + const float32x4_t* const m2, + const float32x4_t* const m3) { + *m0 = *m0 + *m1 + *m2; + *m1 = *m1 - *m2 - *m3; +} + +inline float32x4_t +vmuladdq_f32(const float32x4_t c, const float32x4_t a, const float32x4_t b) { +#if defined(__aarch64__) + return vfmaq_f32(c, a, b); +#else + return vmlaq_f32(c, a, b); +#endif +} + +inline float32x4_t +vmulsubq_f32(const float32x4_t c, const float32x4_t a, const float32x4_t b) { +#if defined(__aarch64__) + return vfmsq_f32(c, a, b); +#else + return vmlsq_f32(c, a, b); +#endif +} + +inline void winograd_f2k3_kernel_transform__neon( + const float32x4_t g0, + const float32x4_t g1, + const float32x4_t g2, + float32x4_t* const transform0, + float32x4_t* const transform1, + float32x4_t* const transform2, + float32x4_t* const transform3) { + const float32x4_t const_half = vdupq_n_f32(0.5f); + float32x4_t half_g0_plus_g2 = const_half * (g0 + g2); + *transform0 = g0; + *transform1 = vmuladdq_f32(half_g0_plus_g2, const_half, g1); + *transform2 = vmulsubq_f32(half_g0_plus_g2, const_half, g1); + *transform3 = g2; +} + +inline float32x4x4_t v4f_transpose4x4__neon(const float32x4x4_t m) { + float32x4x4_t ret; + vst4q_f32((float*)(&ret), m); + return ret; +} + +void convolution_depthwise3x3_winograd_impl( + const Arguments& args, + const float* const input, + const float* const kernel, + const float* const bias, + float* const output) { + const float32x4_t vbias = vsetq_lane_f32(*bias, vdupq_n_f32(0.0), 1); + float32x4x4_t kernel_tile; + + { + const float32x4_t g0 = vld1q_f32(kernel); + const float32x4_t g1 = vld1q_f32(kernel + 3); + // g2[3] is junk + const float32x4_t g2 = + vextq_f32(vld1q_f32(kernel + 5), vld1q_f32(kernel + 5), 1); + float32x4x4_t w; + winograd_f2k3_kernel_transform__neon( + g0, g1, g2, &w.val[0], &w.val[1], &w.val[2], &w.val[3]); + w = v4f_transpose4x4__neon(w); + + winograd_f2k3_kernel_transform__neon( + w.val[0], + w.val[1], + w.val[2], + &kernel_tile.val[0], + &kernel_tile.val[1], + &kernel_tile.val[2], + &kernel_tile.val[3]); + } + +#define TILE \ + winograd_f2k3_input_transform_inplace__neon( \ + &input_tile.val[0], \ + &input_tile.val[1], \ + &input_tile.val[2], \ + &input_tile.val[3]); \ + input_tile = v4f_transpose4x4__neon(input_tile); \ + winograd_f2k3_input_transform_inplace__neon( \ + &input_tile.val[0], \ + &input_tile.val[1], \ + &input_tile.val[2], \ + &input_tile.val[3]); \ + \ + for (const auto row : c10::irange(4)) { \ + input_tile.val[row] = \ + vmulq_f32(input_tile.val[row], kernel_tile.val[row]); \ + } \ + \ + input_tile.val[1] = input_tile.val[1] + vbias; \ + winograd_f2k3_output_transform_inplace__neon( \ + &input_tile.val[0], \ + &input_tile.val[1], \ + &input_tile.val[2], \ + &input_tile.val[3]); \ + input_tile = v4f_transpose4x4__neon(input_tile); \ + winograd_f2k3_output_transform_inplace__neon( \ + &input_tile.val[0], \ + &input_tile.val[1], \ + &input_tile.val[2], \ + &input_tile.val[3]) + + // Non-padded regime. + + // Iterate over non-padded output tiles. + // TODO: avoid spilling W by breaking out the non-padded vs padded case. + for (int64_t oth = 0; oth < (args.out_rows + 1) / 2; ++oth) { + for (int64_t otw = 0; otw < (args.out_cols + 1) / 2; ++otw) { + // load input tile for [oth, otw]; + int64_t ih = oth * 2 - args.pad_rows; + int64_t iw = otw * 2 - args.pad_cols; + // fast-path, all accesses in-bounds + if (C10_LIKELY( + ih >= 0 && iw >= 0 && ih + 3 < args.in_rows && + iw + 3 < args.in_cols && 2 * oth + 1 < args.out_rows && + 2 * otw + 1 < args.out_cols + )) { + float32x4x4_t input_tile; + for (const auto row : c10::irange(4)) { + input_tile.val[row] = + vld1q_f32(input + (ih + row) * args.in_cols + iw); + } + + TILE; + + for (const auto row : c10::irange(2)) { + vst1_f32( + output + (oth * 2 + row) * args.out_cols + otw * 2, + vget_low_f32(input_tile.val[row])); + } + } else { + float block[4][4]; + for (const auto row : c10::irange(4)) { + for (const auto col : c10::irange(4)) { + if (ih + row >= 0 && iw + col >= 0 && ih + row < args.in_rows && + iw + col < args.in_cols) { + block[row][col] = input[(ih + row) * args.in_cols + iw + col]; + } else { + block[row][col] = 0.0; + } + } + } + + float32x4x4_t input_tile; + for (const auto row : c10::irange(4)) { + input_tile.val[row] = vld1q_f32(&block[row][0]); + } + + TILE; + + float oblock[2][2]; + for (const auto row : c10::irange(2)) { + vst1_f32(&oblock[row][0], vget_low_f32(input_tile.val[row])); + } + for (const auto row : c10::irange(2)) { + for (const auto col : c10::irange(2)) { + if (2 * oth + row < args.out_rows && + 2 * otw + col < args.out_cols) { + output[(2 * oth + row) * args.out_cols + 2 * otw + col] = + oblock[row][col]; + } + } + } + } + } + } +} + +#elif defined(__riscv_v_intrinsic) && __riscv_v_intrinsic>=12000 + +inline void winograd_f2k3_input_transform_inplace__rvv( + vfloat32m1x4_t* input_tile_val) { + const vfloat32m1_t d0 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 0); + const vfloat32m1_t d1 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 1); + const vfloat32m1_t d2 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 2); + const vfloat32m1_t d3 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 3); + + const vfloat32m1_t wd0 = __riscv_vfsub_vv_f32m1(d0, d2, 4); + const vfloat32m1_t wd1 = __riscv_vfadd_vv_f32m1(d1, d2, 4); + const vfloat32m1_t wd2 = __riscv_vfsub_vv_f32m1(d2, d1, 4); + const vfloat32m1_t wd3 = __riscv_vfsub_vv_f32m1(d1, d3, 4); + /* GCC 14.2 (RISC-V RVV) ICE workaround: + * Avoid single-statement read-modify-write on MEM_REF like: + * *input_tile_val = + * __riscv_vset_v_f32m1_f32m1x4(*input_tile_val, idx, val); + * This triggers an ICE during GIMPLE lower (gsi_replace / riscv_gimple_fold_builtin) + * with -march=rv64gcv. Use a temporary then write back. + * Do NOT refactor into the single-statement form. Clang is unaffected. + */ + vfloat32m1x4_t tmp_input_tile_val = *input_tile_val; + tmp_input_tile_val = __riscv_vset_v_f32m1_f32m1x4(tmp_input_tile_val, 0, wd0); + tmp_input_tile_val = __riscv_vset_v_f32m1_f32m1x4(tmp_input_tile_val, 1, wd1); + tmp_input_tile_val = __riscv_vset_v_f32m1_f32m1x4(tmp_input_tile_val, 2, wd2); + tmp_input_tile_val = __riscv_vset_v_f32m1_f32m1x4(tmp_input_tile_val, 3, wd3); + *input_tile_val = tmp_input_tile_val; +} + +inline void winograd_f2k3_output_transform_inplace__rvv( + vfloat32m1x4_t* input_tile_val) { + const vfloat32m1_t m0 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 0); + const vfloat32m1_t m1 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 1); + const vfloat32m1_t m2 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 2); + const vfloat32m1_t m3 = __riscv_vget_v_f32m1x4_f32m1(*input_tile_val, 3); + + const vfloat32m1_t m0_plus_m1 = __riscv_vfadd_vv_f32m1(m0, m1, 4); + const vfloat32m1_t wm0 = __riscv_vfadd_vv_f32m1(m0_plus_m1, m2, 4); + const vfloat32m1_t m1_sub_m2 = __riscv_vfsub_vv_f32m1(m1, m2, 4); + const vfloat32m1_t wm1 = __riscv_vfsub_vv_f32m1(m1_sub_m2, m3, 4); + /* GCC 14.2 (RISC-V RVV) ICE workaround — see note above. + * Keep the temporary + write-back pattern to avoid ICE. + * Do NOT rewrite into: + * *input_tile_val = __riscv_vset_v_f32m1_f32m1x4(*input_tile_val, idx, val); + */ + vfloat32m1x4_t tmp_output_tile_val = *input_tile_val; + tmp_output_tile_val = __riscv_vset_v_f32m1_f32m1x4(tmp_output_tile_val, 0, wm0); + tmp_output_tile_val = __riscv_vset_v_f32m1_f32m1x4(tmp_output_tile_val, 1, wm1); + *input_tile_val = tmp_output_tile_val; +} + +inline vfloat32m1_t +vmuladdq_f32(const vfloat32m1_t c, const vfloat32m1_t a, const vfloat32m1_t b) { + return __riscv_vfmacc_vv_f32m1(c, a, b, 4); +} + +inline vfloat32m1_t +vmulsubq_f32(const vfloat32m1_t c, const vfloat32m1_t a, const vfloat32m1_t b) { + return __riscv_vfnmsac_vv_f32m1(c, a, b, 4); +} + +inline void winograd_f2k3_kernel_transform__rvv( + const vfloat32m1_t g0, + const vfloat32m1_t g1, + const vfloat32m1_t g2, + vfloat32m1x4_t* const transform) { + const vfloat32m1_t const_half = __riscv_vfmv_v_f_f32m1(0.5f, 4); + const vfloat32m1_t g0_plus_g2 = __riscv_vfadd_vv_f32m1(g0, g2, 4); + vfloat32m1_t half_g0_plus_g2 = __riscv_vfmul_vv_f32m1(const_half, g0_plus_g2, 4); + /* GCC 14.2 (RISC-V RVV) ICE workaround — see note above. + * Keep the temporary + write-back pattern to avoid ICE. + * Do NOT rewrite into: + * *transform = __riscv_vset_v_f32m1_f32m1x4(*transform, idx, val); + */ + vfloat32m1x4_t tmp_transform = *transform; + tmp_transform = __riscv_vset_v_f32m1_f32m1x4(tmp_transform, 0, g0); + tmp_transform = __riscv_vset_v_f32m1_f32m1x4(tmp_transform, 1, vmuladdq_f32(half_g0_plus_g2, const_half, g1)); + tmp_transform = __riscv_vset_v_f32m1_f32m1x4(tmp_transform, 2, vmulsubq_f32(half_g0_plus_g2, const_half, g1)); + tmp_transform = __riscv_vset_v_f32m1_f32m1x4(tmp_transform, 3, g2); + *transform = tmp_transform; +} + +inline vfloat32m1x4_t v4f_transpose4x4__rvv(const vfloat32m1x4_t m) { + vfloat32m1x4_t ret; + __riscv_vsseg4e32_v_f32m1x4((float*)(&ret), m, 4); + return ret; +} + +void convolution_depthwise3x3_winograd_impl( + const Arguments& args, + const float* const input, + const float* const kernel, + const float* const bias, + float* const output) { + + vbool32_t mask = __riscv_vreinterpret_v_u32m1_b32(__riscv_vmv_v_x_u32m1((uint32_t)(1 << 1),2)); + const vfloat32m1_t vbias = __riscv_vfmerge_vfm_f32m1(__riscv_vfmv_v_f_f32m1(0.0, 4), *bias, mask, 4); + vfloat32m1x4_t kernel_tile; + + { + const vfloat32m1_t g0 = __riscv_vle32_v_f32m1(kernel, 4); + const vfloat32m1_t g1 = __riscv_vle32_v_f32m1(kernel + 3, 4); + // g2[3] is junk + vfloat32m1_t a_slidedown = __riscv_vslidedown_vx_f32m1(__riscv_vle32_v_f32m1(kernel + 5, 4), 1, 4); + const vfloat32m1_t g2 = + __riscv_vslideup_vx_f32m1(a_slidedown, __riscv_vle32_v_f32m1(kernel + 5, 4), 3, 4); + vfloat32m1x4_t w; + + winograd_f2k3_kernel_transform__rvv( + g0, g1, g2, &w); + + w = v4f_transpose4x4__rvv(w); + + winograd_f2k3_kernel_transform__rvv( + __riscv_vget_v_f32m1x4_f32m1(w, 0), + __riscv_vget_v_f32m1x4_f32m1(w, 1), + __riscv_vget_v_f32m1x4_f32m1(w, 2), + &kernel_tile); + + } + +#define TILE \ + winograd_f2k3_input_transform_inplace__rvv( \ + &input_tile); \ + input_tile = v4f_transpose4x4__rvv(input_tile); \ + winograd_f2k3_input_transform_inplace__rvv( \ + &input_tile); \ + \ + for (const auto row : c10::irange(4)) { \ + vfloat32m1_t input_mul_kernel = \ + __riscv_vfmul_vv_f32m1( \ + __riscv_vle32_v_f32m1((float*)&input_tile + row * 4, 4), \ + __riscv_vle32_v_f32m1((float*)&kernel_tile + row * 4, 4), \ + 4); \ + __riscv_vse32_v_f32m1( \ + (float*)&input_tile + row * 4, \ + input_mul_kernel, \ + 4); \ + } \ + \ + vfloat32m1_t val = __riscv_vget_v_f32m1x4_f32m1(input_tile, 1); \ + vfloat32m1_t val_add_vbias = __riscv_vfadd_vv_f32m1(val, vbias, 4); \ + input_tile = __riscv_vset_v_f32m1_f32m1x4(input_tile, 1, val_add_vbias); \ + winograd_f2k3_output_transform_inplace__rvv( \ + &input_tile); \ + input_tile = v4f_transpose4x4__rvv(input_tile); \ + winograd_f2k3_output_transform_inplace__rvv( \ + &input_tile) + + // Non-padded regime. + + // Iterate over non-padded output tiles. + // TODO: avoid spilling W by breaking out the non-padded vs padded case. + for (int64_t oth = 0; oth < (args.out_rows + 1) / 2; ++oth) { + for (int64_t otw = 0; otw < (args.out_cols + 1) / 2; ++otw) { + // load input tile for [oth, otw]; + int64_t ih = oth * 2 - args.pad_rows; + int64_t iw = otw * 2 - args.pad_cols; + // fast-path, all accesses in-bounds + if (C10_LIKELY( + ih >= 0 && iw >= 0 && ih + 3 < args.in_rows && + iw + 3 < args.in_cols && 2 * oth + 1 < args.out_rows && + 2 * otw + 1 < args.out_cols + )) { + vfloat32m1x4_t input_tile; + for (const auto row : c10::irange(4)) { + __riscv_vse32_v_f32m1( + (float*)&input_tile + row * 4, + __riscv_vle32_v_f32m1(input + (ih + row) * args.in_cols + iw, 4), + 4); + } + + TILE; + + for (const auto row : c10::irange(2)) { + __riscv_vse32_v_f32m1( + output + (oth * 2 + row) * args.out_cols + otw * 2, + __riscv_vle32_v_f32m1((float*)&input_tile + row * 4, 2), + 2); + } + } else { + float block[4][4]; + for (const auto row : c10::irange(4)) { + for (const auto col : c10::irange(4)) { + if (ih + row >= 0 && iw + col >= 0 && ih + row < args.in_rows && + iw + col < args.in_cols) { + block[row][col] = input[(ih + row) * args.in_cols + iw + col]; + } else { + block[row][col] = 0.0; + } + } + } + + vfloat32m1x4_t input_tile; + for (const auto row : c10::irange(4)) { + __riscv_vse32_v_f32m1( + (float*)&input_tile + row * 4, + __riscv_vle32_v_f32m1(&block[row][0], 4), + 4); + } + + TILE; + + float oblock[2][2]; + for (const auto row : c10::irange(2)) { + __riscv_vse32_v_f32m1( + &oblock[row][0], + __riscv_vle32_v_f32m1((float*)&input_tile + row * 4, 2), + 2); + } + for (const auto row : c10::irange(2)) { + for (const auto col : c10::irange(2)) { + if (2 * oth + row < args.out_rows && + 2 * otw + col < args.out_cols) { + output[(2 * oth + row) * args.out_cols + 2 * otw + col] = + oblock[row][col]; + } + } + } + } + } + } +} + +#else + +void convolution_depthwise3x3_winograd_impl( + const Arguments& /*unused*/, + const float* const /*unused*/, + const float* const /*unused*/, + const float* const /*unused*/, + float* const /*unused*/) { +} + +#endif /* __ARM_NEON__ */ + +Tensor _convolution_depthwise3x3_winograd( + const Tensor & input, + const Tensor & kernel, + const Tensor & bias_potentially_undefined, + const IntArrayRef stride, + const IntArrayRef padding, + const int64_t groups) +{ + const IntArrayRef input_sizes = input.sizes(); + const IntArrayRef kernel_sizes = kernel.sizes(); + + Tensor output = at::empty( + calculate_conv_output_size(input_sizes, kernel_sizes, stride, padding), + input.options()); + + const IntArrayRef output_sizes = output.sizes(); + + const Arguments args { + input_sizes[0], // Input N + input_sizes[2], // Input H + input_sizes[3], // Input W + stride[0], // Stride + padding[0], // Padding Rows + padding[1], // Padding Columns + output_sizes[2], // Output H + output_sizes[3], // Output W + output_sizes[1], // Output C + }; + + const int64_t input_hxw = args.in_rows * args.in_cols; + const int64_t output_hxw = args.out_rows * args.out_cols; + + const Tensor bias = bias_potentially_undefined.defined() ? + bias_potentially_undefined : + at::zeros({kernel_sizes[0]}, input.options()); + + auto input_data = input.const_data_ptr(); + auto kernel_data = kernel.const_data_ptr(); + auto bias_data = bias.const_data_ptr(); + auto output_data = output.data_ptr(); + + at::parallel_for(0, args.batch * args.out_channels, 0, [&](int64_t start, int64_t end) { + for (const auto k : c10::irange(start, end)) { + const int64_t g = k % args.out_channels; + const int64_t i = k / (args.out_channels / groups); + convolution_depthwise3x3_winograd_impl( + args, + input_data + i * input_hxw, + kernel_data + g * 3 * 3, + bias_data + g, + output_data + k * output_hxw); + } + }); + + return output; +} + +} // namespace + +ALSO_REGISTER_AVX512_DISPATCH(convolution_depthwise3x3_winograd_stub, &_convolution_depthwise3x3_winograd) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DepthwiseConvKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DepthwiseConvKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..09ee71a1310f5d8d2ca41520a7870dafa1f04eea --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DepthwiseConvKernel.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +/* + Depthwise 3x3 Winograd convolution operator +*/ + +namespace at { +class Tensor; + +namespace native { + +using convolution_depthwise3x3_winograd_fn = + Tensor (*)(const Tensor &, const Tensor &, const Tensor &, IntArrayRef, IntArrayRef, int64_t); + +DECLARE_DISPATCH(convolution_depthwise3x3_winograd_fn, convolution_depthwise3x3_winograd_stub) + +} // namespace native +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistanceOpsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistanceOpsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36e59918649dae9946346a3ea01538b2827d19ac --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistanceOpsKernel.cpp @@ -0,0 +1,450 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +template +struct Dist { + using Vec = vec::Vectorized; + + // Depending on the value of the pnorm, there are specific implementations + // that are much faster than std::pow(std::abs(a - b), p), but have the same + // standard loop code for how to process the input vector. To reuse the main + // outside loop while still guaranteeing that the compiler inlines every + // different function on p, we break the inner norm logic into structs with + // static functions that represent what's done differently, and template the + // outer loop on those structs. + // + // The four functions are: + // map : This tells how to modify (a - b) to form the component that + // gets summed. + // red : This tells how to sum the result of map up. This is + // separate because the inf norm actually uses max instead of + // sum. + // finish : This tells what to do with the aggregated value to compute + // the norm. Generally this is the result of val ^ (1 / p). + // backward : This is the gradient for that norm. Arguments are pretty + // self explanatory. + // + // There are a few cases where these aren't used. The 0 norm has no backward, + // because it's always 0, so that's shortcircuited earlier. There's a special + // implementation of the general backward pass when p is less than two, so + // there's a struct with only a backward pass for this case. + + // TODO This is an inefficient way to compite sign, and can be much faster + // using native SSE instructions that should be added to Vectorized. + static inline Vec sign(Vec val) { + return vec::minimum(vec::maximum(Vec(0), val.ceil()), Vec(1)) + + vec::minimum(vec::maximum(Vec(-1), val.floor()), Vec(0)); + } + + static inline Vec abs(Vec val) { + return val.abs(); + } + + static inline scalar_t abs(scalar_t val) { + return std::abs(val); + } + + static inline Vec ceil(Vec val) { + return val.ceil(); + } + + static inline scalar_t ceil(scalar_t val) { + return std::ceil(val); + } + + static inline Vec min(Vec val, scalar_t other) { + return vec::minimum(val, Vec(other)); + } + + static inline scalar_t min(scalar_t val, scalar_t other) { + return std::min(val, other); + } + + static inline Vec max(Vec val, Vec other) { + return vec::maximum(val, other); + } + + static inline scalar_t max(scalar_t val, scalar_t other) { + return std::max(val, other); + } + + static inline Vec pow(Vec val, Vec p) { + return val.pow(p); + } + + static inline scalar_t pow(scalar_t val, scalar_t p) { + return std::pow(val, p); + } + + // Zero norm + template + struct zdist_calc { + static inline data_t map(const data_t& diff, const data_t& p) { return min(ceil(abs(diff)), 1); } + static inline data_t red(const data_t& agg, const data_t& up) { return agg + up; } + static inline scalar_t finish(const scalar_t agg, const scalar_t /*p*/) { return agg; } + }; + + // One norm + template + struct odist_calc { + static inline data_t map(const data_t& diff, const data_t& p) { return diff; } + static inline data_t red(const data_t& agg, const data_t& up) { return agg + up; } + static inline scalar_t finish(const scalar_t agg, const scalar_t /*p*/) { return agg; } + static inline Vec backward(const Vec& diff, const scalar_t grad, const scalar_t /*dist*/, const Vec& /*p*/) { return Vec(grad) * sign(diff); } + }; + + // Special general pnorm derivative if p is less than two + struct lttdist_calc { + static inline Vec backward(const Vec& diff, const scalar_t grad, const scalar_t dist, const Vec& p) { + Vec result = (dist == 0.0) ? Vec(0) : (sign(diff) * diff.abs().pow(p - Vec(1)) * Vec(grad) / Vec(dist).pow(p - Vec(1))); + result = Vec::blendv(result, Vec(0), (diff == Vec(0)) & (p < Vec(1))); + return result; + } + }; + + // Two norm + template + struct tdist_calc { + // TODO This can probably use fused add multiply to get better perf + static inline data_t map(const data_t& diff, const data_t& p) { return diff * diff; } + static inline data_t red(const data_t& agg, const data_t& up) { return agg + up; } + static inline scalar_t finish(const scalar_t agg, const scalar_t p) { return std::sqrt(agg); } + static inline Vec backward(const Vec& diff, const scalar_t grad, const scalar_t dist, const Vec& p) { return dist == 0.0 ? Vec(0) : Vec(grad) * diff / Vec(dist); } + }; + + // General p norm + template + struct pdist_calc { + static inline data_t map(const data_t& diff, const data_t& p) { return pow(diff, p); } + static inline data_t red(const data_t& agg, const data_t& up) { return agg + up; } + static inline scalar_t finish(const scalar_t agg, const scalar_t p) { return std::pow(agg, 1.0 / p); } + static inline Vec backward(const Vec& diff, const scalar_t grad, const scalar_t dist, const Vec& p) { return dist == 0.0 ? Vec(0) : diff * diff.abs().pow(p - Vec(2)) * Vec(grad) / Vec(dist).pow(p - Vec(1)); } + }; + + // Inf norm + template + struct idist_calc { + static inline data_t map(const data_t& diff, const data_t& p) { return diff; } + static inline data_t red(const data_t& agg, const data_t& up) { return max(agg, up); } + static inline scalar_t finish(const scalar_t agg, const scalar_t p) { return agg; } + // TODO This backward pass uses a very complex expression to compute (diff + // == dist) that could be much faster if using SSE instructions. + static inline Vec backward(const Vec& diff, const scalar_t grad, const scalar_t dist, const Vec& p) { return Vec(grad) * sign(diff) * (Vec(1) - vec::minimum(Vec(1), (diff.abs() - Vec(dist)).abs().ceil())); } + }; + + template + static void run_parallel_pdist(Tensor& result, const Tensor& self, const scalar_t p) { + const scalar_t * const self_start = self.const_data_ptr(); + const scalar_t * const self_end = self_start + self.numel(); + int64_t n = self.size(0); + int64_t m = self.size(1); + + scalar_t * const res_start = result.data_ptr(); + int64_t combs = result.numel(); // n * (n - 1) / 2 + + // We conceptually iterate over tuples of (i, j, k) where i is the first + // vector from the input, j is the second, and k is the result index. This + // parallelizes over the range of k and infers what i and j are from the + // value of k. + parallel_for(0, combs, internal::GRAIN_SIZE / (16 * m), [p, self_start, self_end, n, m, res_start](int64_t k, int64_t end) { + const Vec pvec(p); + double n2 = static_cast(n) - .5; + // The -1 accounts for floating point truncation issues + int64_t i = static_cast((n2 - std::sqrt(n2 * n2 - 2.0 * static_cast(k) - 1.0))); + int64_t j = k - n * i + i * (i + 1) / 2 + i + 1; + + const scalar_t * self_i = self_start + i * m; + const scalar_t * self_j = self_start + j * m; + scalar_t * res = res_start + k; + const scalar_t * const res_end = res_start + end; + + while (res != res_end) { + *res = F::finish(vec::map2_reduce_all( + [&pvec](Vec a, Vec b) { return F::map((a - b).abs(), pvec); }, + F::red, self_i, self_j, m), p); + + res += 1; + self_j += m; + if (self_j == self_end) { + self_i += m; + self_j = self_i + m; + } + } + }); + } + + // Assumes self is nonempty, contiguous, and 2D + static void apply_pdist(Tensor& result, const Tensor& self, const scalar_t p) { + if (p == 0.0) { + run_parallel_pdist>(result, self, p); + } else if (p == 1.0) { + run_parallel_pdist>(result, self, p); + } else if (p == 2.0) { + run_parallel_pdist>(result, self, p); + } else if (std::isinf(p)) { + run_parallel_pdist>(result, self, p); + } else { + run_parallel_pdist>(result, self, p); + } + } + + template + static void run_parallel_cdist(Tensor& result, const Tensor& t1, const Tensor& t2, const scalar_t p) { + const scalar_t * const t1_start = t1.const_data_ptr(); + const scalar_t * const t2_start = t2.const_data_ptr(); + int64_t d = t1.size(0); + int64_t r1 = t1.size(-2); + int64_t r2 = t2.size(-2); + int64_t m = t1.size(-1); + + scalar_t * const res_start = result.data_ptr(); + int64_t combs = r1 * r2; + int64_t size1 = r1 * m; + int64_t size2 = r2 * m; + + parallel_for(0, combs * d, internal::GRAIN_SIZE / (16 * m), [=](int64_t start, int64_t end) { + scalar_t * res = res_start + start; + const scalar_t * const res_end = res_start + end; + int64_t l = start / combs; + int64_t k = start % combs; + int64_t i = k / r2; + int64_t j = k % r2; + i = i * m; + j = j * m; + + while (res != res_end) { + const scalar_t * self_i = t1_start + size1 * l + i; + const scalar_t * self_j = t2_start + size2 * l + j; + + scalar_t agg = 0; + for (const auto x : c10::irange(m)) { + scalar_t a = *(self_i + x); + scalar_t b = *(self_j + x); + agg = F::red(agg, F::map(std::abs(a-b), p)); + } + *res = F::finish(agg, p); + + res += 1; + j += m; + if (j == size2) { + j = 0; + i += m; + if (i == size1) { + i = 0; + l += 1; + } + } + } + }); + } + + static void apply_cdist(Tensor& result, const Tensor& x1, const Tensor& x2, const scalar_t p) { + if (p == 0.0) { + run_parallel_cdist>(result, x1, x2, p); + } else if (p == 1.0) { + run_parallel_cdist>(result, x1, x2, p); + } else if (p == 2.0) { + run_parallel_cdist>(result, x1, x2, p); + } else if (std::isinf(p)) { + run_parallel_cdist>(result, x1, x2, p); + } else { + run_parallel_cdist>(result, x1, x2, p); + } + } + + // This does a backward pass down a Vec column of the input + template + static void backward_down_column_pdist(const scalar_t * self_i, scalar_t * res_i, const scalar_t * grad_k, const scalar_t * dist_k, const Vec& pvec, int64_t n, int64_t m, int64_t gs, int64_t count = Vec::size()) { + for (const scalar_t * const self_end = self_i + m * n; self_i != self_end - m; self_i += m, res_i += m) { + + const Vec self_vec_i = Vec::loadu(self_i, count); + Vec res_vec_i = Vec::loadu(res_i, count); + + const scalar_t * self_j = self_i + m; + scalar_t * res_j = res_i + m; + for (; self_j != self_end; self_j += m, res_j += m, grad_k += gs, dist_k += 1) { + const Vec self_vec_j = Vec::loadu(self_j, count); + Vec res_vec_j = Vec::loadu(res_j, count); + + Vec res = F::backward(self_vec_i - self_vec_j, *grad_k, *dist_k, pvec); + res_vec_i = res_vec_i + res; + res_vec_j = res_vec_j - res; + + res_vec_j.store(res_j, count); + } + + res_vec_i.store(res_i, count); + } + } + + template + static void run_backward_parallel_pdist(Tensor& result, const Tensor & grad, const Tensor & self, const scalar_t p, const Tensor& dist) { + const int64_t n = self.size(0); + const int64_t m = self.size(1); + const int64_t gs = grad.stride(0); + + const scalar_t * const grad_start = grad.const_data_ptr(); + const scalar_t * const dist_start = dist.const_data_ptr(); + const scalar_t * const self_start = self.const_data_ptr(); + scalar_t * const res_start = result.data_ptr(); + + // The only way to parallelize and avoid locking requires parallelizing + // over the columns of the input, i.e. we compute the gradient for the + // first section of each vector independently of the second section, etc. + at::parallel_for(0, m / Vec::size(), internal::GRAIN_SIZE / (8 * n * n), [p, n, m, gs, grad_start, dist_start, self_start, res_start](int64_t l, int64_t end) { + const Vec pvec(p); + + const scalar_t * self_l = self_start + l * Vec::size(); + scalar_t * res_l = res_start + l * Vec::size(); + + for (const scalar_t * const res_end = res_start + end * Vec::size(); res_l != res_end; self_l += Vec::size(), res_l += Vec::size()) { + backward_down_column_pdist(self_l, res_l, grad_start, dist_start, pvec, n, m, gs); + } + }); + const int64_t remainder = m % Vec::size(); + if (remainder) { + backward_down_column_pdist(self_start + (m - remainder), res_start + (m - remainder), grad_start, dist_start, Vec(p), n, m, gs, remainder); + } + } + + // Assumes self is nonempty, contiguous, and 2D and dist is also contiguous + static void apply_backward_pdist(Tensor& result, const Tensor& grad, const Tensor& self, const double p, const Tensor& dist) { + result.fill_(0); + if (p == 0.0) { + } else if (p == 1.0) { + run_backward_parallel_pdist>(result, grad, self, p, dist); + } else if (p < 2.0) { + run_backward_parallel_pdist(result, grad, self, p, dist); + } else if (p == 2.0) { + run_backward_parallel_pdist>(result, grad, self, p, dist); + } else if (std::isinf(p)) { + run_backward_parallel_pdist>(result, grad, self, p, dist); + } else { + run_backward_parallel_pdist>(result, grad, self, p, dist); + } + } + + static void apply_backward_cdist(Tensor& result, const Tensor& grad, const Tensor& x1, const Tensor& x2, const double p, const Tensor& dist) { + result.fill_(0); + if (p == 0.0) { + } else if (p == 1.0) { + run_backward_parallel_cdist>(result, grad, x1, x2, p, dist); + } else if (p < 2.0) { + run_backward_parallel_cdist(result, grad, x1, x2, p, dist); + } else if (p == 2.0) { + run_backward_parallel_cdist>(result, grad, x1, x2, p, dist); + } else if (std::isinf(p)) { + run_backward_parallel_cdist>(result, grad, x1, x2, p, dist); + } else { + run_backward_parallel_cdist>(result, grad, x1, x2, p, dist); + } + } + + + template + static void run_backward_parallel_cdist(Tensor& result, const Tensor & grad, const Tensor & t1, const Tensor & t2, const scalar_t p, const Tensor& dist) { + const int64_t r1 = t1.size(-2); + const int64_t r2 = t2.size(-2); + const int64_t m = t1.size(-1); + const int64_t d = result.size(0); + const int64_t l1_size = r1 * m; + const int64_t l2_size = r2 * m; + //current implementation supports only tensor that can be collapsed to 1D. However, to avoid checking if grad satisfies this assumption, + //we call .contiguous() on grad before backward, thus stride is guaranteed to be 1 + //don't use grad.stride(-1), because if last dimension is 1, stride can be bogus. + const int64_t gs = 1; + + const scalar_t * const grad_start = grad.const_data_ptr(); + const scalar_t * const dist_start = dist.const_data_ptr(); + const scalar_t * const t1_start = t1.const_data_ptr(); + const scalar_t * const t2_start = t2.const_data_ptr(); + scalar_t * const res_start = result.data_ptr(); + + at::parallel_for(0, m / Vec::size(), internal::GRAIN_SIZE / (16 * r1), [=](int64_t l, int64_t end) { + const Vec pvec(p); + + const scalar_t * i = t1_start + l * Vec::size(); + const scalar_t * j = t2_start + l * Vec::size(); + scalar_t * res_l = res_start + l * Vec::size(); + + for (const scalar_t * const res_end = res_start + end * Vec::size(); res_l != res_end; i += Vec::size(), j += Vec::size(), res_l += Vec::size()) { + backward_down_column_cdist(i, j, res_l, grad_start, dist_start, pvec, r1, r2, m, d, gs, l1_size, l2_size); + } + }); + const int64_t remainder = m % Vec::size(); + if (remainder) { + backward_down_column_cdist(t1_start + (m - remainder), t2_start + (m - remainder), res_start + (m - remainder), grad_start, dist_start, Vec(p), r1, r2, m, d, gs, l1_size, l2_size, remainder); + } + } + + template + static void backward_down_column_cdist(const scalar_t * t1, const scalar_t * t2, scalar_t * res, const scalar_t * grad_k, const scalar_t * dist_k, const Vec& pvec, int64_t r1, int64_t r2, int64_t m, int64_t d, int64_t gs, int64_t l1_size, int64_t l2_size, int64_t count = Vec::size()) { + const scalar_t * t1_end = t1 + l1_size; + const scalar_t * t2_end = t2 + l2_size; + + for ([[maybe_unused]] const auto l : c10::irange(d)) { + for (; t1 != t1_end; t1 += m, res += m) { + const Vec vec_t1 = Vec::loadu(t1, count); + Vec res_vec = Vec::loadu(res, count); + + for (const scalar_t * t2_curr = t2; t2_curr != t2_end; t2_curr += m, grad_k += gs, dist_k += 1) { + const Vec vec_t2 = Vec::loadu(t2_curr, count); + Vec res = F::backward(vec_t1 - vec_t2, *grad_k, *dist_k, pvec); + res_vec = res_vec + res; + } + + res_vec.store(res, count); + } + t1_end += l1_size; + t2_end += l2_size; + t2 += l2_size; + } + } + +}; + +void pdist_forward_kernel_impl(Tensor& result, const Tensor& self, const double p) { + AT_DISPATCH_FLOATING_TYPES(self.scalar_type(), "pdist", [&] { + Dist::apply_pdist(result, self, p); + }); +} + +void pdist_backward_kernel_impl(Tensor& result, const Tensor& grad, const Tensor& self, const double p, const Tensor& dist) { + AT_DISPATCH_FLOATING_TYPES(self.scalar_type(), "pdist_backward", [&] { + Dist::apply_backward_pdist(result, grad, self, p, dist); + }); +} + +void cdist_kernel_impl(Tensor& result, const Tensor& x1, const Tensor& x2, const double p) { + AT_DISPATCH_FLOATING_TYPES(result.scalar_type(), "cdist", [&] { + Dist::apply_cdist(result, x1, x2, p); + }); +} + +void cdist_backward_kernel_impl(Tensor& result, const Tensor& grad, const Tensor& x1, const Tensor& x2, const double p, const Tensor& dist) { + AT_DISPATCH_FLOATING_TYPES(result.scalar_type(), "cdist_backward", [&] { + Dist::apply_backward_cdist(result, grad, x1, x2, p, dist); + }); +} + + +} // anonymous namespace + +REGISTER_DISPATCH(pdist_forward_stub, &pdist_forward_kernel_impl) +REGISTER_DISPATCH(pdist_backward_stub, &pdist_backward_kernel_impl) +REGISTER_DISPATCH(cdist_stub, &cdist_kernel_impl) +REGISTER_DISPATCH(cdist_backward_stub, &cdist_backward_kernel_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistributionKernels.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistributionKernels.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3a11107c09a63261daaeef6acbc9ac3b20c2630 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistributionKernels.cpp @@ -0,0 +1,253 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include +#include +#include + +// Disable MKL rng until https://github.com/pytorch/pytorch/issues/132395 is addressed +#if AT_MKL_ENABLED() && defined(FBCODE_CAFFE2) +#include +#include +#endif + +namespace at::native { +namespace { + +void cauchy_kernel(TensorIteratorBase& iter, double median, double sigma, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::cauchy_kernel(iter, median, sigma, generator); +} + +void bernoulli_tensor_kernel(const TensorBase &self, const TensorBase &p_, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::bernoulli_kernel(self, p_, generator); +} + +// Disable MKL rng until https://github.com/pytorch/pytorch/issues/132395 is addressed +#if !AT_MKL_ENABLED() || (AT_MKL_ENABLED() && !defined(FBCODE_CAFFE2)) +void bernoulli_scalar_kernel_default(const TensorBase &self, double p, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::bernoulli_kernel(self, p, generator); +} + +void bernoulli_scalar_kernel(const TensorBase &self, double p, std::optional gen) { + bernoulli_scalar_kernel_default(self, p, gen); +} +#else +void bernoulli_scalar_kernel(const TensorBase &self, double p, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + int64_t seed; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + seed = generator->random(); + } + int64_t n = self.numel(); + bool contig = self.is_contiguous(); + + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half, + self.scalar_type(), "bernoulli_scalar_cpu_", [&] { + at::Tensor tmp_int_tensor; + if (std::is_same_v && contig) { + tmp_int_tensor = self; + } else { + tmp_int_tensor = at::empty(self.sizes(), self.options().dtype(at::kInt)); + } + + scalar_t *self_ptr = self.data_ptr(); + int *sample_int_ptr = tmp_int_tensor.data_ptr(); + + auto sample = [&](int64_t begin, int64_t end) { + int64_t len = end - begin; + if (len > 0) { + VSLStreamStatePtr stream; + vslNewStream(&stream, VSL_BRNG_MCG31, seed); + vslSkipAheadStream(stream, begin); + viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, len, + sample_int_ptr + begin, p); + vslDeleteStream(&stream); + + // vectorized copy if using buffer and contiguous, i.e., being non-int + // type and contiguous + if (!std::is_same_v && contig) { + scalar_t *self_seg = self_ptr + begin; + int* tmp_seg = sample_int_ptr + begin; + at::vec::convert(tmp_seg, self_seg, len); + } + } + }; + + parallel_for(0, n, /* grain_size= */ 800, sample); + + // copy_ if using buffer and non contiguous + if (!contig) { + OptionalTensorRef(self)->copy_(tmp_int_tensor); + } + }); +} +#endif + +void exponential_kernel_default(TensorIteratorBase& iter, double lambda, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::exponential_kernel(iter, lambda, generator); +} + +// Disable MKL rng until https://github.com/pytorch/pytorch/issues/132395 is addressed +#if (!AT_MKL_ENABLED() || defined(FBCODE_CAFFE2) || 1) +void exponential_kernel(TensorIteratorBase& iter, double lambda, std::optional gen) { + exponential_kernel_default(iter, lambda, gen); +} +#else +void exponential_kernel(TensorIteratorBase &iter, double lambda, std::optional gen) { + TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype()); + + Tensor self = iter.tensor(0); + if (lambda > 0 && !std::isinf(lambda) && !std::isnan(lambda)) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + int64_t seed; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + if (self.scalar_type() == at::kDouble) + seed = generator->random64(); + else + seed = generator->random(); + } + int64_t n = self.numel(); + bool contig = self.is_contiguous(); + + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "exponential_cpu", [&] { + at::Tensor tmp_tensor; + constexpr bool is_df = std::is_same_v || std::is_same_v; + if (is_df && contig) { + tmp_tensor = self; + } else if (std::is_same_v) { + tmp_tensor = at::empty(self.sizes(), self.options().dtype(at::kDouble)); + } else { + tmp_tensor = at::empty(self.sizes(), self.options().dtype(at::kFloat)); + } + + scalar_t *self_ptr = self.data_ptr(); + using tmp_scalar_t = typename std::conditional_t, double, float>; + tmp_scalar_t *sample_ptr = tmp_tensor.data_ptr(); + + // Intel MKL vRngExponential variate originally does not exclude 0. + // However, to align with pytorch exponential variate definition which excludes 0, + // we shift the MKL vRngExponential distribution location by adding a very small constant, eps. + // If X ~ Exp(lambda), then E(X) = 1/lambda, and V(X) = 1/lambda**2. + // If Y = X + eps, where eps ~= 0, then E(Y) = (1/lambda) + eps, and V(Y) = 1/lambda**2. + // If eps is very small, the two distributions are indistinguishable, and are almost identical. + // The detail of location-shifted MKL vRngExponential is as follows. + // PDF: f(x) = lambda * exp( -lambda * (x - eps) ) + // CDF: F(x) = 1 - exp( -lambda * (x - eps) ) + // Mean: E[X+eps] = (1/lambda) + eps + // Variance: V[X+eps] = 1/lambda**2 + auto eps = std::numeric_limits::min(); + + auto sample = [&](int64_t begin, int64_t end) { + int64_t len = end - begin; + if (len > 0) { + VSLStreamStatePtr stream; + if constexpr (std::is_same_v) { + vslNewStream(&stream, VSL_BRNG_MCG31, seed); + vslSkipAheadStream(stream, begin); + vdRngExponential(VSL_RNG_METHOD_EXPONENTIAL_ICDF, stream, len, + (double *)(sample_ptr + begin), eps, 1./lambda); + vslDeleteStream(&stream); + } else { + vslNewStream(&stream, VSL_BRNG_MCG31, seed); + vslSkipAheadStream(stream, begin); + vsRngExponential(VSL_RNG_METHOD_EXPONENTIAL_ICDF, stream, len, + (float *) (sample_ptr + begin), eps, 1./lambda); + vslDeleteStream(&stream); + } + // vectorized copy if using buffer and contiguous + if (!is_df && contig) { + scalar_t *self_seg = self_ptr + begin; + tmp_scalar_t *tmp_seg = sample_ptr + begin; + at::vec::convert(tmp_seg, self_seg, len); + } + } + }; + + parallel_for(0, n, /* grain_size= */ 800, sample); + + // copy_ if using buffer and non contiguous + if (!contig) { + self.copy_(tmp_tensor); + } + }); + } else { + // The situation of inf and nan, move to using the default version + exponential_kernel_default(iter, lambda, gen); + } +} +#endif + +void geometric_kernel(TensorIteratorBase& iter, double p, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::geometric_kernel(iter, p, generator); +} + +void log_normal_kernel(TensorIteratorBase& iter, double mean, double std, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::log_normal_kernel(iter, mean, std, generator); +} + +void uniform_kernel(TensorIteratorBase& iter, double from, double to, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::uniform_kernel(iter, from, to, generator); +} + +void normal_kernel(const TensorBase &self, double mean, double std, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::normal_kernel(self, mean, std, generator); +} + +void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::random_from_to_kernel(iter, range, base, generator); +} + +void random_kernel(TensorIteratorBase& iter, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::random_kernel(iter, generator); +} + +// This is the special kernel to handle single specific case: +// from(inclusive) = std::numeric_limits::lowest() +// to(exclusive) = None (= std::numeric_limits::max() + 1) +void random_full_64_bits_range_kernel(TensorIteratorBase& iter, std::optional gen) { + CPUGeneratorImpl* generator = get_generator_or_default(gen, detail::getDefaultCPUGenerator()); + templates::cpu::random_full_64_bits_range_kernel(iter, generator); +} + +} // namespace (anonymous) + +REGISTER_DISPATCH(bernoulli_tensor_stub, &bernoulli_tensor_kernel) +REGISTER_DISPATCH(bernoulli_scalar_stub, &bernoulli_scalar_kernel) +REGISTER_DISPATCH(cauchy_stub, &cauchy_kernel) +REGISTER_DISPATCH(exponential_stub, &exponential_kernel) +REGISTER_DISPATCH(geometric_stub, &geometric_kernel) +REGISTER_DISPATCH(log_normal_stub, &log_normal_kernel) +REGISTER_DISPATCH(normal_stub, &normal_kernel) +REGISTER_DISPATCH(uniform_stub, &uniform_kernel) +REGISTER_DISPATCH(random_from_to_stub, &random_from_to_kernel) +REGISTER_DISPATCH(random_full_64_bits_range_stub, &random_full_64_bits_range_kernel) +REGISTER_DISPATCH(random_stub, &random_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistributionTemplates.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistributionTemplates.h new file mode 100644 index 0000000000000000000000000000000000000000..56c3780175a289e8360c8885d5bb27895c8667ec --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/DistributionTemplates.h @@ -0,0 +1,411 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CPU_CAPABILITY_AVX2 +#include +#include +#endif + + + + +namespace at::native::templates::cpu { +namespace { + +// ==================================================== Random ======================================================== + +template +void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, RNG generator) { + AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cpu", AT_WRAP([&] { + std::lock_guard lock(generator->mutex_); + cpu_serial_kernel(iter, [range, base, generator]() -> scalar_t { + uniform_int_from_to_distribution random(range, base); + return random(generator); + }); + }), kBool, kHalf, kBFloat16, AT_EXPAND(AT_ALL_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)); +} + +// This is the special kernel to handle single specific case: +// from(inclusive) = std::numeric_limits::lowest() +// to(exclusive) = None (= std::numeric_limits::max() + 1) +template +void random_full_64_bits_range_kernel(TensorIteratorBase& iter, RNG generator) { + AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::BFloat16, iter.dtype(), "random_full_64_bits_range_kernel_cpu", [&] { + if constexpr (std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v) { + std::lock_guard lock(generator->mutex_); + cpu_serial_kernel(iter, [generator]() -> scalar_t { + uniform_int_full_range_distribution random; + return random(generator); + }); + } else { + TORCH_CHECK(false, "random_full_64_bits_range_kernel_cpu handles only int64, double, float and bfloat16"); + } + }); +} + +template +struct RandomFromToKernel { + void operator()(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional gen) { + random_from_to_kernel(iter, range, base, check_generator(gen)); + } + void operator()(TensorIteratorBase& iter, std::optional gen) { + random_full_64_bits_range_kernel(iter, check_generator(gen)); + } +}; + +template +void random_kernel(TensorIteratorBase& iter, RNG generator) { + std::lock_guard lock(generator->mutex_); + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "random_kernel_cpu", [&] { + cpu_serial_kernel(iter, [generator]() -> scalar_t { + uniform_int_distribution random; + return random(generator); + }); + }); +} + +template +struct RandomKernel { + void operator()(TensorIteratorBase& iter, std::optional gen) { + random_kernel(iter, check_generator(gen)); + } +}; + +// ==================================================== Normal ======================================================== + +// Box-Muller transform on 16 elements (8 pairs of uniforms). +// Primary template is scalar; float specialization uses SIMD when available. +// Constructed once with mean/std so constants are not rebuilt per call. +template +struct NormalFill16 { + opmath_t mean_; + opmath_t std_; + + NormalFill16(opmath_t mean, opmath_t std) + : mean_(mean), std_(std) {} + + void operator()(opmath_t* data) const { + for (const auto j : c10::irange(8)) { + const opmath_t u1 = 1 - data[j]; // [0, 1) -> (0, 1] for log. + const opmath_t u2 = data[j + 8]; + const opmath_t radius = std::sqrt(-2 * std::log(u1)); + const opmath_t theta = 2.0f * c10::pi * u2; + data[j] = std::fma(radius * std::cos(theta), std_, mean_); + data[j + 8] = std::fma(radius * std::sin(theta), std_, mean_); + } + } +}; + +#if defined(CPU_CAPABILITY_AVX2) + +template <> +struct NormalFill16 { + __m256 mean_; + __m256 std_; + __m256 two_pi_ = _mm256_set1_ps(2.0f * c10::pi); + __m256 one_ = _mm256_set1_ps(1.0f); + __m256 minus_two_ = _mm256_set1_ps(-2.0f); + + NormalFill16(float mean, float std) + : mean_(_mm256_set1_ps(mean)), std_(_mm256_set1_ps(std)) {} + + void operator()(float* data) const { + const __m256 u1 = _mm256_sub_ps(one_, _mm256_loadu_ps(data)); + const __m256 u2 = _mm256_loadu_ps(data + 8); + // sincos256_ps and log256_ps are from avx_mathfun.h + const __m256 radius = _mm256_sqrt_ps(_mm256_mul_ps(minus_two_, log256_ps(u1))); + const __m256 theta = _mm256_mul_ps(two_pi_, u2); + __m256 sintheta, costheta; + sincos256_ps(theta, &sintheta, &costheta); + const __m256 n1 = _mm256_mul_ps(radius, costheta); + const __m256 n2 = _mm256_mul_ps(radius, sintheta); + _mm256_storeu_ps(data, _mm256_fmadd_ps(n1, std_, mean_)); + _mm256_storeu_ps(data + 8, _mm256_fmadd_ps(n2, std_, mean_)); + } +}; + +#elif defined(__VSX__) || defined(CPU_CAPABILITY_VSX) + +template <> +struct NormalFill16::size() == 8> { + using Vec = Vectorized; + Vec mean_; + Vec std_; + Vec two_pi_ = Vec(2.0f * c10::pi); + Vec one_ = Vec(1.0f); + Vec minus_two_ = Vec(-2.0f); + + NormalFill16(float mean, float std) + : mean_(mean), std_(std) {} + + void operator()(float* data) const { + Vec u1 = one_ - Vec::loadu(data); + Vec u2 = Vec::loadu(data + 8); + Vec radius = (minus_two_ * u1.log()).sqrt(); + Vec theta = two_pi_ * u2; + Vec output1 = radius * theta.cos() * std_ + mean_; + Vec output2 = radius * theta.sin() * std_ + mean_; + output1.store(data); + output2.store(data + 8); + } +}; + +#endif + +template +void normal_fill(const TensorBase &self, double mean, double std, RNG generator) { + using opmath_t = at::opmath_type; + scalar_t *data = self.data_ptr(); + auto size = self.numel(); + std::lock_guard lock(generator->mutex_); + at::uniform_real_distribution uniform(0, 1); + NormalFill16 normal_fill_16( + static_cast(mean), static_cast(std)); + + if constexpr (std::is_same_v) { + // float/double: generate uniform samples directly into the output buffer, + // then apply Box-Muller in-place. + for (const auto i : c10::irange(size)) { + data[i] = uniform(generator); + } + for (int64_t i = 0; i < size - 15; i += 16) { + normal_fill_16(data + i); + } + // Recompute the last 16 values. + if (size % 16 != 0) { + data = data + size - 16; + for (const auto i : c10::irange(16)) { + data[i] = uniform(generator); + } + normal_fill_16(data); + } + } else { + // bf16/fp16: generate in opmath_t precision using a stack buffer, + // apply Box-Muller, then cast down to scalar_t. + opmath_t buf[16]; + for (int64_t i = 0; i < size - 15; i += 16) { + for (const auto j : c10::irange(16)) { + buf[j] = uniform(generator); + } + normal_fill_16(buf); + for (const auto j : c10::irange(16)) { + data[i + j] = static_cast(buf[j]); + } + } + // Recompute the last 16 values. + if (size % 16 != 0) { + int64_t offset = size - 16; + for (const auto j : c10::irange(16)) { + buf[j] = uniform(generator); + } + normal_fill_16(buf); + for (const auto j : c10::irange(16)) { + data[offset + j] = static_cast(buf[j]); + } + } + } +} + +template +void normal_kernel(const TensorBase &self, double mean, double std, RNG generator) { + auto size = self.numel(); + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, self.scalar_type(), "normal_kernel_cpu", [&] { + if (size >= 16 && self.is_contiguous()) { + normal_fill(self, mean, std, generator); + } else { + auto iter = TensorIterator::borrowing_nullary_op(self); + std::lock_guard lock(generator->mutex_); + cpu_serial_kernel(iter, [mean, std, generator]() -> scalar_t { + at::normal_distribution normal(mean, std); + return static_cast(normal(generator)); + }); + } + }); +} + +template +struct NormalKernel { + void operator()(Tensor& self, double mean, double std, std::optional gen) { + normal_kernel(self, mean, std, check_generator(gen)); + } +}; + +// ==================================================== Uniform ======================================================= + +template +void uniform_kernel(TensorIteratorBase& iter, double from_, double to_, RNG generator) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "uniform_kernel_cpu", [&]() { + std::lock_guard lock(generator->mutex_); + using opmath_t = at::opmath_type; + auto from = static_cast(from_); + auto to = static_cast(to_); + auto to_scalar = static_cast(to_); + auto from_scalar = static_cast(from_); + at::uniform_real_distribution uniform(from, to); + cpu_serial_kernel(iter, [&uniform, generator, to_scalar, from_scalar]() -> scalar_t { + auto value = static_cast(uniform(generator)); + // Clamp if the float→scalar_t cast rounded up to the upper bound + return value == to_scalar ? from_scalar : value; + }); + }); +} + +template +struct UniformKernel { + void operator()(TensorIteratorBase& iter, double from, double to, std::optional gen) { + uniform_kernel(iter, from, to, check_generator(gen)); + } +}; + +// ==================================================== Cauchy ======================================================== + +template +void cauchy_kernel(TensorIteratorBase& iter, double median, double sigma, RNG generator) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "cauchy_cpu", [&]() { + std::lock_guard lock(generator->mutex_); + at::cauchy_distribution cauchy(median, sigma); + cpu_serial_kernel(iter, [&cauchy, generator]() -> scalar_t { + return static_cast(cauchy(generator)); + }); + }); +} + +template +struct CauchyKernel { + void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional gen) { + cauchy_kernel(iter, median, sigma, check_generator(gen)); + } +}; + +// ================================================== LogNormal ======================================================= + +template +void log_normal_kernel(TensorIteratorBase& iter, double mean, double std, RNG generator) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "log_normal_cpu", [&]() { + std::lock_guard lock(generator->mutex_); + at::lognormal_distribution logNormal(mean, std); + cpu_serial_kernel(iter, [&logNormal, generator]() -> scalar_t { + return static_cast(logNormal(generator)); + }); + }); +} + +template +struct LogNormalKernel { + void operator()(TensorIteratorBase& iter, double mean, double std, std::optional gen) { + log_normal_kernel(iter, mean, std, check_generator(gen)); + } +}; + +// =================================================== Geometric ====================================================== + +template +void geometric_kernel(TensorIteratorBase& iter, double p, RNG generator) { + AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "geometric_cpu", [&]() { + std::lock_guard lock(generator->mutex_); + at::geometric_distribution geometric(p); + cpu_serial_kernel(iter, [&geometric, generator]() -> scalar_t { + return static_cast(geometric(generator)); + }); + }); +} + +template +struct GeometricKernel { + void operator()(TensorIteratorBase& iter, double p, std::optional gen) { + geometric_kernel(iter, p, check_generator(gen)); + } +}; + +// ================================================== Exponential ===================================================== + +template +void exponential_kernel(TensorIteratorBase& iter, double lambda, RNG generator) { + TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype()); + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "exponential_cpu", [&]() { + std::lock_guard lock(generator->mutex_); + at::exponential_distribution exponential(lambda); + cpu_serial_kernel(iter, [&exponential, generator]() -> scalar_t { + return static_cast(exponential(generator)); + }); + }); +} + +template +struct ExponentialKernel { + void operator()(TensorIteratorBase& iter, double lambda, std::optional gen) { + exponential_kernel(iter, lambda, check_generator(gen)); + } +}; + +// ================================================== Bernoulli ======================================================= + +template +void bernoulli_kernel(const TensorBase &self, const TensorBase &p_, RNG generator) { + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half, + self.scalar_type(), "bernoulli_tensor_cpu_self_", [&] { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + using self_t = scalar_t; + auto p_cpu = p_.to(kCPU); + auto p = expand_inplace(self, p_cpu); + auto iter = TensorIteratorConfig() + .add_output(self) + .add_const_input(*p) + .check_all_same_dtype(false) + .build(); + if (p->scalar_type() == kDouble) { + cpu_serial_kernel(iter, [&](const double p_val) -> self_t { + at::bernoulli_distribution bernoulli(p_val); + return static_cast(bernoulli(generator)); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, + p->scalar_type(), "bernoulli_tensor_cpu_p_", [&] { + using p_t = scalar_t; + cpu_serial_kernel(iter, [&](const p_t p_val) -> self_t { + at::bernoulli_distribution bernoulli(p_val); + return static_cast(bernoulli(generator)); + }); + }); + } + }); +} + +template +void bernoulli_kernel(const TensorBase &self, double p, RNG generator) { + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::BFloat16, at::ScalarType::Half, + self.scalar_type(), "bernoulli_scalar_cpu_", [&] { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(generator->mutex_); + auto iter = TensorIterator::borrowing_nullary_op(self); + cpu_serial_kernel(iter, [p, generator]() -> scalar_t { + at::bernoulli_distribution bernoulli(p); + return static_cast(bernoulli(generator)); + }); + }); +} + +template +struct BernoulliKernel { + void operator()(const TensorBase &self, double p, std::optional gen) { + bernoulli_kernel(self, p, check_generator(gen)); + } + void operator()(const TensorBase &self, const TensorBase &p_, std::optional gen) { + bernoulli_kernel(self, p_, check_generator(gen)); + } +}; + +}} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Elu.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Elu.h new file mode 100644 index 0000000000000000000000000000000000000000..cf8f62782cc793ca3d885009c9bbb79a27692c34 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Elu.h @@ -0,0 +1,74 @@ +#pragma once + +// On Windows, math.h needs to be included with _USE_MATH_DEFINES defined to +// access constants such as M_SQRT2 and M_2_SQRTPI. +#ifdef _WIN32 +#define _USE_MATH_DEFINES +#include +#endif // _WIN32 + +#include +#include // For c10::is_reduced_floating_point_v. + +namespace at::native { +inline namespace CPU_CAPABILITY { +/** + * Return a function object that calculates ELU with the given + * parameters on its input element. ParamT is the type of the input + * and output to the ELU, and MathT is the type (possibly + * higher-precision, e.g. float if ParamT is reduced-precision float) + * in which to do intermediate calculations. + */ +template +auto get_scalar_elu_elementwise_func(MathT alpha, MathT scale, MathT input_scale) { + const auto negcoef = alpha * scale; + const auto poscoef = scale; + const auto negiptcoef = input_scale; + return [negcoef, negiptcoef, poscoef](ParamT a) -> ParamT { + return MathT(a) < MathT(0) + ? std::expm1(MathT(a) * negiptcoef) * negcoef + : MathT(a) * poscoef; + }; +} + +/** + * Return a function object that calculates ELU with the given + * parameters on its input element. The function object takes and + * returns Vectorized. + */ +template , bool> = true> +auto get_vectorized_elu_elementwise_func(T alpha, T scale, T input_scale) { + const vec::Vectorized negcoef_vec(alpha * scale); + const vec::Vectorized poscoef_vec(scale); + const vec::Vectorized negiptcoef_vec(input_scale); + const vec::Vectorized zero_vec(static_cast(0)); + return [negcoef_vec, poscoef_vec, negiptcoef_vec, zero_vec](vec::Vectorized a) -> vec::Vectorized { + const auto cmp = a >= zero_vec; + if (!cmp.zero_mask()) { + return a * poscoef_vec; + } else { + return vec::Vectorized::blendv((a * negiptcoef_vec).expm1() * negcoef_vec, a * poscoef_vec, cmp); + } + }; +} + +/** + * Return a function object that calculates ELU with the given + * parameters on its input element. The function object takes and + * returns Vectorized, and Vectorized is the type + * (possibly higher-precision) in which to do intermediate + * calculations. + */ +template , bool> = true> +auto get_vectorized_elu_elementwise_func(float alpha, float scale, float input_scale) { + // Takes float->float. + const auto float_func = get_vectorized_elu_elementwise_func(alpha, scale, input_scale); + return [float_func](vec::Vectorized a) -> vec::Vectorized { + auto [a0, a1] = vec::convert_to_float(a); + auto res0 = float_func(a0); + auto res1 = float_func(a1); + return vec::convert_from_float(res0, res1); + }; +} +} // namespace CPU_CAPABILITY +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FillKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FillKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0189c08c4ff18ad3a51bf47eedfde54a5288adbe --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FillKernel.cpp @@ -0,0 +1,75 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace at::native { +namespace { + + +template +void fill_non_native_type(TensorIterator& iter, const Scalar& value_scalar) { + auto value = value_scalar.to().x; + using H = typename std::make_signed_t; // Signed type has more acceleration + // Reserve the representation of value. static_cast(value) is implementation defined. + H val = *reinterpret_cast(std::addressof(value)); + cpu_kernel_vec( + iter, + [val]() -> H { return val; }, + [val]() { return Vectorized(val); }); +} + +template <> +void fill_non_native_type>(TensorIterator& iter, const Scalar& value_scalar) { + static_assert(sizeof(c10::complex) == sizeof(int32_t), "Size of ComplexHalf should be 32-bits"); + auto value = c10::complex(value_scalar.to>()); + auto val = *reinterpret_cast(std::addressof(value)); + cpu_kernel_vec( + iter, + [val]() -> int32_t { return val; }, + [val]() { return Vectorized(val); }); +} + +void fill_kernel(TensorIterator& iter, const Scalar& value_scalar) { + if (iter.dtype() == ScalarType::Half) { + fill_non_native_type(iter, value_scalar); + } else if (iter.dtype() == ScalarType::BFloat16) { + fill_non_native_type(iter, value_scalar); + } else if (iter.dtype() == ScalarType::ComplexHalf) { + fill_non_native_type>(iter, value_scalar); + } else if (iter.dtype() == ScalarType::Float8_e4m3fn) { + fill_non_native_type(iter, value_scalar); + } else if (iter.dtype() == ScalarType::Float8_e5m2) { + fill_non_native_type(iter, value_scalar); + } else if (iter.dtype() == ScalarType::Float8_e4m3fnuz) { + fill_non_native_type(iter, value_scalar); + } else if (iter.dtype() == ScalarType::Float8_e5m2fnuz) { + fill_non_native_type(iter, value_scalar); + } else if (iter.dtype() == ScalarType::Float8_e8m0fnu) { + // TODO(#146647): use macro here instead of spelling out each float8 dtype + fill_non_native_type(iter, value_scalar); + } else { + AT_DISPATCH_V2( + iter.dtype(), "fill_cpu", AT_WRAP([&]() { + scalar_t value = value_scalar.to(); + cpu_kernel_vec( + iter, + [=]() -> scalar_t { return value; }, + [=]() { return Vectorized(value); }); + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), kBool, AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES) + ); + } +} + +} // namespace + +REGISTER_DISPATCH(fill_stub, &fill_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FlashAttentionKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FlashAttentionKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3260ad8f6eb4b6113728e12f9cdee45870dc5d25 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FlashAttentionKernel.cpp @@ -0,0 +1,1277 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif +namespace at::native { + +namespace { + +// out = val * a + b +// is_b_stride_zero: If the stride of b is 0 (mask broadcasting case), +// take b as a scalar pointer. +#if __GNUC__ == 11 && defined(__ARM_FEATURE_SVE) +template +inline void _scale_attn_mask_fusion_kernel( + T1* a, + T2* b, + const int& size, + T1* out, + T1& val, + bool is_b_stride_zero) { +#else +template +inline void _scale_attn_mask_fusion_kernel( + T1* a, + T2* b, + const int& size, + T1* out, + T1& val) { +#endif + const auto vec_size1 = at::vec::Vectorized::size(); + const auto vec_size2 = at::vec::Vectorized::size(); + constexpr int64_t T1_n = + (vec_size2 == vec_size1 * 2 && is_reduced_floating_point_v) ? 2 : 1; + constexpr int64_t T2_n = 1; + auto vec_scale = at::vec::VectorizedN(val); + int64_t i = 0; + for (; i < size - (size % vec_size2); i += vec_size2) { + auto a_n = at::vec::VectorizedN::loadu(a + i); + at::vec::VectorizedN b_n; +#if __GNUC__ == 11 && defined(__ARM_FEATURE_SVE) + if (is_b_stride_zero) { +#else + if constexpr(is_b_stride_zero) { +#endif + b_n = at::vec::VectorizedN((T1)b[0]); + } else { + b_n = at::vec::VectorizedN::loadu(b + i); + } + auto b_n_convert = at::vec::convert(b_n); + auto res = a_n * vec_scale + b_n_convert; + res.store(out + i); + } + for (; i < size; i++) { + auto tmp0 = a[i]; + T1 tmp1; +#if __GNUC__ == 11 && defined(__ARM_FEATURE_SVE) + if (is_b_stride_zero) { +#else + if constexpr(is_b_stride_zero) { +#endif + tmp1 = (T1)b[0]; + } else { + tmp1 = (T1)b[i]; + } + out[i] = tmp0 * val + tmp1; + } +} + +// 1) out = exp(a - val) +// 2) val = sum(out) +template +inline void _exp_reduce_sum_fusion_kernel( + T1* a, + const int& size, + T2* out, + T1& val) { + constexpr auto vec_size1 = vec::Vectorized::size(); + constexpr auto vec_size2 = vec::Vectorized::size(); + constexpr int64_t T1_n = + (vec_size2 == vec_size1 * 2 && is_reduced_floating_point_v) ? 2 : 1; + constexpr int64_t T2_n = 1; + using Vec = vec::Vectorized; + using VecN = vec::VectorizedN; + + auto vec_max = VecN(val); + auto vec_max_tail = Vec(val); + T1 tmp_sum = 0; + auto vec_tmp_sum = VecN(tmp_sum); + auto vec_tmp_sum_tail = Vec(tmp_sum); + const long vec_end_n = vec_size2 * (size / vec_size2); + const long vec_end = vec_size1 * (size / vec_size1); + auto exp_vec = [](const auto& v) { + if constexpr ( + std::is_same_v && + (std::is_same_v || std::is_same_v)) { + return v.fexp_u20(); + } else { + return v.exp_u20(); + } + }; + + long i = 0; + for (; i < vec_end_n; i += vec_size2) { + auto tmp0 = VecN::loadu(a + i); + auto tmp1 = tmp0 - vec_max; + auto tmp2 = exp_vec(tmp1); + vec_tmp_sum = vec_tmp_sum + tmp2; + auto out_n = vec::convert(tmp2); + out_n.store(out + i); + } + for (; i < vec_end; i += vec_size1) { + auto tmp0 = Vec::loadu(a + i); + auto tmp1 = tmp0 - vec_max_tail; + auto tmp2 = exp_vec(tmp1); + vec_tmp_sum_tail = vec_tmp_sum_tail + tmp2; + _store(out + i, tmp2); + } + vec_tmp_sum[0] += vec_tmp_sum_tail; + tmp_sum = vec::vec_reduce_all( + [](vec::Vectorized& x, vec::Vectorized& y) { + return x + y; + }, + vec_tmp_sum); + for (long i = vec_end; i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 - val; + auto tmp2 = exp(tmp1); + tmp_sum += tmp2; + out[i] = tmp2; + } + val = tmp_sum; +} + +// 1) out = a * scale +// 2) max = max(out) +template +inline void _mul_reduce_max_fusion_kernel( + const scalar_t* a, + const scalar_t& scale, + const int& size, + scalar_t* out, + scalar_t& max) { + using Vec = vec::Vectorized; + using VecN = vec::VectorizedN; + constexpr auto vec_size = Vec::size(); + constexpr auto vec_size_n = VecN::size(); + auto vec_scale = VecN(scale); + scalar_t tmp_max = -std::numeric_limits::infinity(); + auto vec_tmp_max = VecN(tmp_max); + auto vec_tmp_max_tail = Vec(tmp_max); + const long vec_end_n = vec_size_n * (size / vec_size_n); + const long vec_end = vec_size * (size / vec_size); + long i = 0; + for (; i < vec_end_n; i += vec_size_n) { + auto tmp0 = VecN::loadu(a + i); + auto tmp1 = tmp0 * vec_scale; + vec_tmp_max = vec::maximum(vec_tmp_max, tmp1); + tmp1.store(out + i); + } + for (; i < vec_end; i += vec_size) { + auto tmp0 = Vec::loadu(a + i); + auto tmp1 = tmp0 * Vec(scale); + vec_tmp_max_tail = vec::maximum(vec_tmp_max_tail, tmp1); + _store(out + i, tmp1); + } + vec_tmp_max[0] = vec::maximum(vec_tmp_max[0], vec_tmp_max_tail); + for (; i < size; i++) { + auto tmp0 = a[i]; + auto tmp1 = tmp0 * scale; + tmp_max = std::max(tmp_max, tmp1); + out[i] = tmp1; + } + auto reduced_tmp_max = vec::vec_reduce_all( + [](vec::Vectorized& x, vec::Vectorized& y) { + return vec::maximum(x, y); + }, + vec_tmp_max); + // Guard against Q*K^T being NaN + max = std::isnan(reduced_tmp_max) ? std::numeric_limits::quiet_NaN() + : std::max(tmp_max, reduced_tmp_max); +} + +template +inline scalar_t* conditional_data_ptr(scalar_t* ptr, scalar_t* ptr2) { + TORCH_CHECK(ptr2 == nullptr); + return ptr; +} + +template , int> = 0> +inline scalar_t* conditional_data_ptr(float* ptr, scalar_t* ptr2) { + return ptr2; +} + +template +inline void fill_stub(scalar_t* data, scalar_t val, int64_t size) { + using Vec = Vectorized; + Vec data_vec = Vec(val); + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + data_vec.store(data + d); + } + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (; d < size; d++) { + data[d] = val; + } +} + +void reshape_attn_mask_to_4d( + Tensor& attn_mask, + int64_t batchSize, + int64_t num_head, + int64_t qSize, + int64_t kvSize) { + // Support mask shapes: + // 2d: ({Q_seq_len, 1} x {KV_seq_len, 1}) + // 4d: ({Batch, 1} x {Num_heads, 1} x {Q_seq_len, 1} x {KV_seq_len, 1}) + // Guaranteed in check_attn_mask_shape + int64_t attn_mask_size_0 = 1; + int64_t attn_mask_size_1 = 1; + if (attn_mask.dim() == 4) { + if (attn_mask.size(0) == batchSize) { + attn_mask_size_0 = batchSize; + } + if (attn_mask.size(1) == num_head) { + attn_mask_size_1 = num_head; + } + } + attn_mask = attn_mask + .view({attn_mask_size_0, attn_mask_size_1, attn_mask.size(-2), attn_mask.size(-1)}) + .expand({attn_mask_size_0, attn_mask_size_1, qSize, kvSize}); + if (attn_mask.sym_stride(-1) != 1 && attn_mask.sym_stride(-1) != 0) { + attn_mask = attn_mask.contiguous(); + } +} + +template +inline void copy_value_with_pad( + const scalar_t* value_ptr, + scalar_t* dst_ptr, + int64_t rows, + int64_t cols, + int64_t prows, + int64_t pcols, + int64_t ldi) { + auto vec_size = at::vec::Vectorized::size(); + int64_t i = 0; + for (; i < rows; i++) { + int64_t j = 0; + for (; j < cols - (cols % vec_size); j += vec_size) { + auto vec_v = + at::vec::Vectorized::loadu(value_ptr + i * ldi + j); + vec_v.store(dst_ptr + i * pcols + j); + } + + if (j < cols) { + auto vec_v = at::vec::Vectorized::loadu( + value_ptr + i * ldi + j, cols - j); + vec_v.store(dst_ptr + i * pcols + j, cols - j); + } + + // col padding + auto psize = pcols - cols; + if (psize > 0) { + auto zero_vec = at::vec::Vectorized(0); + int64_t pj = 0; + for (; pj < psize - (psize % vec_size); pj += vec_size) { + zero_vec.store(dst_ptr + i * pcols + cols + pj); + } + if (pj < psize) { + zero_vec.store(dst_ptr + i * pcols + cols + pj, psize - pj); + } + } + } + // row padding + for (; i < prows; i++) { + auto zero_vec = at::vec::Vectorized(0); + int64_t j = 0; + for (; j < pcols - (pcols % vec_size); j += vec_size) { + zero_vec.store(dst_ptr + i * pcols + j); + } + if (j < pcols) { + zero_vec.store(dst_ptr + i * pcols + j, pcols - j); + } + + } +} + +template +inline void pad_remain_row_col_zero( + scalar_t* value_ptr, + int rows, + int cols, + int prows, + int pcols, + int ldi) { + auto psize = pcols - cols; + if (psize == 0 && prows == rows) { + return; + } + auto vec_size = at::vec::Vectorized::size(); + auto zero = at::vec::Vectorized(0); + if (psize > 0) { + for (int i = 0; i < rows; i++) { + int j = 0; + for (; j < psize - (psize % vec_size); j += vec_size) { + zero.store(value_ptr + i * ldi + cols + j); + } + if (j < psize) { + zero.store(value_ptr + i * ldi + cols + j, psize - j); + } + } + } + + for (int i = rows; i < prows; i++) { + int j = 0; + for (; j < pcols - (pcols % vec_size); j += vec_size) { + zero.store(value_ptr + i * ldi + j); + } + if (j < pcols) { + zero.store(value_ptr + i * ldi + j, pcols - j); + } + } + +} + + +template +void cpu_flash_attention( + const Tensor& output, + const Tensor& logsumexp, + const at::Tensor& q, + const at::Tensor& k, + const at::Tensor& v, + double dropout_p, + bool is_causal, + std::optional attn_mask, + std::optional scale) { + // Query (Batch x Num_heads x Q_seq_len x Dim_per_head) + // -> (Batch x Q_seq_len x Num_heads x Dim_per_head) + // Key (Batch x KV_num_heads x KV_seq_len x Dim_per_head) + // -> (Batch x KV_seq_len x KV_num_heads x Dim_per_head) + // Value (Batch x KV_num_heads x KV_seq_len x Dim_per_head) + // -> (Batch x KV_seq_len x KV_num_heads x Dim_per_head) + const at::Tensor query = q.stride(-1) == 1 ? q.transpose(1, 2) : q.transpose(1, 2).contiguous(); + const at::Tensor key = k.stride(-1) == 1 ? k.transpose(1, 2) : k.transpose(1, 2).contiguous(); + const at::Tensor value = v.stride(-1) == 1 ? v.transpose(1, 2) : v.transpose(1, 2).contiguous(); + + constexpr bool is_reduced_type = is_reduced_floating_point_v; + using accum_t = at::opmath_type; + using Vec = vec::Vectorized; + accum_t scaling_factor = + sdp::calculate_scale(query, scale).expect_float(); + + // Sizes + TORCH_CHECK((query.size(3) == value.size(3)) && (key.size(3) == value.size(3)), + "scaled_dot_product_attention_flash_attention: Q/K/V should have the same head size"); + int64_t batchSize = query.size(0); + int64_t qSize = query.size(1); + int64_t kvSize = value.size(1); + int64_t num_head = query.size(2); + int64_t kv_num_head = key.size(2); + int64_t repeat_factor = num_head / kv_num_head; + int64_t headSize = query.size(3); + + bool has_attn_mask = attn_mask.has_value() && attn_mask.value().numel(); + if (has_attn_mask) { + reshape_attn_mask_to_4d(attn_mask.value(), batchSize, num_head, qSize, kvSize); + } + + // Strides + int64_t qStrideB = query.stride(0); + int64_t qStrideM = query.stride(1); + int64_t qStrideH = query.stride(2); + int64_t kStrideB = key.stride(0); + int64_t kStrideN = key.stride(1); + int64_t kStrideH = key.stride(2); + int64_t vStrideB = value.stride(0); + int64_t vStrideN = value.stride(1); + int64_t vStrideH = value.stride(2); + int64_t oStrideB = output.stride(0); + int64_t oStrideM = output.stride(1); + int64_t oStrideH = output.stride(2); + int64_t lStrideB = logsumexp.stride(0); + int64_t lStrideM = logsumexp.stride(1); + int64_t lStrideH = logsumexp.stride(2); + int64_t mStrideB = + (has_attn_mask && attn_mask.value().size(0) > 1) + ? attn_mask.value().stride(0) + : 0; + int64_t mStrideH = + (has_attn_mask && attn_mask.value().size(1) > 1) + ? attn_mask.value().stride(1) + : 0; + int64_t mStrideM = + (has_attn_mask && attn_mask.value().size(2) > 1) + ? attn_mask.value().stride(2) + : 0; + int64_t mStrideN = + (has_attn_mask && attn_mask.value().size(3) > 1) + ? attn_mask.value().stride(3) + : 0; + + int64_t qSplitSize = q_split_size > qSize ? qSize : q_split_size; + int64_t kvSplitSize = kv_split_size > kvSize ? kvSize : kv_split_size; + int64_t qSlice = (qSize + qSplitSize - 1) / qSplitSize; + int64_t kvSlice = (kvSize + kvSplitSize - 1) / kvSplitSize; + int64_t kvTail = (kvSize - 1) % kvSplitSize + 1; + int64_t num_thread = at::get_num_threads(); + + const auto dtype = query.scalar_type(); + const auto accumulate_dtype = toOpMathType(dtype); + + // Whether pack is needed + bool need_pack = false; + if (with_pack) { + // BFloat16 requires larger size as the fallback implementation + // mkl_gemm_bf16bf16f32 is faster than mkl_gemm_f16f16f32 + int64_t thresh_size = (dtype == at::ScalarType::BFloat16) ? 64 : 16; + need_pack = kvSize >= thresh_size && qSize >= thresh_size; + // When the number of gemm is greater than the number of pack, + // the pack overhead can be overlapped. + if (need_pack) { + double pack_size = batchSize * kv_num_head * kvSize * headSize; + double qs_per_thread = (batchSize * num_head * qSlice + num_thread - 1) / num_thread; + double gemm_size_per_thread = qs_per_thread * qSplitSize * + (is_causal ? std::min(qSize, kvSize) : kvSize) * headSize; + need_pack = gemm_size_per_thread / pack_size >= (dtype == at::ScalarType::BFloat16 ? 4 : 1); + } + } + + // Pad is needed for packing when K is not even + bool headSize_even = headSize % 2 == 0; + int64_t eheadSize = need_pack && !headSize_even ? headSize + 1: headSize; + int64_t ekvSplitSize = need_pack && (kvSplitSize % 2 != 0) ? kvSplitSize + 1 : kvSplitSize; + int64_t ekvTail = need_pack && (kvTail % 2 != 0) ? kvTail + 1 : kvTail; + + // Allocate per thread temp buf (accumulate type) + int64_t size_per_thread = + /* qk */ qSplitSize * kvSplitSize + + /* qk_max */ qSplitSize + + /* qk_sum */ qSplitSize + + /* dst */ qSplitSize * headSize; + + at::Tensor buf = at::empty({num_thread, size_per_thread}, query.options().dtype(accumulate_dtype)); + at::Tensor buf_reduced = at::empty( + {num_thread, + qSplitSize, + is_reduced_type ? ekvSplitSize : 0}, + query.options()); + + // Data ptrs + const scalar_t* q_data = query.const_data_ptr(); + const scalar_t* k_data = key.const_data_ptr(); + const scalar_t* v_data = value.const_data_ptr(); + mask_t* mask_data = has_attn_mask + ? attn_mask.value().data_ptr() + : nullptr; + scalar_t* out_data = output.data_ptr(); + accum_t* lse_data = logsumexp.data_ptr(); + accum_t* buf_data = buf.data_ptr(); + scalar_t* buf_reduced_data = is_reduced_type ? buf_reduced.data_ptr() : nullptr; + + // Buffer to store padding query and packing key/value + scalar_t* key_reorder_ptr = nullptr; + scalar_t* value_reorder_ptr = nullptr; + scalar_t* query_padding_ptr = nullptr; + int64_t kv_padding_size = (kvSize - 1) / kvSplitSize * ekvSplitSize + ekvTail; + at::Tensor key_t_reorder; + at::Tensor value_t_reorder; + at::Tensor qeury_t_padding; + if (need_pack) { + key_t_reorder = at::empty( + {batchSize, kv_num_head, eheadSize, kvSize}, + c10::CppTypeToScalarType::value); + value_t_reorder = at::empty( + {batchSize, kv_num_head, kv_padding_size, headSize}, + c10::CppTypeToScalarType::value); + key_reorder_ptr = key_t_reorder.data_ptr(); + value_reorder_ptr = value_t_reorder.data_ptr(); + } + + if (!headSize_even && need_pack) { + qeury_t_padding = at::empty( + {num_thread, qSplitSize, eheadSize}, + c10::CppTypeToScalarType::value); + query_padding_ptr = qeury_t_padding.data_ptr(); + } + + // Reorder K, V + if (need_pack) { + at::Tensor tranpose_t_reorder = at::empty( + {num_thread, kvSplitSize, headSize}, + c10::CppTypeToScalarType::value); + scalar_t* transpose_buffer_ptr = tranpose_t_reorder.data_ptr(); + at::parallel_for(0, batchSize * kv_num_head * kvSlice, 1, [&](int64_t begin, int64_t end) { + int ompIdx = at::get_thread_num(); + int64_t i = 0, kv_j = 0, l = 0, n = 0; + scalar_t* transpose_ptr = transpose_buffer_ptr + ompIdx * kvSplitSize * headSize; + at::native::data_index_init(begin, i, batchSize, kv_j, kv_num_head, l, kvSlice); + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + n = l * kvSplitSize; + int64_t kvBlockSize = std::min(kvSplitSize, kvSize - n); + + // transpose [kvBlockSize, headSize] -> [headSize, kvBlockSize] + utils::transpose( + kvBlockSize, + headSize, + /* src_ptr */ + reinterpret_cast(k_data + i * kStrideB + kv_j * kStrideH + n * kStrideN), + /* ld_src */ kStrideN, + /* dst */ reinterpret_cast(transpose_ptr), + /* ld_dst */ kvBlockSize); + + // Pack [headSize, kvBlockSize] + at::vec::pack_vnni2( + /* src */ reinterpret_cast(transpose_ptr), + /* dst */ reinterpret_cast(key_reorder_ptr + i * kv_num_head * eheadSize * kvSize + + kv_j * eheadSize * kvSize + n * eheadSize), + /* ld_src */ kvBlockSize, + /* K */ headSize, + /* N */ kvBlockSize); + + // Pack [kvBlockSize, headSize] + at::vec::pack_vnni2( + /* src */ reinterpret_cast(v_data + i * vStrideB + kv_j * vStrideH + n * vStrideN), + /* dst */ reinterpret_cast(value_reorder_ptr + + i * kv_num_head * kv_padding_size * headSize + + kv_j * kv_padding_size * headSize + n * headSize), + /* ld_src */ vStrideN, + /* K */ kvBlockSize, + /* N */ headSize); + + // Move to the next query + at::native::data_index_step(i, batchSize, kv_j, kv_num_head, l, kvSlice); + } + }); + } + + at::parallel_for(0, batchSize * num_head * qSlice, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, j = 0, k = 0; + data_index_init(begin, i, batchSize, j, num_head, k, qSlice); + int ompIdx = at::get_thread_num(); + accum_t* buf_ptr = buf_data + ompIdx * size_per_thread; + accum_t* qk_data = buf_ptr; + accum_t* qk_max_data = qk_data + qSplitSize * kvSplitSize; + accum_t* qk_sum_data = qk_max_data + qSplitSize; + accum_t* dst_data = qk_sum_data + qSplitSize; + scalar_t* qk_reduced_data = is_reduced_type ? buf_reduced_data + ompIdx * qSplitSize * ekvSplitSize : nullptr; + scalar_t* query_t_padding_ptr = (!headSize_even && need_pack) + ? query_padding_ptr + ompIdx * qSplitSize * eheadSize + : nullptr; + + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + int64_t m = k * qSplitSize; + int64_t qBlockSize = std::min(qSplitSize, qSize - m); + int64_t kv_j = j / repeat_factor; + // Initialize max and sum + fill_stub(qk_max_data, + -std::numeric_limits::infinity(), qBlockSize); + fill_stub(qk_sum_data, + static_cast(0), qBlockSize); + int64_t num_keys = is_causal ? std::min(m + qBlockSize, kvSize) : kvSize; + if (!headSize_even && need_pack) { + // Pad query if headSize is not even + // [qBlockSize, headSize] -> [qBlockSize, eheadSize] + copy_value_with_pad( + q_data + i * qStrideB + j * qStrideH + m * qStrideM, + query_t_padding_ptr, + qBlockSize, + headSize, + qBlockSize, + eheadSize, + qStrideM + ); + } + for (int64_t n = 0; n < num_keys; n += kvSplitSize) { + int64_t kvBlockSize = std::min(kvSplitSize, kvSize - n); + int64_t ekvBlockSize = (need_pack && kvBlockSize % 2 != 0) ? kvBlockSize + 1 : kvBlockSize; + // Calculate scale * q @ k.T + if (need_pack) { + if constexpr (is_reduced_floating_point_v) { + cpublas::brgemm( + qBlockSize, + kvBlockSize, + eheadSize, + headSize_even ? qStrideM : eheadSize, + kvBlockSize, + kvBlockSize, + false, + !headSize_even + ? query_t_padding_ptr + : q_data + i * qStrideB + j * qStrideH + m * qStrideM, + key_reorder_ptr + i * kv_num_head * eheadSize * kvSize + + kv_j * eheadSize * kvSize + n * eheadSize, + qk_data); + } + } else { + cpublas::gemm( + TransposeType::Transpose, + TransposeType::NoTranspose, + kvBlockSize, + qBlockSize, + headSize, + static_cast(1), + k_data + i * kStrideB + kv_j * kStrideH + + n * kStrideN, + kStrideN, + q_data + i * qStrideB + j * qStrideH + + m * qStrideM, + qStrideM, + static_cast(0), + qk_data, + kvBlockSize); + } + // Apply causal mask, fill unused with -inf + if (is_causal && num_keys - n <= kvSplitSize) { + for (const auto row : c10::irange(qBlockSize)) { + int64_t last_col = m + row - n; + accum_t* row_ptr = qk_data + row * kvBlockSize; + fill_stub(row_ptr + last_col + 1, + -std::numeric_limits::infinity(), + kvBlockSize - last_col - 1); + } + } + // Update attention weights with attention mask + // And apply scaling factor + // qk <- qk * scaling + attn_mask + if (has_attn_mask) { + for (int64_t row = 0; row < qBlockSize; ++row) { +#if __GNUC__ == 11 && defined(__ARM_FEATURE_SVE) + _scale_attn_mask_fusion_kernel( + qk_data + row * kvBlockSize, + mask_data + i * mStrideB + j * mStrideH + + (m + row) * mStrideM + (mStrideN == 0 ? 0 : n), + kvBlockSize, + qk_data + row * kvBlockSize, + scaling_factor, + mStrideN == 0); +#else + if (mStrideN == 0) { + _scale_attn_mask_fusion_kernel( + qk_data + row * kvBlockSize, + mask_data + i * mStrideB + j * mStrideH + + (m + row) * mStrideM, + kvBlockSize, + qk_data + row * kvBlockSize, + scaling_factor); + } else { + _scale_attn_mask_fusion_kernel( + qk_data + row * kvBlockSize, + mask_data + i * mStrideB + j * mStrideH + + (m + row) * mStrideM + n, + kvBlockSize, + qk_data + row * kvBlockSize, + scaling_factor); + } +#endif + } + } + // Update coefficients with Softmax + accum_t tmp_max = 0, tmp_sum = 0, exp_tmp = 0; + for (int64_t row = 0; row < qBlockSize; ++row) { + if (has_attn_mask) { + // max per row + tmp_max = at::vec::reduce_all( + [](Vec& x, Vec& y) { return at::vec::maximum(x, y); }, + qk_data + row * kvBlockSize, + kvBlockSize); + } else { + // apply scaling factor and max per row in fusion + _mul_reduce_max_fusion_kernel( + qk_data + row * kvBlockSize, + scaling_factor, + kvBlockSize, + qk_data + row * kvBlockSize, + tmp_max); + } + tmp_max = qk_max_data[row] > tmp_max ? qk_max_data[row] : tmp_max; + if (tmp_max == -std::numeric_limits::infinity()) { + // to avoid `nan = exp2f(-inf - (-inf))` + fill_stub(conditional_data_ptr(qk_data, qk_reduced_data) + row * ekvBlockSize, + static_cast(0), kvBlockSize); + } else { + tmp_sum = tmp_max; + // qk <- exp(qk - max) and sum per row + _exp_reduce_sum_fusion_kernel( + qk_data + row * kvBlockSize, kvBlockSize, + conditional_data_ptr(qk_data, qk_reduced_data) + row * ekvBlockSize, + tmp_sum); + // exp_tmp <- exp(max[row] - max) + exp_tmp = std::exp(qk_max_data[row] - tmp_max); + // sum[row] <- sum + exp_tmp * sum[row] + qk_sum_data[row] = tmp_sum + exp_tmp * qk_sum_data[row]; + // max[row] <- max + qk_max_data[row] = tmp_max; + // dst <- dst * exp_tmp + if (n > 0) { + vec::map( + [exp_tmp](Vec x) { return x * Vec(exp_tmp); }, + dst_data + row * headSize, + dst_data + row * headSize, + headSize); + } + } + if (need_pack && kvBlockSize % 2 != 0) { + // Pad: [qSplitSize, kvBlockSize] -> [qSplitSize, kvBlockSize + 1] + *(qk_reduced_data + row * (1 + kvBlockSize) + kvBlockSize) = scalar_t(0); + } + } + // Calculate Softmax(q @ k.T) @ v + if (need_pack) { + int64_t psize = n / kvSplitSize * ekvSplitSize; + if constexpr (is_reduced_floating_point_v) { + cpublas::brgemm( + qBlockSize, + headSize, + ekvBlockSize, + ekvBlockSize, + headSize, + headSize, + n > 0, + qk_reduced_data, + value_reorder_ptr + + i * kv_num_head * kv_padding_size * headSize + + kv_j * kv_padding_size * headSize + psize * headSize, + dst_data); + } + } else { + cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::NoTranspose, + headSize, + qBlockSize, + kvBlockSize, + static_cast(1), + v_data + i * vStrideB + kv_j * vStrideH + + n * vStrideN, + vStrideN, + conditional_data_ptr(qk_data, qk_reduced_data), + kvBlockSize, + n == 0 ? static_cast(0) : static_cast(1), + dst_data, + headSize); + } + } + + // dst <- dst / sum[row] + // reorder MHA output with strides + for (int64_t row = 0; row < qBlockSize; ++row) { + // Row sums for full masked out rows are 0, we set them to 1 + // in order to avoid NaNs in the output and instead set fully + // masked out rows to 0 + qk_max_data[row] = qk_max_data[row] == -std::numeric_limits::infinity() ? 0 : qk_max_data[row]; + qk_sum_data[row] = qk_sum_data[row] == 0 ? 1 : qk_sum_data[row]; + accum_t sum_reciprocal = 1 / qk_sum_data[row]; + vec::map( + [sum_reciprocal](Vec x) { return x * Vec(sum_reciprocal); }, + out_data + i * oStrideB + j * oStrideH + m * oStrideM + row * oStrideM, + dst_data + row * headSize, + headSize); + } + // Store logsumexp for backward + accum_t* lse_ptr = lse_data + i * lStrideB + j * lStrideH + m * lStrideM; + for (const auto row : c10::irange(qBlockSize)) { + lse_ptr[row * lStrideM] = qk_max_data[row] + + std::log(qk_sum_data[row]); + } + // Move to the next query + data_index_step(i, batchSize, j, num_head, k, qSlice); + } + if (need_pack) { + cpublas::brgemm_release(); + } + }); +} + +template +void cpu_flash_attention_backward( + const at::Tensor& grad_q, + const at::Tensor& grad_k, + const at::Tensor& grad_v, + const at::Tensor& grad_out, + const at::Tensor& q, + const at::Tensor& k, + const at::Tensor& v, + const at::Tensor& out, + const at::Tensor& logsumexp, + double dropout_p, + bool is_causal, + std::optional attn_mask, + std::optional scale) { + constexpr bool is_reduced_type = is_reduced_floating_point_v; + using accum_t = at::opmath_type; + using Vec = vec::Vectorized; + + // Query (Batch x Q_seq_len x Num_heads x Dim_per_head) + // Key (Batch x KV_seq_len x KV_num_heads x Dim_per_head) + // Value (Batch x KV_seq_len x KV_num_heads x Dim_per_head) + const at::Tensor query = q.stride(-1) == 1 ? q : q.contiguous(); + const at::Tensor key = k.stride(-1) == 1 ? k : k.contiguous(); + const at::Tensor value = v.stride(-1) == 1 ? v : v.contiguous(); + + accum_t scaling_factor = + sdp::calculate_scale(query, scale).expect_float(); + + // Sizes + TORCH_CHECK((query.size(3) == value.size(3)) && (key.size(3) == value.size(3)), + "scaled_dot_product_attention_flash_attention_backward: Q/K/V should have the same head size"); + int64_t batchSize = query.size(0); + int64_t qSize = query.size(1); + int64_t kvSize = value.size(1); + int64_t num_head = query.size(2); + int64_t kv_num_head = key.size(2); + int64_t repeat_factor = num_head / kv_num_head; + int64_t headSize = query.size(3); + + bool has_attn_mask = attn_mask.has_value() && attn_mask.value().numel(); + if (has_attn_mask) { + reshape_attn_mask_to_4d(attn_mask.value(), batchSize, num_head, qSize, kvSize); + } + + // Strides + int64_t qStrideB = query.stride(0); + int64_t qStrideM = query.stride(1); + int64_t qStrideH = query.stride(2); + int64_t kStrideB = key.stride(0); + int64_t kStrideN = key.stride(1); + int64_t kStrideH = key.stride(2); + int64_t vStrideB = value.stride(0); + int64_t vStrideN = value.stride(1); + int64_t vStrideH = value.stride(2); + int64_t oStrideB = out.stride(0); + int64_t oStrideM = out.stride(1); + int64_t oStrideH = out.stride(2); + int64_t lStrideB = logsumexp.stride(0); + int64_t lStrideM = logsumexp.stride(1); + int64_t lStrideH = logsumexp.stride(2); + int64_t mStrideB = + (has_attn_mask && attn_mask.value().size(0) > 1) + ? attn_mask.value().stride(0) + : 0; + int64_t mStrideH = + (has_attn_mask && attn_mask.value().size(1) > 1) + ? attn_mask.value().stride(1) + : 0; + int64_t mStrideM = + (has_attn_mask && attn_mask.value().size(2) > 1) + ? attn_mask.value().stride(2) + : 0; + int64_t mStrideN = + (has_attn_mask && attn_mask.value().size(3) > 1) + ? attn_mask.value().stride(3) + : 0; + + int64_t grad_qStrideB = grad_q.stride(0); + int64_t grad_qStrideM = grad_q.stride(1); + int64_t grad_qStrideH = grad_q.stride(2); + int64_t grad_kStrideB = grad_k.stride(0); + int64_t grad_kStrideN = grad_k.stride(1); + int64_t grad_kStrideH = grad_k.stride(2); + int64_t grad_vStrideB = grad_v.stride(0); + int64_t grad_vStrideN = grad_v.stride(1); + int64_t grad_vStrideH = grad_v.stride(2); + int64_t grad_oStrideB = grad_out.stride(0); + int64_t grad_oStrideM = grad_out.stride(1); + int64_t grad_oStrideH = grad_out.stride(2); + + int64_t qSplitSize = q_split_size > qSize ? qSize : q_split_size; + int64_t kvSplitSize = kv_split_size > kvSize ? kvSize : kv_split_size; + int64_t num_thread = at::get_num_threads(); + + const auto dtype = query.scalar_type(); + const auto accumulate_dtype = toOpMathType(dtype); + + // allocate per thread temp buf (accumulate type) + int64_t size_per_thread = + /* attn */ qSplitSize * kvSplitSize + + /* grad_attn */ qSplitSize * kvSplitSize; + + at::Tensor buf = at::empty({num_thread, size_per_thread}, query.options().dtype(accumulate_dtype)); + + // allocate per thread temp buf_reduced (scalar type) + // buf2 is only needed for bfloat16 and float16 + int64_t size_per_thread_reduced = + /* attn_reduced */ qSplitSize * kvSplitSize + + /* grad_attn_reduced */ qSplitSize * kvSplitSize; + + at::Tensor buf_reduced = at::empty({num_thread, is_reduced_type ? size_per_thread_reduced : 0}, query.options()); + + scalar_t* grad_q_data = grad_q.data_ptr(); + scalar_t* grad_k_data = grad_k.data_ptr(); + scalar_t* grad_v_data = grad_v.data_ptr(); + const scalar_t* grad_out_data = grad_out.const_data_ptr(); + const scalar_t* q_data = query.const_data_ptr(); + const scalar_t* k_data = key.const_data_ptr(); + const scalar_t* v_data = value.const_data_ptr(); + mask_t* mask_data = has_attn_mask + ? attn_mask.value().data_ptr() + : nullptr; + const scalar_t* out_data = out.const_data_ptr(); + const accum_t* lse_data = logsumexp.const_data_ptr(); + accum_t* buf_data = buf.data_ptr(); + scalar_t* buf_reduced_data = is_reduced_type ? buf_reduced.data_ptr() : nullptr; + + at::parallel_for(0, batchSize * kv_num_head, 1, [&](int64_t begin, int64_t end) { + int64_t i = 0, kv_j = 0; + data_index_init(begin, i, batchSize, kv_j, kv_num_head); + int ompIdx = at::get_thread_num(); + accum_t* buf_ptr = buf_data + ompIdx * size_per_thread; + accum_t* attn_data = buf_ptr; + accum_t* grad_attn_data = attn_data + qSplitSize * kvSplitSize; + scalar_t* buf_reduced_ptr = is_reduced_type ? buf_reduced_data + ompIdx * size_per_thread_reduced : nullptr; + scalar_t* attn_reduced_data = is_reduced_type ? buf_reduced_ptr : nullptr; + scalar_t* grad_attn_reduced_data = is_reduced_type ? attn_reduced_data + qSplitSize * kvSplitSize : nullptr; + + at::Tensor dsum = at::empty({qSplitSize}, query.options().dtype(accumulate_dtype)); + accum_t* dsum_data = dsum.data_ptr(); + for ([[maybe_unused]] auto z : c10::irange(begin, end)) { + for (int64_t r = 0; r < repeat_factor; r++) { + int64_t j = kv_j * repeat_factor + r; + // rowsum of grad_out * out + for (int64_t m = 0; m < qSize; m += qSplitSize) { + int64_t qBlockSize = std::min(qSplitSize, qSize - m); + // dsum <- rowsum(grad_out * out) + for (const auto row : c10::irange(qBlockSize)) { + *(dsum_data + row) = vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + grad_out_data + i * grad_oStrideB + j * grad_oStrideH + (m + row) * grad_oStrideM, + out_data + i * oStrideB + j * oStrideH + (m + row) * oStrideM, + headSize); + } + int64_t num_keys = is_causal ? std::min(m + qBlockSize, kvSize) : kvSize; + for (int64_t n = 0; n < num_keys; n += kvSplitSize) { + int64_t kvBlockSize = std::min(kvSplitSize, kvSize - n); + // attn <- scale * q @ k.T + cpublas::gemm( + TransposeType::Transpose, + TransposeType::NoTranspose, + kvBlockSize, + qBlockSize, + headSize, + scaling_factor, + k_data + i * kStrideB + kv_j * kStrideH + + n * kStrideN, + kStrideN, + q_data + i * qStrideB + j * qStrideH + + m * qStrideM, + qStrideM, + static_cast(0), + attn_data, + kvBlockSize); + // attn <- attn + mask + if (has_attn_mask) { + accum_t one = accum_t(1); + for (const auto row : c10::irange(qBlockSize)) { + #if __GNUC__ == 11 && defined(__ARM_FEATURE_SVE) + _scale_attn_mask_fusion_kernel( + attn_data + row * kvBlockSize, + mask_data + i * mStrideB + j * mStrideH + + (m + row) * mStrideM + (mStrideN == 0 ? 0 : n), + kvBlockSize, + attn_data + row * kvBlockSize, + one, + mStrideN == 0); + #else + if (mStrideN == 0) { + _scale_attn_mask_fusion_kernel( + attn_data + row * kvBlockSize, + mask_data + i * mStrideB + j * mStrideH + + (m + row) * mStrideM, + kvBlockSize, + attn_data + row * kvBlockSize, + one); + } else { + _scale_attn_mask_fusion_kernel( + attn_data + row * kvBlockSize, + mask_data + i * mStrideB + j * mStrideH + + (m + row) * mStrideM + n, + kvBlockSize, + attn_data + row * kvBlockSize, + one); + } + #endif + } + } + // restore self attention after softmax from logsumexp + // attn <- exp(attn - normalizer) + for (const auto row : c10::irange(qBlockSize)) { + accum_t normalizer = lse_data[i * lStrideB + j * lStrideH + (m + row) * lStrideM]; + vec::map( + [normalizer](Vec x) { return (x - Vec(normalizer)).exp(); }, + attn_data + row * kvBlockSize, + attn_data + row * kvBlockSize, + kvBlockSize); + } + // Apply causal mask, filled unused with 0 + if (is_causal && num_keys - n <= kvSplitSize) { + for (const auto row : c10::irange(qBlockSize)) { + int64_t last_col = m + row - n; + accum_t* row_ptr = attn_data + row * kvBlockSize; + fill_stub(row_ptr + last_col + 1, static_cast(0), kvBlockSize - last_col - 1); + } + } + #ifdef _MSC_VER + if (is_reduced_type) { + #else + if constexpr (is_reduced_type) { + #endif + for (const auto row : c10::irange(qBlockSize)) { + convert( + attn_data + row * kvBlockSize, + attn_reduced_data + row * kvBlockSize, + kvBlockSize); + } + } + // grad_v <- grad_v + attn.T @ grad_out + cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::Transpose, + headSize, + kvBlockSize, + qBlockSize, + static_cast(1), + grad_out_data + i * grad_oStrideB + j * grad_oStrideH + + m * grad_oStrideM, + grad_oStrideM, + conditional_data_ptr(attn_data, attn_reduced_data), + kvBlockSize, + static_cast(1), + grad_v_data + i * grad_vStrideB + kv_j * grad_vStrideH + + n * grad_vStrideN, + grad_vStrideN); + // grad_attn <- grad_out @ v.T + cpublas::gemm( + TransposeType::Transpose, + TransposeType::NoTranspose, + kvBlockSize, + qBlockSize, + headSize, + static_cast(1), + v_data + i * vStrideB + kv_j * vStrideH + + n * vStrideN, + vStrideN, + grad_out_data + i * grad_oStrideB + j * grad_oStrideH + + m * grad_oStrideM, + grad_oStrideM, + static_cast(0), + grad_attn_data, + kvBlockSize); + // grad_attn <- attn * (grad_attn - dsum) + for (const auto row : c10::irange(qBlockSize)) { + accum_t d = *(dsum_data + row); + vec::map2( + [d](Vec attn, Vec grad_attn) { return attn * (grad_attn - Vec(d)); }, + grad_attn_data + row * kvBlockSize, + attn_data + row * kvBlockSize, + grad_attn_data + row * kvBlockSize, + kvBlockSize); + } + #ifdef _MSC_VER + if (is_reduced_type) { + #else + if constexpr (is_reduced_type) { + #endif + for (const auto row : c10::irange(qBlockSize)) { + convert( + grad_attn_data + row * kvBlockSize, + grad_attn_reduced_data + row * kvBlockSize, + kvBlockSize); + } + } + // grad_q <- grad_q + scale * grad_attn @ k + cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::NoTranspose, + headSize, + qBlockSize, + kvBlockSize, + scaling_factor, + k_data + i * kStrideB + kv_j * kStrideH + + n * kStrideN, + kStrideN, + conditional_data_ptr(grad_attn_data, grad_attn_reduced_data), + kvBlockSize, + static_cast(1), + grad_q_data + i * grad_qStrideB + j * grad_qStrideH + + m * grad_qStrideM, + grad_qStrideM); + // grad_k <- grad_k + scale * grad_attn.T @ q + cpublas::gemm( + TransposeType::NoTranspose, + TransposeType::Transpose, + headSize, + kvBlockSize, + qBlockSize, + scaling_factor, + q_data + i * qStrideB + j * qStrideH + + m * qStrideM, + qStrideM, + conditional_data_ptr(grad_attn_data, grad_attn_reduced_data), + kvBlockSize, + static_cast(1), + grad_k_data + i * grad_kStrideB + kv_j * grad_kStrideH + + n * grad_kStrideN, + grad_kStrideN); + } + } + } + // Move to the next query + data_index_step(i, batchSize, kv_j, kv_num_head); + } + }); +} + +#define AT_DISPATCH_MASK_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_SWITCH( \ + TYPE, \ + NAME, \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::Bool, mask_t, __VA_ARGS__) \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::Float, mask_t, __VA_ARGS__) \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::Double, mask_t, __VA_ARGS__) \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::BFloat16, mask_t, __VA_ARGS__) \ + AT_PRIVATE_CASE_TYPE_USING_HINT( \ + at::ScalarType::Half, mask_t, __VA_ARGS__)) + +#define FLASH_ATTENTION_KERNEL(FNAME, PACK, TYPE1, TYPE2, SEQ1, SEQ2, ...) \ + if (PACK) { \ + FNAME(__VA_ARGS__); \ + } else { \ + FNAME(__VA_ARGS__); \ + } + +void flash_attention_kernel_impl( + const Tensor& output, + const Tensor& logsumexp, + const at::Tensor& query, + const at::Tensor& key, + const at::Tensor& value, + double dropout_p, + bool is_causal, + std::optional attn_mask, + std::optional scale) { + auto q_seq_len = query.size(2); + + // When q_seq_len and k_seq_len are long enough, + // cpu_flash_attention with pack has better performance. + bool could_pack = ((query.scalar_type() == kHalf && cpublas::could_pack(kHalf)) || + (query.scalar_type() == kBFloat16 && cpublas::could_pack(kBFloat16))); + + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, query.scalar_type(), "flash_attention", [&] { + if (!attn_mask.has_value()) { + if (q_seq_len >= 768) { + FLASH_ATTENTION_KERNEL(cpu_flash_attention, could_pack, scalar_t, scalar_t, 256, 512, + output, logsumexp, query, key, value, + dropout_p, is_causal, attn_mask, scale); + } else if (q_seq_len >= 192) { + FLASH_ATTENTION_KERNEL(cpu_flash_attention, could_pack, scalar_t, scalar_t, 64, 512, + output, logsumexp, query, key, value, + dropout_p, is_causal, attn_mask, scale); + } else { + FLASH_ATTENTION_KERNEL(cpu_flash_attention, could_pack, scalar_t, scalar_t, 32, 512, + output, logsumexp, query, key, value, + dropout_p, is_causal, attn_mask, scale); + } + } else { + AT_DISPATCH_MASK_TYPES(attn_mask.value().scalar_type(), "flash_attention_mask", [&]() { + if (q_seq_len >= 768) { + FLASH_ATTENTION_KERNEL(cpu_flash_attention, could_pack, scalar_t, mask_t, 256, 512, + output, logsumexp, query, key, value, + dropout_p, is_causal, attn_mask, scale); + } else if (q_seq_len >= 192) { + FLASH_ATTENTION_KERNEL(cpu_flash_attention, could_pack, scalar_t, mask_t, 64, 512, + output, logsumexp, query, key, value, + dropout_p, is_causal, attn_mask, scale); + } else { + FLASH_ATTENTION_KERNEL(cpu_flash_attention, could_pack, scalar_t, mask_t, 32, 512, + output, logsumexp, query, key, value, + dropout_p, is_causal, attn_mask, scale); + } + }); + } + }); +} + +#undef FLASH_ATTENTION_KERNEL + +void flash_attention_backward_kernel_impl( + const at::Tensor& grad_q, + const at::Tensor& grad_k, + const at::Tensor& grad_v, + const at::Tensor& grad_out, + const at::Tensor& query, + const at::Tensor& key, + const at::Tensor& value, + const at::Tensor& out, + const at::Tensor& logsumexp, + double dropout_p, + bool is_causal, + std::optional attn_mask, + std::optional scale) { + // make sure grad_out has no zero strides (broadcasted dimensions) + // since we are going to call gemm next + // zero stride in leading dimension would lead to slow impl for gemm + auto grad_out_contig = grad_out.contiguous(); + auto q_seq_len = query.size(1); + + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, query.scalar_type(), "flash_attention_backward", [&] { + if (!attn_mask.has_value() || !attn_mask.value().defined()) { + using accum_t = at::opmath_type; + if (q_seq_len >= 768) { + cpu_flash_attention_backward( + grad_q, grad_k, grad_v, grad_out_contig, + query, key, value, out, logsumexp, + dropout_p, is_causal, attn_mask, scale); + } else if (q_seq_len >= 192) { + cpu_flash_attention_backward( + grad_q, grad_k, grad_v, grad_out_contig, + query, key, value, out, logsumexp, + dropout_p, is_causal, attn_mask, scale); + } else { + cpu_flash_attention_backward( + grad_q, grad_k, grad_v, grad_out_contig, + query, key, value, out, logsumexp, + dropout_p, is_causal, attn_mask, scale); + } + } else { + AT_DISPATCH_MASK_TYPES(attn_mask.value().scalar_type(), "flash_attention_mask_backward", [&]() { + if (q_seq_len >= 768) { + cpu_flash_attention_backward( + grad_q, grad_k, grad_v, grad_out_contig, + query, key, value, out, logsumexp, + dropout_p, is_causal, attn_mask, scale); + } else if (q_seq_len >= 192) { + cpu_flash_attention_backward( + grad_q, grad_k, grad_v, grad_out_contig, + query, key, value, out, logsumexp, + dropout_p, is_causal, attn_mask, scale); + } else { + cpu_flash_attention_backward( + grad_q, grad_k, grad_v, grad_out_contig, + query, key, value, out, logsumexp, + dropout_p, is_causal, attn_mask, scale); + } + }); + } + }); +} + +} // anonymous namespace + +ALSO_REGISTER_AVX512_DISPATCH(flash_attention_kernel, &flash_attention_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH(flash_attention_backward_kernel, &flash_attention_backward_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FunctionOfAMatrixUtilsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FunctionOfAMatrixUtilsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6380cda1b4f27a5c75fbf8a98ec0982f7592471e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FunctionOfAMatrixUtilsKernel.cpp @@ -0,0 +1,57 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include +#include + +#if (defined(_WIN32) || defined(_WIN64)) +#define RESTRICT __restrict +#else +#define RESTRICT __restrict__ +#endif + +namespace at::native { + +namespace { + +void _compute_linear_combination_cpu_kernel( + TensorIterator& iter, + int64_t in_stride, + int64_t coeff_stride, + int64_t num_summations +) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + at::ScalarType::Half, at::ScalarType::Bool, at::ScalarType::BFloat16, + iter.dtype(), + "_compute_linear_combination_cpu", [&] { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* RESTRICT out_ptr = data[0]; + auto* RESTRICT in_ptr = data[1]; + auto* RESTRICT coeff_ptr = data[2]; + + for ([[maybe_unused]] const auto elem : c10::irange(n)) { + auto* RESTRICT out_data = reinterpret_cast(out_ptr); + auto* RESTRICT in_data = reinterpret_cast(in_ptr); + using primitive_t = typename scalar_value_type::type; + auto* RESTRICT coeff_data = reinterpret_cast(coeff_ptr); + + // perform summation + for (const auto i : c10::irange(num_summations)) { + *out_data += in_data[i * in_stride] * coeff_data[i * coeff_stride]; + } + + out_ptr += strides[0]; + in_ptr += strides[1]; + coeff_ptr += strides[2]; + } + }; + iter.for_each(loop); + }); +} + +} + +REGISTER_DISPATCH(_compute_linear_combination_stub, &_compute_linear_combination_cpu_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedAdagradKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedAdagradKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..488966ff4d71e8a9b96b99e52844217b6d886333 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedAdagradKernel.cpp @@ -0,0 +1,218 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +namespace at::native { + +namespace{ + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> + inline adagrad_math( + scalar_t* param_ptr, + scalar_t* grad_ptr, + scalar_t* state_sum_ptr, + const double clr, + const double eps, + const double weight_decay, + const bool maximize, + const float* grad_scale_ptr, + int64_t size +){ + using lpVec = at::vec::Vectorized; + using fVec = at::vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % lpVec::size()); d += lpVec::size()) { + lpVec param_lpvec = lpVec::loadu(param_ptr + d); + auto [param_vec1, param_vec2] = vec::convert_to_float(param_lpvec); + lpVec grad_lpvec = lpVec::loadu(grad_ptr + d); + auto [grad_vec1, grad_vec2] = vec::convert_to_float(grad_lpvec); + if (grad_scale_ptr) { + grad_vec1 = grad_vec1 / fVec(float(*grad_scale_ptr)); + grad_vec2 = grad_vec2 / fVec(float(*grad_scale_ptr)); + lpVec grad_vec_to_store = vec::convert_from_float(grad_vec1, grad_vec2); + grad_vec_to_store.store(grad_ptr + d); + } + if (maximize){ + grad_vec1 = grad_vec1 * fVec(opmath_t(-1.0)); + grad_vec2 = grad_vec2 * fVec(opmath_t(-1.0)); + } + if (weight_decay != 0.0){ + grad_vec1 += param_vec1 * fVec(scalar_t(weight_decay)); + grad_vec2 += param_vec2 * fVec(scalar_t(weight_decay)); + } + auto [state_sum_vec1, state_sum_vec2] = vec::convert_to_float(lpVec::loadu(state_sum_ptr + d)); + state_sum_vec1 += grad_vec1 * grad_vec1; + state_sum_vec2 += grad_vec2 * grad_vec2; + vec::convert_from_float(state_sum_vec1, state_sum_vec2).store(state_sum_ptr + d); + + fVec std_vec1 = state_sum_vec1.sqrt() + fVec(scalar_t(eps)); + fVec std_vec2 = state_sum_vec2.sqrt() + fVec(scalar_t(eps)); + param_vec1 = param_vec1 - fVec(scalar_t(clr)) * grad_vec1 / std_vec1; + param_vec2 = param_vec2 - fVec(scalar_t(clr)) * grad_vec2 / std_vec2; + vec::convert_from_float(param_vec1, param_vec2).store(param_ptr + d); + } + for (; d < size; d++) { + opmath_t grad_val = grad_ptr[d]; + opmath_t param_val = param_ptr[d]; + if (grad_scale_ptr) { + grad_val = grad_ptr[d] / opmath_t(*grad_scale_ptr); + grad_ptr[d] = grad_val; + } + if (maximize) grad_val = -grad_val; + if (weight_decay != 0.0){ + grad_val += param_val * opmath_t(weight_decay); + } + opmath_t state_sum_val = state_sum_ptr[d]; + state_sum_val += grad_val * grad_val; + state_sum_ptr[d] = state_sum_val; + opmath_t std_val = std::sqrt(state_sum_val) + opmath_t(eps); + param_val -= opmath_t(clr) * grad_val / std_val; + param_ptr[d] = param_val; + } +} + + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> + inline adagrad_math( + scalar_t* param_ptr, + scalar_t* grad_ptr, + scalar_t* state_sum_ptr, + const double clr, + const double eps, + const double weight_decay, + const bool maximize, + const float* grad_scale_ptr, + int64_t size +){ + using Vec = at::vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec param_vec = Vec::loadu(param_ptr + d); + Vec grad_vec = Vec::loadu(grad_ptr + d); + if (grad_scale_ptr) { + grad_vec = grad_vec / Vec(scalar_t(*grad_scale_ptr)); + Vec grad_vec_to_store = grad_vec; + grad_vec_to_store.store(grad_ptr + d); + } + if (maximize) grad_vec = grad_vec * Vec(scalar_t(-1.0)); + if (weight_decay != 0.0){ + grad_vec += param_vec * Vec(scalar_t(weight_decay)); + } + + Vec sum_vec = Vec::loadu(state_sum_ptr + d) + grad_vec * grad_vec; + sum_vec.store(state_sum_ptr + d); + + Vec std_vec = sum_vec.sqrt() + Vec(scalar_t(eps)); + param_vec = param_vec - Vec(scalar_t(clr)) * grad_vec / std_vec; + param_vec.store(param_ptr + d); + } + scalar_t grad_val_to_store; + for (; d < size; d++) { + scalar_t grad_val = grad_ptr[d]; + if (grad_scale_ptr) { + grad_val = grad_ptr[d] / scalar_t(*grad_scale_ptr); + grad_val_to_store = grad_val; + grad_ptr[d] = grad_val_to_store; + } + if (maximize) grad_val = -grad_val; + if (weight_decay != 0.0){ + grad_val += param_ptr[d] * scalar_t(weight_decay); + } + state_sum_ptr[d] += grad_val * grad_val; + + scalar_t std_val = std::sqrt(state_sum_ptr[d]) + scalar_t(eps); + param_ptr[d] -= scalar_t(clr) * grad_val / std_val; + } +} + +template +void adagrad_fused_step_impl( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& state_sum, + const at::Tensor& state_step, + const double lr, + const double lr_decay, + const double weight_decay, + const double eps, + const bool maximize, + const float* grad_scale_ptr) { + using opmath_t = at::opmath_type; + scalar_t* param_data = param.data_ptr(); + scalar_t* grad_data = grad.data_ptr(); + scalar_t* state_sum_data = state_sum.data_ptr(); + double step = state_step.item(); + double clr = lr / (1.0 + (step - 1.0) * lr_decay); + + constexpr size_t cache_line_size = 64; + constexpr int64_t cache_line_aligned_task_unit = cache_line_size / sizeof(scalar_t); + size_t num_units = divup(param.numel(), cache_line_aligned_task_unit); + + auto adagrad_fn = [&](int64_t begin, int64_t end) { + // local pointers + begin *= cache_line_aligned_task_unit; + end = std::min(end * cache_line_aligned_task_unit, param.numel()); + scalar_t* param_ptr = param_data + begin; + scalar_t* grad_ptr = grad_data + begin; + scalar_t* state_sum_ptr = state_sum_data + begin; + + const int64_t size = end - begin; + adagrad_math( + param_ptr, + grad_ptr, + state_sum_ptr, + clr, + eps, + weight_decay, + maximize, + grad_scale_ptr, + size + ); + }; + at::parallel_for( + 0, num_units, 0, adagrad_fn); +} + +void fused_adagrad_kernel( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& state_sum, + const at::Tensor& state_step, + const double lr, + const double lr_decay, + const double weight_decay, + const double eps, + const bool maximize, + const float* grad_scale_ptr + ) { + Tensor grad_contiguous = grad.contiguous(); + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, param.scalar_type(), "fused_adagrad_kernel", [&] { + adagrad_fused_step_impl( + param, + grad, + state_sum, + state_step, + lr, + lr_decay, + weight_decay, + eps, + maximize, + grad_scale_ptr); + }); +} + +} + +REGISTER_DISPATCH(fused_adagrad_stub, &fused_adagrad_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedAdamKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedAdamKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b38ca27fc66098e67a8b2e727f78fc7838afd6f0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedAdamKernel.cpp @@ -0,0 +1,368 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +namespace at::native { + +namespace{ + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> + inline adam_math( + scalar_t* param_ptr, + scalar_t* exp_avg_ptr, + scalar_t* exp_avg_sq_ptr, + scalar_t* grad_ptr, + scalar_t* max_exp_avg_sq_ptr, + double lr, + double bias_correction1, + double bias_correction2, + double exp_avg_grad_coefficient, + double exp_avg_sq_grad_coefficient, + double bias_correction2_sqrt, + double eps, + double weight_decay, + double beta2, + bool amsgrad, + bool maximize, + const float* grad_scale_ptr, + int64_t size +){ + double step_size = lr / bias_correction1; + using lpVec = at::vec::Vectorized; + using fVec = at::vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % lpVec::size()); d += lpVec::size()) { + lpVec param_lpvec = lpVec::loadu(param_ptr + d); + auto [param_vec1, param_vec2] = vec::convert_to_float(param_lpvec); + lpVec grad_lpvec = lpVec::loadu(grad_ptr + d); + auto [grad_vec1, grad_vec2] = vec::convert_to_float(grad_lpvec); + if (grad_scale_ptr) { + grad_vec1 = grad_vec1 / fVec(float(*grad_scale_ptr)); + grad_vec2 = grad_vec2 / fVec(float(*grad_scale_ptr)); + lpVec grad_vec_to_store = vec::convert_from_float(grad_vec1, grad_vec2); + grad_vec_to_store.store(grad_ptr + d); + } + if (maximize){ + grad_vec1 = grad_vec1 * fVec(opmath_t(-1.0)); + grad_vec2 = grad_vec2 * fVec(opmath_t(-1.0)); + } + if (weight_decay != 0.f){ + if constexpr (adam_mode == ADAM_MODE::ORIGINAL) { + grad_vec1 += param_vec1 * fVec(opmath_t(weight_decay)); + grad_vec2 += param_vec2 * fVec(opmath_t(weight_decay)); + } else if constexpr (adam_mode == ADAM_MODE::ADAMW) { + param_vec1 = param_vec1 * fVec(opmath_t(1 - lr * weight_decay)); + param_vec2 = param_vec2 * fVec(opmath_t(1 - lr * weight_decay)); + } + } + + lpVec exp_avg_lpvec = lpVec::loadu(exp_avg_ptr + d); + auto [exp_avg_vec1, exp_avg_vec2] = vec::convert_to_float(exp_avg_lpvec); + + // exp_avg.lerp_(grad, 1 - beta1) + const fVec lerp_weight = fVec(opmath_t(exp_avg_grad_coefficient)); + auto mask = lerp_weight.abs() < fVec(0.5); + auto coeff = fVec::blendv(lerp_weight - fVec(1), lerp_weight, mask); + + auto base1 = fVec::blendv(grad_vec1, exp_avg_vec1, mask); + exp_avg_vec1 = vec::fmadd(coeff, grad_vec1 - exp_avg_vec1, base1); + + auto base2 = fVec::blendv(grad_vec2, exp_avg_vec2, mask); + exp_avg_vec2 = vec::fmadd(coeff, grad_vec2 - exp_avg_vec2, base2); + + lpVec exp_avg_sq_lpvec = lpVec::loadu(exp_avg_sq_ptr + d); + auto [exp_avg_sq_vec1, exp_avg_sq_vec2] = vec::convert_to_float(exp_avg_sq_lpvec); + exp_avg_sq_vec1 = exp_avg_sq_vec1 * fVec(opmath_t(beta2)) + + fVec(opmath_t(exp_avg_sq_grad_coefficient)) * grad_vec1 * grad_vec1; + exp_avg_sq_vec2 = exp_avg_sq_vec2 * fVec(opmath_t(beta2)) + + fVec(opmath_t(exp_avg_sq_grad_coefficient)) * grad_vec2 * grad_vec2; + + vec::convert_from_float(exp_avg_vec1, exp_avg_vec2).store(exp_avg_ptr + d); + vec::convert_from_float(exp_avg_sq_vec1, exp_avg_sq_vec2).store(exp_avg_sq_ptr + d); + + fVec denom_vec1, denom_vec2; + if (amsgrad) { + lpVec max_exp_avg_sq_lpvec = lpVec::loadu(max_exp_avg_sq_ptr + d); + auto [max_exp_avg_sq_vec1, max_exp_avg_sq_vec2] = vec::convert_to_float(max_exp_avg_sq_lpvec); + max_exp_avg_sq_vec1 = maximum(max_exp_avg_sq_vec1, exp_avg_sq_vec1); + max_exp_avg_sq_vec2 = maximum(max_exp_avg_sq_vec2, exp_avg_sq_vec2); + vec::convert_from_float(max_exp_avg_sq_vec1, max_exp_avg_sq_vec2).store(max_exp_avg_sq_ptr + d); + denom_vec1 = + (max_exp_avg_sq_vec1.sqrt() / fVec(opmath_t(bias_correction2_sqrt))) + fVec(opmath_t(eps)); + denom_vec2 = + (max_exp_avg_sq_vec2.sqrt() / fVec(opmath_t(bias_correction2_sqrt))) + fVec(opmath_t(eps)); + } else { + denom_vec1 = + (exp_avg_sq_vec1.sqrt() / fVec(opmath_t(bias_correction2_sqrt))) + fVec(opmath_t(eps)); + denom_vec2 = + (exp_avg_sq_vec2.sqrt() / fVec(opmath_t(bias_correction2_sqrt))) + fVec(opmath_t(eps)); + } + param_vec1 = param_vec1 + fVec(opmath_t(-step_size)) * exp_avg_vec1 / denom_vec1; + param_vec2 = param_vec2 + fVec(opmath_t(-step_size)) * exp_avg_vec2 / denom_vec2; + vec::convert_from_float(param_vec1, param_vec2).store(param_ptr + d); + } + for (; d < size; d++) { + opmath_t grad_val = grad_ptr[d]; + opmath_t param_val = param_ptr[d]; + if (grad_scale_ptr) { + grad_val = grad_ptr[d] / float(*grad_scale_ptr); + grad_ptr[d] = grad_val; + } + if (maximize) grad_val = -grad_val; + if (weight_decay != 0.f){ + if constexpr (adam_mode == ADAM_MODE::ORIGINAL) { + grad_val += param_val * opmath_t(weight_decay); + } else if constexpr (adam_mode == ADAM_MODE::ADAMW) { + param_val = param_val * opmath_t(1 - lr * weight_decay); + } + } + // exp_avg.lerp_(grad, 1 - beta1) + opmath_t exp_avg_var = exp_avg_ptr[d]; + auto is_lerp_weight_small = std::abs(opmath_t(exp_avg_grad_coefficient)) < opmath_t(0.5); + if (is_lerp_weight_small) { + exp_avg_var = exp_avg_var + opmath_t(exp_avg_grad_coefficient) * (grad_val - exp_avg_var); + } else { + exp_avg_var = grad_val - (grad_val - exp_avg_var) * (opmath_t(1) - opmath_t(exp_avg_grad_coefficient)); + } + exp_avg_ptr[d] = scalar_t(exp_avg_var); + opmath_t exp_avg_sq_var = exp_avg_sq_ptr[d]; + exp_avg_sq_var = exp_avg_sq_var * opmath_t(beta2); + exp_avg_sq_var = exp_avg_sq_var + + opmath_t(exp_avg_sq_grad_coefficient) * grad_val * grad_val; + exp_avg_sq_ptr[d] = scalar_t(exp_avg_sq_var); + opmath_t demon_val; + if (amsgrad) { + opmath_t max_exp_avg_sq_var = max_exp_avg_sq_ptr[d]; + max_exp_avg_sq_var = std::max(max_exp_avg_sq_var, exp_avg_sq_var); + max_exp_avg_sq_ptr[d] = + scalar_t(max_exp_avg_sq_var); + demon_val = + std::sqrt(max_exp_avg_sq_var) / opmath_t(bias_correction2_sqrt) + opmath_t(eps); + } else { + demon_val = std::sqrt(exp_avg_sq_var) / opmath_t(bias_correction2_sqrt) + opmath_t(eps); + } + param_ptr[d] = param_val - opmath_t(step_size) * exp_avg_var / demon_val; + } +} + + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> + inline adam_math( + scalar_t* param_ptr, + scalar_t* exp_avg_ptr, + scalar_t* exp_avg_sq_ptr, + scalar_t* grad_ptr, + scalar_t* max_exp_avg_sq_ptr, + double lr, + double bias_correction1, + double bias_correction2, + double exp_avg_grad_coefficient, + double exp_avg_sq_grad_coefficient, + double bias_correction2_sqrt, + double eps, + double weight_decay, + double beta2, + bool amsgrad, + bool maximize, + const float* grad_scale_ptr, + int64_t size +){ + double step_size = lr / bias_correction1; + using Vec = at::vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec param_vec = Vec::loadu(param_ptr + d); + Vec grad_vec = Vec::loadu(grad_ptr + d); + if (grad_scale_ptr) { + grad_vec = grad_vec / Vec(scalar_t(*grad_scale_ptr)); + Vec grad_vec_to_store = grad_vec; + grad_vec_to_store.store(grad_ptr + d); + } + if (maximize) grad_vec = grad_vec * Vec(scalar_t(-1.0)); + if (weight_decay != 0.f){ + if constexpr (adam_mode == ADAM_MODE::ORIGINAL) { + grad_vec += param_vec * Vec(scalar_t(weight_decay)); + } else if constexpr (adam_mode == ADAM_MODE::ADAMW) { + param_vec = param_vec * Vec(scalar_t(1 - lr * weight_decay)); + } + } + Vec exp_avg_vec = Vec::loadu(exp_avg_ptr + d); + // exp_avg.lerp_(grad, 1 - beta1) + const Vec lerp_weight = Vec(scalar_t(exp_avg_grad_coefficient)); + auto mask = lerp_weight.abs() < Vec(0.5); + auto coeff = Vec::blendv(lerp_weight - Vec(1), lerp_weight, mask); + auto base = Vec::blendv(grad_vec, exp_avg_vec, mask); + exp_avg_vec = vec::fmadd(coeff, grad_vec - exp_avg_vec, base); + + Vec exp_avg_sq_vec = Vec::loadu(exp_avg_sq_ptr + d) * Vec(scalar_t(beta2)) + + Vec(scalar_t(exp_avg_sq_grad_coefficient)) * grad_vec * grad_vec; + exp_avg_vec.store(exp_avg_ptr + d); + exp_avg_sq_vec.store(exp_avg_sq_ptr + d); + + Vec denom_vec; + if (amsgrad) { + Vec max_exp_avg_sq_vec = + maximum(Vec::loadu(max_exp_avg_sq_ptr + d), exp_avg_sq_vec); + max_exp_avg_sq_vec.store(max_exp_avg_sq_ptr + d); + denom_vec = + (max_exp_avg_sq_vec.sqrt() / Vec(scalar_t(bias_correction2_sqrt))) + Vec(scalar_t(eps)); + } else { + denom_vec = + (exp_avg_sq_vec.sqrt() / Vec(scalar_t(bias_correction2_sqrt))) + Vec(scalar_t(eps)); + } + param_vec = param_vec + Vec(scalar_t(-step_size)) * exp_avg_vec / denom_vec; + param_vec.store(param_ptr + d); + } + for (; d < size; d++) { + scalar_t grad_val = grad_ptr[d]; + if (grad_scale_ptr) { + grad_val = grad_ptr[d] / scalar_t(*grad_scale_ptr); + grad_ptr[d] = grad_val; + } + if (maximize) grad_val = -grad_val; + if (weight_decay != 0.f){ + if constexpr (adam_mode == ADAM_MODE::ORIGINAL) { + grad_val += param_ptr[d] * scalar_t(weight_decay); + } else if constexpr (adam_mode == ADAM_MODE::ADAMW) { + param_ptr[d] = param_ptr[d] * scalar_t(1 - lr * weight_decay); + } + } + // exp_avg.lerp_(grad, 1 - beta1) + auto is_lerp_weight_small = std::abs(scalar_t(exp_avg_grad_coefficient)) < scalar_t(0.5); + if (is_lerp_weight_small) { + exp_avg_ptr[d] = exp_avg_ptr[d] + scalar_t(exp_avg_grad_coefficient) * (grad_val - exp_avg_ptr[d]); + } else { + exp_avg_ptr[d] = grad_val - (grad_val - exp_avg_ptr[d]) * (scalar_t(1) - scalar_t(exp_avg_grad_coefficient)); + } + exp_avg_sq_ptr[d] = exp_avg_sq_ptr[d] * scalar_t(beta2); + exp_avg_sq_ptr[d] = exp_avg_sq_ptr[d] + + scalar_t(exp_avg_sq_grad_coefficient) * grad_val * grad_val; + scalar_t demon_val; + if (amsgrad) { + max_exp_avg_sq_ptr[d] = + std::max(max_exp_avg_sq_ptr[d], exp_avg_sq_ptr[d]); + demon_val = + std::sqrt(max_exp_avg_sq_ptr[d]) / scalar_t(bias_correction2_sqrt) + scalar_t(eps); + } else { + demon_val = std::sqrt(exp_avg_sq_ptr[d]) / scalar_t(bias_correction2_sqrt) + scalar_t(eps); + } + param_ptr[d] = param_ptr[d] - scalar_t(step_size) * exp_avg_ptr[d] / demon_val; + } +} + + +template +void adam_fused_step_impl( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& exp_avg, + const at::Tensor& exp_avg_sq, + const at::Tensor& max_exp_avg_sq, + const at::Tensor& state_step, + const double lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const float* grad_scale_ptr) { + using opmath_t = at::opmath_type; + double step = state_step.item(); + scalar_t* param_data = param.data_ptr(); + scalar_t* exp_avg_data = exp_avg.data_ptr(); + scalar_t* exp_avg_sq_data = exp_avg_sq.data_ptr(); + scalar_t* max_exp_avg_sq_data = amsgrad ? max_exp_avg_sq.data_ptr() : nullptr; + scalar_t* grad_data = grad.data_ptr(); + + // need to use double here to align with non-fused adam + double bias_correction1 = 1 - std::pow(beta1, step); + double bias_correction2 = 1 - std::pow(beta2, step); + double exp_avg_grad_coefficient = 1 - beta1; + double exp_avg_sq_grad_coefficient = 1 - beta2; + double bias_correction2_sqrt = std::sqrt(bias_correction2); + + + constexpr size_t cache_line_size = 64; + constexpr int64_t cache_line_aligned_task_unit = cache_line_size / sizeof(scalar_t); + size_t num_units = divup(param.numel(), cache_line_aligned_task_unit); + + auto adam_fn = [&](int64_t begin, int64_t end) { + // local pointers + begin *= cache_line_aligned_task_unit; + end = std::min(end * cache_line_aligned_task_unit, param.numel()); + scalar_t* param_ptr = param_data + begin; + scalar_t* exp_avg_ptr = exp_avg_data + begin; + scalar_t* exp_avg_sq_ptr = exp_avg_sq_data + begin; + scalar_t* grad_ptr = grad_data + begin; + scalar_t* max_exp_avg_sq_ptr = amsgrad ? max_exp_avg_sq_data + begin : nullptr; + + const int64_t size = end - begin; + adam_math( + param_ptr, + exp_avg_ptr, + exp_avg_sq_ptr, + grad_ptr, + max_exp_avg_sq_ptr, + lr, + bias_correction1, + bias_correction2, + exp_avg_grad_coefficient, + exp_avg_sq_grad_coefficient, + bias_correction2_sqrt, + eps, + weight_decay, + beta2, + amsgrad, + maximize, + grad_scale_ptr, + size + ); + }; + at::parallel_for( + 0, num_units, 0, adam_fn); +} + +void fused_adam_kernel( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& exp_avg, + const at::Tensor& exp_avg_sq, + const at::Tensor& max_exp_avg_sq, + const at::Tensor& state_step, + const double lr, + const double beta1, + const double beta2, + const double weight_decay, + const double eps, + const bool amsgrad, + const bool maximize, + const float* grad_scale_ptr, + const ADAM_MODE adam_mode + ) { + Tensor grad_contiguous = grad.contiguous(); + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, param.scalar_type(), "fused_adam_kernel", [&] { + if(adam_mode == ADAM_MODE::ORIGINAL){ + adam_fused_step_impl(param, grad, exp_avg, exp_avg_sq, max_exp_avg_sq, state_step, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale_ptr); + } else { + adam_fused_step_impl(param, grad, exp_avg, exp_avg_sq, max_exp_avg_sq, state_step, lr, beta1, beta2, weight_decay, eps, amsgrad, maximize, grad_scale_ptr); + } + + }); +} + +} + +REGISTER_DISPATCH(fused_adam_stub, &fused_adam_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedSGDKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedSGDKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6350225eb23e345b90ad631d9fb179c8fe22372b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/FusedSGDKernel.cpp @@ -0,0 +1,268 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +namespace at::native { + +namespace{ + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> + inline sgd_math( + scalar_t* param_ptr, + scalar_t* grad_ptr, + scalar_t* momentum_buf_ptr, + const double weight_decay, + const double momentum, + const double lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const float* grad_scale_ptr, + int64_t size +){ + using lpVec = at::vec::Vectorized; + using fVec = at::vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % lpVec::size()); d += lpVec::size()) { + lpVec param_lpvec = lpVec::loadu(param_ptr + d); + auto [param_vec1, param_vec2] = vec::convert_to_float(param_lpvec); + lpVec grad_lpvec = lpVec::loadu(grad_ptr + d); + auto [grad_vec1, grad_vec2] = vec::convert_to_float(grad_lpvec); + if (grad_scale_ptr) { + grad_vec1 = grad_vec1 / fVec(float(*grad_scale_ptr)); + grad_vec2 = grad_vec2 / fVec(float(*grad_scale_ptr)); + lpVec grad_vec_to_store = vec::convert_from_float(grad_vec1, grad_vec2); + grad_vec_to_store.store(grad_ptr + d); + } + if (maximize){ + grad_vec1 = grad_vec1 * fVec(opmath_t(-1.0)); + grad_vec2 = grad_vec2 * fVec(opmath_t(-1.0)); + } + if (weight_decay != 0.0){ + grad_vec1 = vec::fmadd(param_vec1, fVec(scalar_t(weight_decay)), grad_vec1); + grad_vec2 = vec::fmadd(param_vec2, fVec(scalar_t(weight_decay)), grad_vec2); + } + if (momentum != 0.0) { + fVec momentum_vec1, momentum_vec2; + if (is_first_step) { + momentum_vec1 = grad_vec1; + momentum_vec2 = grad_vec2; + } else { + momentum_vec1 = fVec::loadu(momentum_buf_ptr + d) * fVec(scalar_t(momentum)); + momentum_vec2 = fVec::loadu(momentum_buf_ptr + d + fVec::size()) * fVec(scalar_t(momentum)); + momentum_vec1 = vec::fmadd(fVec(scalar_t(1 - dampening)), grad_vec1, momentum_vec1); + momentum_vec2 = vec::fmadd(fVec(scalar_t(1 - dampening)), grad_vec2, momentum_vec2); + } + vec::convert_from_float(momentum_vec1, momentum_vec2).store(momentum_buf_ptr + d);; + if (nesterov) { + grad_vec1 = vec::fmadd(momentum_vec1, fVec(scalar_t(momentum)), grad_vec1); + grad_vec2 = vec::fmadd(momentum_vec2, fVec(scalar_t(momentum)), grad_vec2); + } else { + grad_vec1 = momentum_vec1; + grad_vec2 = momentum_vec2; + } + } + } + for (; d < size; d++) { + opmath_t grad_val = grad_ptr[d]; + opmath_t param_val = param_ptr[d]; + if (grad_scale_ptr) { + grad_val = grad_ptr[d] / opmath_t(*grad_scale_ptr); + grad_ptr[d] = grad_val; + } + if (maximize) grad_val = -grad_val; + if (weight_decay != 0.0){ + grad_val += param_val * opmath_t(weight_decay); + } + if (momentum != 0.0) { + opmath_t momentum_buf_var = momentum_buf_ptr[d]; + if (is_first_step) { + momentum_buf_var = grad_val; + } else { + momentum_buf_var = momentum_buf_var * opmath_t(momentum) + + grad_val * opmath_t(1 - dampening); + } + momentum_buf_ptr[d] = momentum_buf_var; + if (nesterov) { + grad_val += momentum_buf_var * opmath_t(momentum); + } else { + grad_val = momentum_buf_var; + } + } + param_ptr[d] = param_val - grad_val * opmath_t(lr); + } +} + + +template +std::enable_if_t< + std::is_same_v || std::is_same_v, + void> + inline sgd_math( + scalar_t* param_ptr, + scalar_t* grad_ptr, + scalar_t* momentum_buf_ptr, + const double weight_decay, + const double momentum, + const double lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const float* grad_scale_ptr, + int64_t size +){ + using Vec = at::vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec param_vec = Vec::loadu(param_ptr + d); + Vec grad_vec = Vec::loadu(grad_ptr + d); + if (grad_scale_ptr) { + grad_vec = grad_vec / Vec(scalar_t(*grad_scale_ptr)); + Vec grad_vec_to_store = grad_vec; + grad_vec_to_store.store(grad_ptr + d); + } + if (maximize) grad_vec = grad_vec * Vec(scalar_t(-1.0)); + if (weight_decay != 0.0){ + grad_vec = vec::fmadd(param_vec, Vec(scalar_t(weight_decay)), grad_vec); + } + if (momentum != 0.0) { + Vec momentum_vec; + if (is_first_step) { + momentum_vec = grad_vec; + } else { + momentum_vec = + Vec::loadu(momentum_buf_ptr + d) * Vec(scalar_t(momentum)); + momentum_vec = vec::fmadd(Vec(scalar_t(1 - dampening)), grad_vec, momentum_vec); + } + momentum_vec.store(momentum_buf_ptr + d); + if (nesterov) { + grad_vec = vec::fmadd(momentum_vec, Vec(scalar_t(momentum)), grad_vec); + } else { + grad_vec = momentum_vec; + } + } + param_vec += grad_vec * Vec(scalar_t(-lr)); + param_vec.store(param_ptr + d); + } + for (; d < size; d++) { + scalar_t grad_val = grad_ptr[d]; + if (grad_scale_ptr) { + grad_val = grad_ptr[d] / scalar_t(*grad_scale_ptr); + grad_ptr[d] = grad_val; + } + if (maximize) grad_val = -grad_val; + if (weight_decay != 0.0){ + grad_val += param_ptr[d] * scalar_t(weight_decay); + } + if (momentum != 0.0) { + if (is_first_step) { + momentum_buf_ptr[d] = grad_val; + } else { + momentum_buf_ptr[d] = momentum_buf_ptr[d] * scalar_t(momentum) + + grad_val * scalar_t(1 - dampening); + } + if (nesterov) { + grad_val += momentum_buf_ptr[d] * scalar_t(momentum); + } else { + grad_val = momentum_buf_ptr[d]; + } + } + param_ptr[d] -= grad_val * scalar_t(lr); + } +} + +template +void sgd_fused_step_impl( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& momentum_buffer, + const double weight_decay, + const double momentum, + const double lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const float* grad_scale_ptr) { + using opmath_t = at::opmath_type; + scalar_t* param_data = param.data_ptr(); + scalar_t* grad_data = grad.data_ptr(); + bool has_momentum_buffer = momentum != 0.0; + scalar_t* momentum_buffer_data = has_momentum_buffer ? momentum_buffer.data_ptr() : nullptr; + + constexpr size_t cache_line_size = 64; + constexpr int64_t cache_line_aligned_task_unit = cache_line_size / sizeof(scalar_t); + size_t num_units = divup(param.numel(), cache_line_aligned_task_unit); + + auto sgd_fn = [&](int64_t begin, int64_t end) { + // local pointers + begin *= cache_line_aligned_task_unit; + end = std::min(end * cache_line_aligned_task_unit, param.numel()); + scalar_t* param_ptr = param_data + begin; + scalar_t* grad_ptr = grad_data + begin; + scalar_t* momentum_buffer_ptr = has_momentum_buffer ? momentum_buffer_data + begin : nullptr; + + const int64_t size = end - begin; + sgd_math( + param_ptr, + grad_ptr, + momentum_buffer_ptr, + weight_decay, + momentum, + lr, + dampening, + nesterov, + maximize, + is_first_step, + grad_scale_ptr, + size + ); + }; + at::parallel_for( + 0, num_units, 0, sgd_fn); +} + +void fused_sgd_kernel( + const at::Tensor& param, + const at::Tensor& grad, + const at::Tensor& momentum_buffer, + const double weight_decay, + const double momentum, + const double lr, + const double dampening, + const bool nesterov, + const bool maximize, + const bool is_first_step, + const float* grad_scale_ptr + ) { + Tensor grad_contiguous = grad.contiguous(); + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, param.scalar_type(), "fused_sgd_kernel", [&] { + sgd_fused_step_impl( + param, + grad, + momentum_buffer, + weight_decay, + momentum, + lr, + dampening, + nesterov, + maximize, + is_first_step, + grad_scale_ptr); + }); +} + +} + +REGISTER_DISPATCH(fused_sgd_stub, &fused_sgd_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Gelu.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Gelu.h new file mode 100644 index 0000000000000000000000000000000000000000..1b9cc5248e6ce3c0228ee1552e86b7f942cfd3f7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Gelu.h @@ -0,0 +1,83 @@ +#pragma once + +// On Windows, math.h needs to be included with _USE_MATH_DEFINES defined to +// access constants such as M_SQRT2 and M_2_SQRTPI. +#ifdef _WIN32 +#define _USE_MATH_DEFINES +#include +#include +#endif // _WIN32 + +#include +#include // For c10::is_reduced_floating_point_v. + +namespace at::native { +inline namespace CPU_CAPABILITY { +constexpr double kGeluBeta = M_SQRT2 * M_2_SQRTPI * 0.5; +constexpr double kGeluKappa = 0.044715; + +template +using reduced_fp_to_float_t = std::conditional_t, float, T>; + +template , bool> = true> +float reduced_fp_to_float(T x) { + return float(x); +} + +template , bool> = true> +T reduced_fp_to_float(T x) { + return x; +} + +template +T scalar_gelu_approximated_with_tanh(T x) { + using opmath_t = reduced_fp_to_float_t; + auto x_float = reduced_fp_to_float(x); + auto x_cube = x_float * x_float * x_float; + auto inner = opmath_t(kGeluBeta) * (x_float + opmath_t(kGeluKappa) * x_cube); + return opmath_t(0.5) * x_float * (opmath_t(1) + std::tanh(inner)); +} + +template , bool> = true> +vec::Vectorized vectorized_gelu_approximated_with_tanh(vec::Vectorized x) { + const vec::Vectorized kPointFiveVec(T(0.5)); + const vec::Vectorized kOneVec(T(1)); + const vec::Vectorized kGeluBetaVec((T(kGeluBeta))); + const vec::Vectorized kGeluKappaVec((T(kGeluKappa))); + auto x_cube = x * x * x; + vec::Vectorized inner_vec = kGeluBetaVec * (x + kGeluKappaVec * x_cube); + return kPointFiveVec * x * (kOneVec + inner_vec.tanh()); +} + +template , bool> = true> +vec::Vectorized vectorized_gelu_approximated_with_tanh(vec::Vectorized x) { + auto [x0, x1] = at::vec::convert_to_float(x); + return at::vec::convert_from_float( + vectorized_gelu_approximated_with_tanh(x0), + vectorized_gelu_approximated_with_tanh(x1)); +} + + +template +T scalar_gelu(T x) { + using opmath_t = reduced_fp_to_float_t; + const auto kAlpha = opmath_t(M_SQRT1_2); + return reduced_fp_to_float(x) * opmath_t(0.5) * (opmath_t(1) + std::erf(reduced_fp_to_float(x) * kAlpha)); +} + +template, bool> = true> +vec::Vectorized vectorized_gelu(vec::Vectorized x) { + const vec::Vectorized kAlphaVec(T(M_SQRT1_2)); + const vec::Vectorized kOneVec(T(1)); + const vec::Vectorized kPointFiveVec(T(0.5)); + return x * kPointFiveVec * (kOneVec + (x * kAlphaVec).erf()); +} + +template, bool> = true> +vec::Vectorized vectorized_gelu(vec::Vectorized x) { + auto [x0, x1] = at::vec::convert_to_float(x); + return at::vec::convert_from_float(vectorized_gelu(x0), vectorized_gelu(x1)); +} + +} // namespace CPU_CAPABILITY +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/GridSamplerKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/GridSamplerKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b46c9fd9eac068263f7c6875631de3b85dccad1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/GridSamplerKernel.cpp @@ -0,0 +1,1329 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace at::native { namespace { + +// fixes segfaults for GCC >= 12 on some AArch64 cpus https://github.com/pytorch/pytorch/issues/157626 +#if defined(__GNUC__) && __GNUC__ >= 12 && defined(__aarch64__) +#pragma GCC push_options +#pragma GCC optimize ("no-strict-aliasing") +#endif + +/** NOTE [ Grid Sample CPU Kernels ] + * + * Implementation of vectorized grid sample CPU kernels is divided into three + * parts. More detailed description exist after this paragraph, but on a high + * level, they are + * 1. `ComputeLocation` struct + * + Computes the interpolation location basing on padding mode. + * 2. `ApplyGridSample` struct + * + Owns N (# spatial dims) `ComputeLocation` structs, and uses them to + * compute the interpolation locations. + * + Interpolates the values and writes to output. + * 3. `grid_sample_2d_grid_slice_iterator` function + * + Iterates over a slice of the grid tensor based on the geometry by the + * spatial ordering, i.e., the first iteration will process grid values + * grid[n, 0, 0, :], grid[n, 0, 1, :], grid[n, 0, 2, :], ... + * (Recall that, e.g., 2D grid has shape [N x H x W x 2], so grid[n, ...] + * is a slice, and grid[n, h, w, :] contains the values for a single + * output spatial location.) + * + Applies a given operator at each iteration, so we can use the same + * pattern for forward and backward. + * + * Putting everything together, we have, e.g., the forward kernel implemented + * as + * + * // `ApplyGridSample` struct that processes grid values, extracts and + * // interpolates input values, and write to output. + * ApplyGridSample grid_sample(input_accessor); + * + * // For each slice, we call `grid_sample_2d_grid_slice_iterator` with + * // 1. the grid slice, and + * // 2. a lambda that takes in + * // i. location vectors (x and y for 2D) extracted from grid + * // ii. `spatial_offset` as the spatial offset of these vectors + * // from the beginning of this slice. + * // iii. `len` as the number of valid locations in the vectors. + * // (There might not be enough near boundary.) + * for (const auto n : c10::irange(input_accessor.size(0))) { + * grid_sample_2d_grid_slice_iterator( + * grid_accessor[n], + * [&](const Vectorized& grid_x, + * const Vectorized& grid_y, + * int64_t spatial_offset, int64_t len) { + * grid_sample.forward(out_accessor[n], input_accessor[n], + * spatial_offset, grid_x, grid_y, len); + * }); + * } + * + * Now we talk about details of each of these three parts: + * + * 1. `ComputeLocation` struct + * Transforms grid values into interpolation locations of the input tensor + * for a particular spatial dimension, based on the size of that dimension + * in input tensor, and the padding mode. + * + * template + * struct ComputeLocation { + * using Vec = Vectorized; + * + * // ctor + * ComputeLocation(int64_t size); + * + * // Given grid values `in`, return the interpolation locations after + * // un-normalization and padding mechanism (elementwise). + * Vec apply(const Vec &in) const; + * + * // Similar to `apply`, but also returns `d apply(in) / d in` + * // (elementwise). + * // this is often used in gradient computation. + * std::pair apply_get_grad(const Vec &in) const; + * }; + * + * 2. `ApplyGridSample` struct + * Owns N `ComputeLocation` structs, where N is the number of spatial + * dimensions. Given N input grid vectors (one for each spatial dimension) + * and spatial offset, it gets the interpolation locations from + * `ComputeLocation`s, applies interpolation procedure, and then writes to + * the output (or grad_input & grad_grid in backward). + * + * template + * struct ApplyGridSample { + * + * // ctor + * ApplyGridSample(const TensorAccessor& input); + * + * // Applies grid sampling (forward) procedure: + * // 1. computes interpolation locations from grid values `grid_x` + * // and `grid_y`, + * // 2. interpolates output values using the locations and input + * // data in `inp_slice`, and + * // 3. writes the first `len` values in the interpolated vector to + * // `out_slice` with spatial offset being `offset`. + * // + * // This assumes that `grid_x` and `grid_y` all contain valid grid + * // values \in [-1, 1], even at indices greater than `len`. + * // + * // The `*_slice` argument names mean samples within a batch (i.e., + * // with the batch dimension sliced out). + * void forward(TensorAccessor& out_slice, + * const TensorAccessor& inp_slice, + * int64_t offset, const Vec& grid_x, const Vec& grid_y, + * int64_t len) const; + * + * // Applies grid sampling (backward) procedure. Arguments semantics + * // and strategy are similar to those of `forward`, with the + * // exception that `backward` has branches based on whether `input` + * // requires gradient (passed in as a template parameter). The + * // TensorAccessor for the input gradient is also given as a + * // pointer instead of reference, so that it can be null if the + * // gradient is not calculated. + * template + * void backward(TensorAccessor* gInp_slice_ptr, + * TensorAccessor& gGrid_slice, + * const TensorAccessor& gOut_slice, + * const TensorAccessor& inp_slice, + * int64_t offset, const Vec& grid_x, const Vec& grid_y, + * int64_t len) const; + * }; + * + * 3. `grid_sample_2d_grid_slice_iterator` function + * Among the tensors we work with, we know that the output tensors are + * contiguous (i.e., `output` in forward, and `grad_input` & `grad_grid` in + * backward), we need to randomly read `input` anyways, and `grad_output` + * usually comes from autograd and is often contiguous. So we base our + * iterating strategy on the geometry of grid. + * `grid_sample_2d_grid_slice_iterator` function provides an abstraction to + * efficiently iterates through a `grid` slice (without batch dimension). + * See comments of that function on the specific cases and strategies used. + * + * template + * void grid_sample_2d_grid_slice_iterator( + * const TensorAccessor& grid_slice, + * const ApplyFn &apply_fn); + * + * `apply_fn` is a function/lambda that takes in + * i. location vectors (x and y for 2D) extracted from grid + * ii. `spatial_offset` as the spatial offset of these vectors + * from the beginning of this slice. + * iii. `len` as the number of valid locations in the vectors. + * (There might not be enough near boundary.) + + * It should be callable as if it has declaration: + * void apply_fn(const Vectorized& grid_x, + * const Vectorized& grid_y, + * int64_t spatial_offset, int64_t len); + * + * `apply_fn` will be called multiple times, and together cover the entire + * output spatial space. + * + * Now you should be able to understand everything about the implementation of + * 2D forward kernel shown at the beginning of this note. + * + **/ + + +using at::native::detail::GridSamplerInterpolation; +using at::native::detail::GridSamplerPadding; +using namespace at::vec; + + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComputeLocation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Struct to compute interpolation location from grid values, and to apply +// padding mechanism (e.g., reflection). +// See NOTE [ Grid Sample CPU Kernels ] for details. + +template +struct ComputeLocationBase; + +template +struct ComputeLocationBase { + using Vec = Vectorized; + + // values are clipped to between 0 and max_val + const scalar_t max_val; + // unnormalization scaling factor + const scalar_t scaling_factor; + // reflection parameters: reflected coordinates land in [low, low+span] inclusive + const scalar_t low; // only used when align_corners=False + const scalar_t twice_span; + // if the reflecting span is empty, all reflected coords are set to 0 + const bool empty; + + ComputeLocationBase(int64_t size) + : max_val(static_cast(size - 1)) + , scaling_factor(static_cast(size - 1) / 2) + , low(static_cast(0)) + , twice_span(static_cast(size - 1) * 2) + , empty(size <= 1) {} + + inline Vec unnormalize(const Vec &in) const { + return (in + Vec(1)) * Vec(scaling_factor); + } + + inline Vec clip_coordinates(const Vec &in) const { + // Invert order of clamp_min operands in order to clamp Nans to zero + return clamp_max(Vec(max_val), clamp_min(Vec(0), in)); + } + + // same as clip_coordinates but also returns the gradient multiplier + inline std::pair clip_coordinates_get_grad(const Vec &in) const { + using int_t = int_same_size_t; + auto bounded_lo = maximum(in, Vec(0)); + // Integral type equality comparison is very very fast because it just looks + // at the bits. Casting is free too. So we use the following pattern instead + // of comparison + blendv. + // Note that it is important for the gradient calculation that borders + // are considered out of bounds. + auto in_bound_lo = cast(cast(bounded_lo) != cast(Vec(0))); + auto res = minimum(bounded_lo, Vec(max_val)); + auto in_bound_hi = cast(cast(res) != cast(Vec(max_val))); + return std::make_pair(res, in_bound_lo & in_bound_hi); + } + + inline Vec reflect_coordinates(const Vec &in) const { + if (empty) { + return Vec(0); + } + Vec twice_span_vec(twice_span); + auto abs_in = in.abs(); + auto fdouble_flips = abs_in / twice_span_vec; + auto double_flips = fdouble_flips.trunc(); + auto extra = abs_in - double_flips * twice_span_vec; + // Now we need to test if extra > max_val to find out if another flip is + // needed. The following comparison does that and returns the correct + // flipped value. + return minimum(extra, twice_span_vec - extra); + } + + // same as reflect_coordinates but also returns the gradient multiplier + inline std::pair reflect_coordinates_get_grad(const Vec &in) const { + if (empty) { + return std::make_pair(Vec(0), Vec(0)); + } + Vec twice_span_vec(twice_span); + auto neg_in = in < Vec(0); + auto abs_in = in.abs(); + auto fdouble_flips = abs_in / twice_span_vec; + auto double_flips = fdouble_flips.trunc(); + + auto extra = abs_in - double_flips * twice_span_vec; + auto reflected_extra = twice_span_vec - extra; + auto one_more_flip = extra > reflected_extra; + + return std::make_pair( + Vec::blendv(extra, reflected_extra, one_more_flip), + Vec::blendv(Vec(1), Vec(-1), one_more_flip ^ neg_in) + ); + } +}; + +template +struct ComputeLocationBase { + using Vec = Vectorized; + + // values are clipped to between 0 and max_val + const scalar_t max_val; + // unnormalization scaling factor + const scalar_t scaling_factor; + // reflection parameters: reflected coordinates land in [low, low+span] inclusive + const scalar_t low; + const scalar_t twice_span; + // if the reflecting span is empty, all reflected coords are set to 0 + const bool empty; // only used when align_corners=True + + ComputeLocationBase(int64_t size) + : max_val(static_cast(size - 1)) + , scaling_factor(static_cast(size) / 2) + , low(static_cast(-0.5)) + , twice_span(static_cast(size) * 2) + , empty(size <= 0) {} + + inline Vec unnormalize(const Vec &in) const { + return (in + Vec(static_cast(1))) * Vec(scaling_factor) - Vec(static_cast(0.5)); + } + + inline Vec clip_coordinates(const Vec &in) const { + // Invert order of clamp_min operands in order to clamp Nans to zero + return clamp_max(Vec(max_val), clamp_min(Vec(0), in)); + } + + // same as clip_coordinates but also returns the gradient multiplier + inline std::pair clip_coordinates_get_grad(const Vec &in) const { + using int_t = int_same_size_t; + auto bounded_lo = maximum(in, Vec(0)); + // Integral type equality comparison is very very fast because it just looks + // at the bits. Casting is free too. So we use the following pattern instead + // of comparison + blendv. + // Note that it is important for the gradient calculation that borders + // are considered out of bounds. + auto in_bound_lo = cast(cast(bounded_lo) != cast(Vec(0))); + auto res = minimum(bounded_lo, Vec(max_val)); + auto in_bound_hi = cast(cast(res) != cast(Vec(max_val))); + return std::make_pair(res, in_bound_lo & in_bound_hi); + } + + inline Vec reflect_coordinates(const Vec &in) const { + Vec twice_span_vec(twice_span), low_vec(low); + // Since reflection is around low and low+span, subtract low before + // the reflection, and then add it back at the end. + auto abs_in = (in - low_vec).abs(); + auto fdouble_flips = abs_in / twice_span_vec; + auto double_flips = fdouble_flips.trunc(); + auto extra = abs_in - double_flips * twice_span_vec; + // Now we need to test if extra > max_val to find out if another flip is + // needed. The following comparison does that and returns the correct + // flipped value. + return minimum(extra, twice_span_vec - extra) + low_vec; + } + + // same as reflect_coordinates but also returns the gradient multiplier + inline std::pair reflect_coordinates_get_grad(const Vec &in) const { + Vec twice_span_vec(twice_span), low_vec(low); + Vec in_minus_low = in - low_vec; + auto neg_in = in_minus_low < Vec(0); + auto abs_in = in_minus_low.abs(); + auto fdouble_flips = abs_in / twice_span_vec; + auto double_flips = fdouble_flips.trunc(); + + auto extra = abs_in - double_flips * twice_span_vec; + auto reflected_extra = twice_span_vec - extra; + auto one_more_flip = extra > reflected_extra; + + return std::make_pair( + Vec::blendv(extra, reflected_extra, one_more_flip) + low_vec, + Vec::blendv(Vec(1), Vec(-1), one_more_flip ^ neg_in) + ); + } +}; + +template +struct ComputeLocation; + +template +struct ComputeLocation + : ComputeLocationBase { + using Vec = Vectorized; + using ComputeLocationBase::unnormalize; + using ComputeLocationBase::scaling_factor; + + using ComputeLocationBase::ComputeLocationBase; + + inline Vec apply(const Vec &in) const { + return unnormalize(in); + } + + inline Vec compute_coordinates(const Vec &in) const { + return in; + } + + inline std::pair apply_get_grad(const Vec &in) const { + return std::make_pair(unnormalize(in), Vec(scaling_factor)); + } +}; + +template +struct ComputeLocation + : ComputeLocationBase { + using Vec = Vectorized; + using ComputeLocationBase::unnormalize; + using ComputeLocationBase::clip_coordinates; + using ComputeLocationBase::clip_coordinates_get_grad; + using ComputeLocationBase::scaling_factor; + + using ComputeLocationBase::ComputeLocationBase; + + inline Vec apply(const Vec &in) const { + return clip_coordinates(unnormalize(in)); + } + + inline Vec compute_coordinates(const Vec &in) const { + return clip_coordinates(in); + } + + inline std::pair apply_get_grad(const Vec &in) const { + auto [res, grad_clip] = clip_coordinates_get_grad(unnormalize(in)); + return std::make_pair(res, grad_clip & Vec(scaling_factor)); + } +}; + +template +struct ComputeLocation + : ComputeLocationBase { + using Vec = Vectorized; + using ComputeLocationBase::unnormalize; + using ComputeLocationBase::clip_coordinates; + using ComputeLocationBase::clip_coordinates_get_grad; + using ComputeLocationBase::reflect_coordinates; + using ComputeLocationBase::reflect_coordinates_get_grad; + using ComputeLocationBase::scaling_factor; + + using ComputeLocationBase::ComputeLocationBase; + + inline Vec apply(const Vec &in) const { + auto res = reflect_coordinates(unnormalize(in)); + res = clip_coordinates(res); + return res; + } + + inline Vec compute_coordinates(const Vec &in) const { + auto res = reflect_coordinates(in); + res = clip_coordinates(res); + return res; + } + + inline std::pair apply_get_grad(const Vec &in) const { + auto [res, grad_refl] = reflect_coordinates_get_grad(unnormalize(in)); + Vec grad(scaling_factor); + grad = grad_refl * grad; + auto [res2, grad_clip] = clip_coordinates_get_grad(res); + grad = grad_clip & grad; + return std::make_pair(res2, grad); + } +}; + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ApplyGridSample ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Struct to apply grid sample (reading from input, interpolate, and write to +// output). +// See NOTE [ Grid Sample CPU Kernels ] for details. + +template +inline void +mask_scatter_add(const scalar_t *src, scalar_t* base_addr, + const int_same_size_t *offsets, + const int_same_size_t *mask, int64_t len) { + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto i : c10::irange(len)) { + if (mask[i] & 0x01) { + base_addr[offsets[i]] += src[i]; + } + } +} + +template +struct ApplyGridSample; + +template +struct ApplyGridSample { + using Vec = Vectorized; + using integer_t = int_same_size_t; + using iVec = Vectorized; + + const int64_t inp_H; + const int64_t inp_W; + const int64_t inp_sH; + const int64_t inp_sW; + const int64_t C; + const int64_t inp_sC; + const ComputeLocation compute_H; + const ComputeLocation compute_W; + const bool must_in_bound = padding != GridSamplerPadding::Zeros; + + ApplyGridSample(const TensorAccessor& input) + : inp_H(input.size(2)) + , inp_W(input.size(3)) + , inp_sH(input.stride(2)) + , inp_sW(input.stride(3)) + , C(input.size(1)) + , inp_sC(input.stride(1)) + , compute_H(input.size(2)) + , compute_W(input.size(3)) {} + + inline std::tuple< + Vec, Vec, Vec, Vec, // distances to 4 sides + Vec, Vec, Vec, Vec, // interpolation weights wrt 4 corners + Vec, Vec, Vec, Vec, // in_bound masks + iVec, iVec // y_n and x_w + > + compute_interp_params(const Vec& x, const Vec& y) const { + // get NE, NW, SE, SW pixel values from (x, y) + // assuming we get exact integer representation and just use scalar_t + // if we don't, the weights will be garbage anyways. + auto x_w = x.floor(); + auto y_n = y.floor(); + + // get distances to each side + auto w = x - x_w; + auto e = Vec(1) - w; + auto n = y - y_n; + auto s = Vec(1) - n; + + // get interpolation weights for each neighbor + // e.g., for the nw corner, the weight is `dist_to_south * dist_to_east`. + auto nw = s * e; + auto ne = s * w; + auto sw = n * e; + auto se = n * w; + + auto i_x_w = convert_to_int_of_same_size(x_w); + auto i_y_n = convert_to_int_of_same_size(y_n); + auto i_x_e = i_x_w + iVec(1); + auto i_y_s = i_y_n + iVec(1); + + // Use int comparison because it is much faster than float comp with AVX2 + // (latency 1 cyc vs. 4 cyc on skylake) + // Avoid using the le and ge because those are not implemented in AVX2 and + // are actually simulated using multiple instructions. + auto w_mask = must_in_bound ? iVec(-1) // true = all ones + : (i_x_w > iVec(-1)) & (i_x_w < iVec(inp_W)); + auto n_mask = must_in_bound ? iVec(-1) // true = all ones + : (i_y_n > iVec(-1)) & (i_y_n < iVec(inp_H)); + auto e_mask = must_in_bound ? (i_x_e < iVec(inp_W)) + : (i_x_e > iVec(-1)) & (i_x_e < iVec(inp_W)); + auto s_mask = must_in_bound ? (i_y_s < iVec(inp_H)) + : (i_y_s > iVec(-1)) & (i_y_s < iVec(inp_H)); + auto nw_mask = cast(must_in_bound ? iVec(-1) : (w_mask & n_mask)); + auto ne_mask = cast(e_mask & n_mask); + auto sw_mask = cast(w_mask & s_mask); + auto se_mask = cast(e_mask & s_mask); + + return std::make_tuple( + n, s, w, e, + nw, ne, sw, se, + nw_mask, ne_mask, sw_mask, se_mask, + i_y_n, i_x_w); + } + + inline void forward(TensorAccessor& out_slice, + const TensorAccessor& inp_slice, + int64_t offset, const Vec& grid_x, const Vec& grid_y, + int64_t len) const { + auto x = compute_W.apply(grid_x); + auto y = compute_H.apply(grid_y); + + auto interp_params = compute_interp_params(x, y); + + auto nw = std::get<4>(interp_params); + auto ne = std::get<5>(interp_params); + auto sw = std::get<6>(interp_params); + auto se = std::get<7>(interp_params); + + auto nw_mask = std::get<8>(interp_params); + auto ne_mask = std::get<9>(interp_params); + auto sw_mask = std::get<10>(interp_params); + auto se_mask = std::get<11>(interp_params); + + auto i_y_n = std::get<12>(interp_params); + auto i_x_w = std::get<13>(interp_params); + + auto i_nw_offset = i_y_n * iVec(inp_sH) + i_x_w * iVec(inp_sW); + auto i_ne_offset = i_nw_offset + iVec(inp_sW); + auto i_sw_offset = i_nw_offset + iVec(inp_sH); + auto i_se_offset = i_sw_offset + iVec(inp_sW); + + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto c : c10::irange(C)) { + auto inp_slice_C_ptr = inp_slice[c].data(); + + // mask_gather zeros out the mask, so we need to make copies + Vec nw_mask_copy = nw_mask; + Vec ne_mask_copy = ne_mask; + Vec sw_mask_copy = sw_mask; + Vec se_mask_copy = se_mask; + auto nw_val = mask_gather(Vec(0), inp_slice_C_ptr, i_nw_offset, nw_mask_copy); + auto ne_val = mask_gather(Vec(0), inp_slice_C_ptr, i_ne_offset, ne_mask_copy); + auto sw_val = mask_gather(Vec(0), inp_slice_C_ptr, i_sw_offset, sw_mask_copy); + auto se_val = mask_gather(Vec(0), inp_slice_C_ptr, i_se_offset, se_mask_copy); + + auto interpolated = (nw_val * nw) + (ne_val * ne) + (sw_val * sw) + (se_val * se); + interpolated.store(out_slice[c].data() + offset, len); + } + } + + template + inline void backward(TensorAccessor* gInp_slice_ptr, + TensorAccessor& gGrid_slice, + const TensorAccessor& gOut_slice, + const TensorAccessor& inp_slice, + int64_t offset, const Vec& grid_x, const Vec& grid_y, + int64_t len) const { + auto [x, gx_mult] = compute_W.apply_get_grad(grid_x); + auto [y, gy_mult] = compute_H.apply_get_grad(grid_y); + + auto [ + n, s, w, e, nw, ne, sw, se, nw_mask, ne_mask, sw_mask, se_mask, + i_y_n, i_x_w] = compute_interp_params(x, y); + + auto i_nw_offset = i_y_n * iVec(inp_sH) + i_x_w * iVec(inp_sW); + auto i_ne_offset = i_nw_offset + iVec(inp_sW); + auto i_sw_offset = i_nw_offset + iVec(inp_sH); + auto i_se_offset = i_sw_offset + iVec(inp_sW); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_nw_mask_arr[iVec::size()]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_ne_mask_arr[iVec::size()]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_sw_mask_arr[iVec::size()]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_se_mask_arr[iVec::size()]; + nw_mask.store(i_nw_mask_arr); + ne_mask.store(i_ne_mask_arr); + sw_mask.store(i_sw_mask_arr); + se_mask.store(i_se_mask_arr); + + // i_gInp_*_offset_arr and gInp_corner_arr variables below are unnecessary + // when input_requires_grad is false (they are only used within the + // if-blocks), but required to make the code well-formed. + + // When reading input values, we used mask_gather. Unfortunately, there is + // no mask_scatter_add (the backward of mask_gather) in Intel intrinsics. + // So we store the necessary vectors to temporary arrays and use the helper + // mask_scatter_add defined above. + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_gInp_nw_offset_arr[iVec::size()]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_gInp_ne_offset_arr[iVec::size()]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_gInp_sw_offset_arr[iVec::size()]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_gInp_se_offset_arr[iVec::size()]; + if (input_requires_grad) { + auto i_gInp_nw_offset = i_y_n * iVec(inp_W) + i_x_w; + auto i_gInp_ne_offset = i_gInp_nw_offset + iVec(1); + auto i_gInp_sw_offset = i_gInp_nw_offset + iVec(inp_W); + auto i_gInp_se_offset = i_gInp_sw_offset + iVec(1); + + i_gInp_nw_offset.store(i_gInp_nw_offset_arr); + i_gInp_ne_offset.store(i_gInp_ne_offset_arr); + i_gInp_sw_offset.store(i_gInp_sw_offset_arr); + i_gInp_se_offset.store(i_gInp_se_offset_arr); + } + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t gInp_corner_arr[Vec::size()]; + + auto gx = Vec(0), gy = Vec(0); + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto c : c10::irange(C)) { + auto inp_slice_C_ptr = inp_slice[c].data(); + auto gOut = Vec::loadu(gOut_slice[c].data() + offset, len); + + if (input_requires_grad) { + TORCH_INTERNAL_ASSERT(gInp_slice_ptr); + auto gInp_slice_C_ptr = (*gInp_slice_ptr)[c].data(); + + (nw * gOut).store(gInp_corner_arr); + mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_nw_offset_arr, i_nw_mask_arr, len); + (ne * gOut).store(gInp_corner_arr); + mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_ne_offset_arr, i_ne_mask_arr, len); + (sw * gOut).store(gInp_corner_arr); + mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_sw_offset_arr, i_sw_mask_arr, len); + (se * gOut).store(gInp_corner_arr); + mask_scatter_add(gInp_corner_arr, gInp_slice_C_ptr, i_gInp_se_offset_arr, i_se_mask_arr, len); + } + + // mask_gather zeros out the mask, so we need to make copies + Vec nw_mask_copy = nw_mask; + Vec ne_mask_copy = ne_mask; + Vec sw_mask_copy = sw_mask; + Vec se_mask_copy = se_mask; + auto nw_val = mask_gather(Vec(0), inp_slice_C_ptr, i_nw_offset, nw_mask_copy); + auto ne_val = mask_gather(Vec(0), inp_slice_C_ptr, i_ne_offset, ne_mask_copy); + auto sw_val = mask_gather(Vec(0), inp_slice_C_ptr, i_sw_offset, sw_mask_copy); + auto se_val = mask_gather(Vec(0), inp_slice_C_ptr, i_se_offset, se_mask_copy); + + gx = gx + ((ne_val - nw_val) * s + (se_val - sw_val) * n) * gOut; + gy = gy + ((sw_val - nw_val) * e + (se_val - ne_val) * w) * gOut; + } + + gx = gx * gx_mult; + gy = gy * gy_mult; + + constexpr int64_t step = Vec::size(); + auto interleaved_gGrid = interleave2(gx, gy); + auto gGrid_ptr = gGrid_slice.data() + offset * 2; + std::get<0>(interleaved_gGrid).store(gGrid_ptr, + std::min(len * 2, step)); + std::get<1>(interleaved_gGrid).store(gGrid_ptr + step, + std::max(static_cast(0), len * 2 - step)); + } +}; + +template +struct ApplyGridSample { + using Vec = Vectorized; + using integer_t = int_same_size_t; + using iVec = Vectorized; + + const int64_t inp_H; + const int64_t inp_W; + const int64_t inp_sH; + const int64_t inp_sW; + const int64_t C; + const int64_t inp_sC; + const ComputeLocation compute_H; + const ComputeLocation compute_W; + const bool must_in_bound = padding != GridSamplerPadding::Zeros; + + ApplyGridSample(const TensorAccessor& input) + : inp_H(input.size(2)) + , inp_W(input.size(3)) + , inp_sH(input.stride(2)) + , inp_sW(input.stride(3)) + , C(input.size(1)) + , inp_sC(input.stride(1)) + , compute_H(input.size(2)) + , compute_W(input.size(3)) {} + + inline void forward(TensorAccessor& out_slice, + const TensorAccessor& inp_slice, + int64_t offset, const Vec& grid_x, const Vec& grid_y, + int64_t len) const { + auto x = compute_W.apply(grid_x); + auto y = compute_H.apply(grid_y); + + auto x_nearest = x.round(); + auto y_nearest = y.round(); + + auto i_x_nearest = convert_to_int_of_same_size(x_nearest); + auto i_y_nearest = convert_to_int_of_same_size(y_nearest); + + auto i_mask = must_in_bound ? iVec(-1) + : (i_x_nearest > iVec(-1)) & (i_x_nearest < iVec(inp_W)) & + (i_y_nearest > iVec(-1)) & (i_y_nearest < iVec(inp_H)); + auto mask = cast(i_mask); + + auto i_offset = i_y_nearest * iVec(inp_sH) + i_x_nearest * iVec(inp_sW); + + auto out_ptr = out_slice.data() + offset; + auto out_sC = out_slice.stride(0); + auto inp_slice_ptr = inp_slice.data(); + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (int64_t c = 0; c < C; ++c, out_ptr += out_sC, inp_slice_ptr += inp_sC) { + // mask_gather zeros out the mask, so we need to make a copy + auto mask_copy = mask; + auto inp_val = mask_gather(Vec(0), inp_slice_ptr, i_offset, mask_copy); + inp_val.store(static_cast(out_ptr), len); + } + } + + template + inline void backward(TensorAccessor* gInp_slice_ptr, + TensorAccessor& gGrid_slice, + const TensorAccessor& gOut_slice, + const TensorAccessor& /*inp_slice*/, + int64_t offset, const Vec& grid_x, const Vec& grid_y, + int64_t len) const { + if (input_requires_grad) { + auto x = compute_W.apply(grid_x); + auto y = compute_H.apply(grid_y); + + auto x_nearest = x.round(); + auto y_nearest = y.round(); + + auto i_x_nearest = convert_to_int_of_same_size(x_nearest); + auto i_y_nearest = convert_to_int_of_same_size(y_nearest); + + auto i_mask = must_in_bound ? iVec(-1) + : (i_x_nearest > iVec(-1)) & (i_x_nearest < iVec(inp_W)) & + (i_y_nearest > iVec(-1)) & (i_y_nearest < iVec(inp_H)); + + auto i_gInp_offset = i_y_nearest * iVec(inp_W) + i_x_nearest; // gInp is contiguous + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t mask_arr[iVec::size()]; + i_mask.store(mask_arr); + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t gInp_offset_arr[iVec::size()]; + i_gInp_offset.store(gInp_offset_arr); + + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto c : c10::irange(C)) { + mask_scatter_add(gOut_slice[c].data() + offset, (*gInp_slice_ptr)[c].data(), + gInp_offset_arr, mask_arr, len); + } + } + + // grid has zero 0 gradient in Nearest mode + auto gGrid_ptr = gGrid_slice.data() + offset * 2; + std::memset(gGrid_ptr, 0, sizeof(scalar_t) * len * 2); + } +}; + +// Use bicubic convolution algorithm. Based on +// https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm +template +struct ApplyGridSample { + using Vec = Vectorized; + using integer_t = int_same_size_t; + using iVec = Vectorized; + + const int64_t inp_H; + const int64_t inp_W; + const int64_t inp_sH; + const int64_t inp_sW; + const int64_t C; + const int64_t inp_sC; + const ComputeLocation compute_H; + const ComputeLocation compute_W; + const bool must_in_bound = padding != GridSamplerPadding::Zeros; + + // constant used in cubic convolution + // could be -0.5 or -0.75, use the same value in UpSampleBicubic2d.h + const Vec A = Vec(static_cast(-0.75)); + + ApplyGridSample(const TensorAccessor& input) + : inp_H(input.size(2)) + , inp_W(input.size(3)) + , inp_sH(input.stride(2)) + , inp_sW(input.stride(3)) + , C(input.size(1)) + , inp_sC(input.stride(1)) + , compute_H(input.size(2)) + , compute_W(input.size(3)) {} + + // Calculate the cubic convolution coefficient + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + inline void get_cubic_coefficients(Vec (&coeffs)[4], const Vec& tx) const { + Vec x; + x = tx + Vec(1); // 1 < x = |-1 - tx| < 2 + coeffs[0] = ((A * x - Vec(5) * A) * x + Vec(8) * A) * x - Vec(4) * A; + x = tx; // x = |0 - tx| <= 1 + coeffs[1] = ((A + Vec(2)) * x - (A + Vec(3))) * x * x + Vec(1); + x = Vec(1) - tx; // x = |1 - tx| <= 1 + coeffs[2] = ((A + Vec(2)) * x - (A + Vec(3))) * x * x + Vec(1); + x = Vec(2) - tx; // 1 < x = |2 - tx| < 2 + coeffs[3] = ((A * x - Vec(5) * A) * x + Vec(8) * A) * x - Vec(4) * A; + } + + // Calculate the differential of the cubic convolution, i.e. `d coeff / d x` + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + inline void get_cubic_coefficients_grad(Vec (&coeffs)[4], const Vec& tx) const { + Vec x; + x = Vec(-1) - tx; // 1 < x = |-1 - tx| < 2 + coeffs[0] = (Vec(-3) * A * x - Vec(10) * A ) * x - Vec(8) * A; + x = Vec(0) - tx; // x = |0 - tx| <= 1 + coeffs[1] = (Vec(-3) * (A + Vec(2)) * x - Vec(2) * (A + Vec(3))) * x; + x = Vec(1) - tx; // x = |1 - tx| <= 1 + coeffs[2] = (Vec(3) * (A + Vec(2)) * x - Vec(2) * (A + Vec(3))) * x; + x = Vec(2) - tx; // 1 < x = |2 - tx| < 2 + coeffs[3] = (Vec(3) * A * x - Vec(10) * A) * x + Vec(8) * A; + } + + inline Vec get_value_bounded(const scalar_t* data, const Vec& x, const Vec& y) const { + auto ix = convert_to_int_of_same_size(compute_W.compute_coordinates(x)); + auto iy = convert_to_int_of_same_size(compute_H.compute_coordinates(y)); + + auto mask_x = must_in_bound ? iVec(-1) : (ix > iVec(-1)) & (ix < iVec(inp_W)); + auto mask_y = must_in_bound ? iVec(-1) : (iy > iVec(-1)) & (iy < iVec(inp_H)); + auto mask = cast(mask_x & mask_y); + + auto offset = iy * iVec(inp_sH) + ix * iVec(inp_sW); + + auto val = mask_gather(Vec(0), data, offset, mask); + return val; + } + + inline void add_value_bounded(scalar_t* data, int64_t len, const Vec& x, const Vec&y, + const Vec& delta) const { + + auto ix = convert_to_int_of_same_size(compute_W.compute_coordinates(x)); + auto iy = convert_to_int_of_same_size(compute_H.compute_coordinates(y)); + + auto mask_x = must_in_bound ? iVec(-1) : (ix > iVec(-1)) & (ix < iVec(inp_W)); + auto mask_y = must_in_bound ? iVec(-1) : (iy > iVec(-1)) & (iy < iVec(inp_H)); + auto mask = cast(mask_x & mask_y); + + auto i_gInp_offset = iy * iVec(inp_W) + ix; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t i_gInp_offset_arr[iVec::size()]; + i_gInp_offset.store(i_gInp_offset_arr); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + integer_t mask_arr[iVec::size()]; + mask.store(mask_arr); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + scalar_t gInp_corner_arr[Vec::size()]; + delta.store(gInp_corner_arr); + + mask_scatter_add(gInp_corner_arr, data, i_gInp_offset_arr, mask_arr, len); + } + + inline void forward(TensorAccessor& out_slice, + const TensorAccessor& inp_slice, + int64_t offset, const Vec& grid_x, const Vec& grid_y, + int64_t len) const { + + auto x = compute_W.unnormalize(grid_x); + auto y = compute_H.unnormalize(grid_y); + + auto ix = x.floor(); + auto iy = y.floor(); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec coeff_x[4]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec coeff_y[4]; + get_cubic_coefficients(coeff_x, x - ix); + get_cubic_coefficients(coeff_y, y - iy); + + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto c : c10::irange(C)) { + auto inp_slice_C_ptr = inp_slice[c].data(); + + // Interpolate the 4 values in the x direction + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec interp_x[4]; + for (const auto i : c10::irange(4)) { + interp_x[i] = + coeff_x[0] * get_value_bounded(inp_slice_C_ptr, ix - Vec(1), iy + Vec(-1 + i)) + + coeff_x[1] * get_value_bounded(inp_slice_C_ptr, ix + Vec(0), iy + Vec(-1 + i)) + + coeff_x[2] * get_value_bounded(inp_slice_C_ptr, ix + Vec(1), iy + Vec(-1 + i)) + + coeff_x[3] * get_value_bounded(inp_slice_C_ptr, ix + Vec(2), iy + Vec(-1 + i)); + } + + // Interpolate the 4 values in the y direction + auto interpolated = coeff_y[0] * interp_x[0] + coeff_y[1] * interp_x[1] + + coeff_y[2] * interp_x[2] + coeff_y[3] * interp_x[3]; + interpolated.store(out_slice[c].data() + offset, len); + } + } + + template + inline void backward(TensorAccessor* gInp_slice_ptr, + TensorAccessor& gGrid_slice, + const TensorAccessor& gOut_slice, + const TensorAccessor& inp_slice, + int64_t offset, const Vec& grid_x, const Vec& grid_y, + int64_t len) const { + Vec x = compute_W.unnormalize(grid_x); + Vec y = compute_H.unnormalize(grid_y); + Vec gx_mult = Vec(compute_W.scaling_factor); + Vec gy_mult = Vec(compute_H.scaling_factor); + + auto ix = x.floor(); + auto iy = y.floor(); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec coeff_x[4]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec coeff_y[4]; + get_cubic_coefficients(coeff_x, x - ix); + get_cubic_coefficients(coeff_y, y - iy); + + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec coeff_x_grad[4]; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + Vec coeff_y_grad[4]; + get_cubic_coefficients_grad(coeff_x_grad, x - ix); + get_cubic_coefficients_grad(coeff_y_grad, y - iy); + + auto gx = Vec(0), gy = Vec(0); + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto c : c10::irange(C)) { + auto inp_slice_C_ptr = inp_slice[c].data(); + auto gOut = Vec::loadu(gOut_slice[c].data() + offset, len); + + for (const auto i : c10::irange(4)) { + for (const auto j : c10::irange(4)) { + auto xx = ix + Vec(-1 + i); + auto yy = iy + Vec(-1 + j); + + if (input_requires_grad) { + auto gInp_slice_C_ptr = (*gInp_slice_ptr)[c].data(); + add_value_bounded(gInp_slice_C_ptr, len, xx, yy, gOut * coeff_x[i] * coeff_y[j]); + } + + auto val = get_value_bounded(inp_slice_C_ptr, xx, yy); + gx = gx - val * gOut * coeff_x_grad[i] * coeff_y[j]; + gy = gy - val * gOut * coeff_y_grad[j] * coeff_x[i]; + } + } + } + + gx = gx * gx_mult; + gy = gy * gy_mult; + + constexpr int64_t step = Vec::size(); + auto interleaved_gGrid = interleave2(gx, gy); + auto gGrid_ptr = gGrid_slice.data() + offset * 2; + std::get<0>(interleaved_gGrid).store(gGrid_ptr, + std::min(len * 2, step)); + std::get<1>(interleaved_gGrid).store(gGrid_ptr + step, + std::max(static_cast(0), len * 2 - step)); + } +}; + +#if defined(__GNUC__) && __GNUC__ >= 12 && defined(__aarch64__) +#pragma GCC pop_options +#endif + +// ~~~~~~~~~~~~~~~~~~ grid_sample_2d_grid_slice_iterator ~~~~~~~~~~~~~~~~~~~~~~ +// Function to apply a vectorized function on a grid slice tensor (without batch +// dimension). +// See NOTE [ Grid Sample CPU Kernels ] for details. + +template +inline void grid_sample_2d_grid_slice_iterator( + const TensorAccessor& grid_slice, const ApplyFn &apply_fn) { + int64_t out_H = grid_slice.size(0); + int64_t out_W = grid_slice.size(1); + int64_t grid_sH = grid_slice.stride(0); + int64_t grid_sW = grid_slice.stride(1); + int64_t grid_sCoor = grid_slice.stride(2); + auto grid_ptr = grid_slice.data(); + + using Vec = Vectorized; + using iVec = Vectorized>; + constexpr int64_t step = Vec::size(); + + // Loop over each output pixel in grid. + // We consider the following three cases (after slicing out the batch + // dimension). + // See detailed discussions under each if-case. + + if (at::geometry_is_contiguous({out_H, out_W, 2}, {grid_sH, grid_sW, grid_sCoor})) { + // Case 1: + // Grid is contiguous. + // Strategy: Sequentially load two vectors at the same time, and get, + // e.g., {x0, y0, x1, y1}, {x2, y2, x3, y3}. Then we use + // at::vec::deinterleave2 to get x and y vectors. + auto total_size = out_H * out_W; + for (int64_t spatial_offset = 0; spatial_offset < total_size; spatial_offset += step) { + auto grid_offset = spatial_offset * 2; + auto len = std::min(step, total_size - spatial_offset); + auto vec1 = Vec::loadu(grid_ptr + grid_offset, + std::min(step, len * 2)); + auto vec2 = Vec::loadu(grid_ptr + grid_offset + step, + std::max(static_cast(0), len * 2 - step)); + auto [x, y] = deinterleave2(vec1, vec2); + + // make sure that x and y are valid grid sample locations + if (len < step) { + x = Vec::set(Vec(0), x, len); + y = Vec::set(Vec(0), y, len); + } + apply_fn(x, y, spatial_offset, len); + } + } else if (grid_sW == 1 || out_W == 1) { + // Case 2: + // The W dimension is contiguous. + // This can be common, e.g., grid is from a conv net output of shape + // [N, 2, H, W]. + // Strategy: Divide into two contiguous slices each of shape [H, W], and + // each containing x and y vectors. So we sequentially load a + // vector from each of them to get x and y vector + + // Function to apply along a contiguous W dimension (or flattened H x W). + auto line_fn = [&](const scalar_t *grid_ptr_x, const scalar_t *grid_ptr_y, + int64_t out_base_offset, int64_t total_size) { + for (int64_t i = 0; i < total_size; i += step) { + auto len = std::min(step, total_size - i); + auto x = Vec::loadu(grid_ptr_x + i, len); + auto y = Vec::loadu(grid_ptr_y + i, len); + // make sure that x and y are valid grid sample locations + if (len < step) { + x = Vec::set(Vec(0), x, len); + y = Vec::set(Vec(0), y, len); + } + apply_fn(x, y, out_base_offset + i, len); + } + }; + + if (at::geometry_is_contiguous({out_H, out_W}, {grid_sH, grid_sW})) { + // If [H, W] is contiguous, apply line_fn once. + line_fn(grid_ptr, grid_ptr + grid_sCoor, 0, out_H * out_W); + } else { + // If only [W] is contiguous, apply line_fn once for each h slice. + auto grid_ptr_NH = grid_ptr; + for (const auto h : c10::irange(out_H)) { + line_fn(grid_ptr_NH, grid_ptr_NH + grid_sCoor, h * out_W, out_W); + grid_ptr_NH += grid_sH; + } + } + } else { + // Case 3: + // General case. + // Strategy: Do a for-loop over H, for each W slice, use + // at::vec::gather to load the x and y vectors. + int64_t spatial_offset = 0; + const int64_t i_offset_delta = grid_sW * step; + + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto h : c10::irange(out_H)) { + auto grid_ptr_x = grid_ptr + h * grid_sH; + auto grid_ptr_y = grid_ptr_x + grid_sCoor; + auto i_offsets = iVec::arange(0, grid_sW); + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (int64_t w = 0; w < out_W; w += step) { + auto len = std::min(step, out_W - w); + if (len < step) { + // prevents illegal memory access, sets the exceeding offsets to zero + i_offsets = iVec::set(iVec(0), i_offsets, len); + } + apply_fn(vec::gather(grid_ptr_x, i_offsets), + vec::gather(grid_ptr_y, i_offsets), + spatial_offset, len); + + grid_ptr_x += i_offset_delta; + grid_ptr_y += i_offset_delta; + spatial_offset += len; + } + } + } +} + +// ~~~~~~~~~~~~~~~~~~~~~~~~~ Grid Sample Kernels ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// Use the structs & functions defined above to calculate grid sample forward +// and backward. +// See NOTE [ Grid Sample CPU Kernels ] for details. + +void grid_sampler_2d_cpu_kernel_impl( + const TensorBase &output, const TensorBase &input, const TensorBase &grid, + int64_t interpolation_mode, int64_t padding_mode, bool align_corners) { + auto N = input.size(0); + auto H = grid.size(1); + auto W = grid.size(2); + auto spatial_size = H * W; + auto grain_size = spatial_size == 0 ? (N + 1) + : at::divup(at::internal::GRAIN_SIZE, spatial_size * 4 /* 2d * 2 tensors*/); + if (output.numel() == 0) { + return; + } + +#define HANDLE_CASE(interp, padding, align_corners) \ + case padding: { \ + ApplyGridSample \ + grid_sample(inp_acc); \ + parallel_for(0, N, grain_size, [&](int64_t begin, int64_t end) { \ + for (const auto n : c10::irange(begin, end)) { \ + auto out_slice = out_acc[n]; \ + auto inp_slice = inp_acc[n]; \ + grid_sample_2d_grid_slice_iterator( \ + grid_acc[n], \ + [&](const Vectorized& grid_x, const Vectorized& grid_y, \ + int64_t spatial_offset, int64_t len) { \ + grid_sample.forward(out_slice, inp_slice, spatial_offset, \ + grid_x, grid_y, len); \ + }); \ + } \ + }); \ + return; \ + } + +#define HANDLE_INTERP(interp, align_corners) \ + case interp: { \ + switch (static_cast(padding_mode)) { \ + HANDLE_CASE(interp, GridSamplerPadding::Zeros, align_corners); \ + HANDLE_CASE(interp, GridSamplerPadding::Border, align_corners); \ + HANDLE_CASE(interp, GridSamplerPadding::Reflection, align_corners); \ + } \ + return; \ + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "grid_sampler_2d_cpu_kernel_impl", [&] { + auto out_acc = output.accessor(); + auto inp_acc = input.accessor(); + auto grid_acc = grid.accessor(); + if (align_corners) { + switch (static_cast(interpolation_mode)) { + HANDLE_INTERP(GridSamplerInterpolation::Bilinear, true); + HANDLE_INTERP(GridSamplerInterpolation::Nearest, true); + HANDLE_INTERP(GridSamplerInterpolation::Bicubic, true); + } + } else { + switch (static_cast(interpolation_mode)) { + HANDLE_INTERP(GridSamplerInterpolation::Bilinear, false); + HANDLE_INTERP(GridSamplerInterpolation::Nearest, false); + HANDLE_INTERP(GridSamplerInterpolation::Bicubic, false); + } + } + }); +#undef HANDLE_CASE +#undef HANDLE_INTERP +} + +void grid_sampler_2d_backward_cpu_kernel_impl( + const TensorBase &grad_input, + const TensorBase &grad_grid, + const TensorBase &grad_output_, + const TensorBase &input, + const TensorBase &grid, + int64_t interpolation_mode, + int64_t padding_mode, + bool align_corners, + std::array output_mask) { + if (grad_output_.numel() == 0) { + grad_grid.zero_(); + return; + } + // grad_output should be contiguous most of time. Ensuring that it is + // contiguous can greatly simplify this code. + auto grad_output = grad_output_.contiguous(); + + // If `input` gradient is not required, we skip computing it -- not needing to create + // the tensor to hold the gradient can markedly increase performance. (`grid` gradient + // is always computed.) + auto input_requires_grad = output_mask[0]; + + auto N = input.size(0); + auto spatial_size = grid.size(1) * grid.size(2); + auto grain_size = spatial_size == 0 ? (N + 1) + : at::divup(at::internal::GRAIN_SIZE, spatial_size * 10 /* 2d * 5 tensors*/); + +#define GINP_SLICE_PTR_true auto gInp_slice = gInp_acc[n]; auto gInp_slice_ptr = &gInp_slice; +#define GINP_SLICE_PTR_false TensorAccessor* gInp_slice_ptr = nullptr; +#define GINP_SLICE_PTR(input_requires_grad) GINP_SLICE_PTR_##input_requires_grad + +#define HANDLE_CASE(interp, padding, align_corners, input_requires_grad) \ + case padding: { \ + ApplyGridSample \ + grid_sample(inp_acc); \ + parallel_for(0, N, grain_size, [&](int64_t begin, int64_t end) { \ + for (const auto n : c10::irange(begin, end)) { \ + GINP_SLICE_PTR(input_requires_grad) \ + auto gGrid_slice = gGrid_acc[n]; \ + auto gOut_slice = gOut_acc[n]; \ + auto inp_slice = inp_acc[n]; \ + grid_sample_2d_grid_slice_iterator( \ + grid_acc[n], \ + [&](const Vectorized& grid_x, const Vectorized& grid_y, \ + int64_t spatial_offset, int64_t len) { \ + grid_sample.backward(gInp_slice_ptr, gGrid_slice, \ + gOut_slice, inp_slice, \ + spatial_offset, grid_x, \ + grid_y, len); \ + }); \ + } \ + }); \ + return; \ + } + +#define HANDLE_INTERP(interp, align_corners, input_requires_grad) \ + case interp: { \ + switch (static_cast(padding_mode)) { \ + HANDLE_CASE(interp, GridSamplerPadding::Zeros, align_corners, input_requires_grad); \ + HANDLE_CASE(interp, GridSamplerPadding::Border, align_corners, input_requires_grad); \ + HANDLE_CASE(interp, GridSamplerPadding::Reflection, align_corners, input_requires_grad); \ + } \ + return; \ + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "grid_sampler_2d_backward_cpu_kernel_impl", [&] { + auto gGrid_acc = grad_grid.accessor(); + auto inp_acc = input.accessor(); + auto grid_acc = grid.accessor(); + auto gOut_acc = grad_output.accessor(); + if (input_requires_grad) { + auto gInp_acc = grad_input.accessor(); + if (align_corners) { + switch (static_cast(interpolation_mode)) { + HANDLE_INTERP(GridSamplerInterpolation::Bilinear, true, true); + HANDLE_INTERP(GridSamplerInterpolation::Nearest, true, true); + HANDLE_INTERP(GridSamplerInterpolation::Bicubic, true, true); + } + } else { + switch (static_cast(interpolation_mode)) { + HANDLE_INTERP(GridSamplerInterpolation::Bilinear, false, true); + HANDLE_INTERP(GridSamplerInterpolation::Nearest, false, true); + HANDLE_INTERP(GridSamplerInterpolation::Bicubic, false, true); + } + } + } else { + if (align_corners) { + switch (static_cast(interpolation_mode)) { + HANDLE_INTERP(GridSamplerInterpolation::Bilinear, true, false); + HANDLE_INTERP(GridSamplerInterpolation::Nearest, true, false); + HANDLE_INTERP(GridSamplerInterpolation::Bicubic, true, false); + } + } else { + switch (static_cast(interpolation_mode)) { + HANDLE_INTERP(GridSamplerInterpolation::Bilinear, false, false); + HANDLE_INTERP(GridSamplerInterpolation::Nearest, false, false); + HANDLE_INTERP(GridSamplerInterpolation::Bicubic, false, false); + } + } + + } + }); +#undef HANDLE_CASE +#undef HANDLE_INTERP +} + +} + +REGISTER_DISPATCH(grid_sampler_2d_cpu_kernel, &grid_sampler_2d_cpu_kernel_impl) +REGISTER_DISPATCH(grid_sampler_2d_backward_cpu_kernel, &grid_sampler_2d_backward_cpu_kernel_impl) + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/GridSamplerKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/GridSamplerKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f0c8439f6f80e025c98d4a698464d5bd6244916e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/GridSamplerKernel.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +#include +#include + +namespace at { +class TensorBase; +} + +namespace at::native { + +using forward_2d_fn = void (*) ( + const TensorBase &output, + const TensorBase &input, + const TensorBase &grid, + int64_t interpolation_mode, + int64_t padding_mode, + bool align_corners); +using backward_2d_fn = void (*) ( + const TensorBase &grad_input, + const TensorBase &grad_grid, + const TensorBase &grad_output, + const TensorBase &input, + const TensorBase &grid, + int64_t interpolation_mode, + int64_t padding_mode, + bool align_corners, + std::array output_mask); +DECLARE_DISPATCH(forward_2d_fn, grid_sampler_2d_cpu_kernel) +DECLARE_DISPATCH(backward_2d_fn, grid_sampler_2d_backward_cpu_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/HistogramKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/HistogramKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..135c120124e4a69a55d4ed7e3f526db70c551188 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/HistogramKernel.cpp @@ -0,0 +1,314 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +#include +#include +#include + +namespace at::native { + +namespace { + +constexpr int64_t HISTOGRAM_GRAIN_SIZE = 200; + +/* The main algorithm. Expects that the input tensor has shape (N, D). + * Expects that bin_edges contains D one-dimensional tensors, each specifying + * an increasing sequences of bin edges. + * + * Interprets the input as N different D-dimensional coordinates and maps them + * into the D-dimensional bins defined by bin_edges, accumulating a D-dimensional + * histogram in the hist tensor. + * + * Accepts a template argument of type BIN_SELECTION_ALGORITHM specifying how + * the scalars in each dimension should be mapped into the dimension's bins: + * + * - LINEAR_INTERPOLATION: each bin edge sequence must form a linear progression. + * Scalars are mapped to bins by computing + * (element - leftmost_edge)/(rightmost_edge - leftmost_edge) * bin_ct + * and truncating the result to an integer. + * + * This is the fastest option, but its results may not be perfectly consistent + * with the boundaries specified in bin_edges due to precision issues. + * + * Used by torch.histc, which doesn't need consistency with bin_edges as it does not + * return bin_edges. Additionally, this implementation is identical to the legacy histc + * implementation, which was replaced when histogram was implemented. + * + * - LINEAR_INTERPOLATION_WITH_LOCAL_SEARCH: Also expects that each bin edge sequence + * forms a linear progression. For each scalar, if 'pos' is the bin selected by the + * LINEAR_INTERPOLATION approach, this approach inspects the boundaries in bin_edges to + * place the scalar into pos - 1, pos, or pos + 1. The "local search" over neighboring + * bins allows for correction of misclassifications due to precision issues (a scalar + * very close to a bin_edge may be misclassified by LINEAR_INTERPOLATION). + * + * Should produce the same output as the general case BINARY_SEARCH, but run about + * 3x faster asymptotically. + * + * Used by torch.histogram for cases in which bin_edges is constructed using + * torch.linspace. The behavior of LINEAR_INTERPOLATION may not perfectly align + * with linspace bin_edges due to precision issues. torch.histogram returns both + * the hist and bin_edges tensors as output, so the "local search" is needed to + * keep its output internally consistent. + * + * - BINARY_SEARCH: Handles torch.histogram's general case by by searching over the + * elements of bin_edges. Implemented using std::upper_bound. + * + * See discussion at https://github.com/pytorch/pytorch/pull/58780#discussion_r648604866 + * for further details on relative performance of the bin selection algorithms. + */ +enum BIN_SELECTION_ALGORITHM { + LINEAR_INTERPOLATION, + LINEAR_INTERPOLATION_WITH_LOCAL_SEARCH, + BINARY_SEARCH, +}; +template +void histogramdd_cpu_contiguous(Tensor& hist, const TensorList& bin_edges, + const Tensor& input, const std::optional& weight) { + TORCH_INTERNAL_ASSERT(input.dim() == 2); + + const int64_t N = input.size(0); + if (weight.has_value()) { + TORCH_INTERNAL_ASSERT(weight.value().dim() == 1 && weight.value().numel() == N); + } + + const int64_t D = input.size(1); + TORCH_INTERNAL_ASSERT(int64_t(bin_edges.size()) == D); + for (const auto dim : c10::irange(D)) { + TORCH_INTERNAL_ASSERT(bin_edges[dim].is_contiguous()); + TORCH_INTERNAL_ASSERT(hist.size(dim) + 1 == bin_edges[dim].numel()); + } + + if (D == 0) { + // hist is an empty tensor in this case; nothing to do here + return; + } + + TensorAccessor accessor_in = input.accessor(); + + /* Constructs a std::optional containing an accessor if + * the optional weight tensor has a value. + */ + const auto accessor_wt = weight.has_value() + ? std::optional>(weight.value().accessor()) + : std::optional>(); + + std::vector bin_seq(D); + std::vector num_bin_edges(D); + std::vector leftmost_edge(D), rightmost_edge(D); + + for (const auto dim : c10::irange(D)) { + bin_seq[dim] = bin_edges[dim].const_data_ptr(); + num_bin_edges[dim] = bin_edges[dim].numel(); + leftmost_edge[dim] = bin_seq[dim][0]; + rightmost_edge[dim] = bin_seq[dim][num_bin_edges[dim] - 1]; + } + + int64_t GRAIN_SIZE = std::max(int64_t(1), HISTOGRAM_GRAIN_SIZE / D); + + /* Parallelizes processing of input using at::parallel_for. + * Each thread accumulates a local result into their own slice of + * thread_histograms which get summed together at the end. + */ + const auto num_threads = at::get_num_threads(); + const auto hist_sizes = hist.sizes(); + DimVector thread_hist_sizes(hist_sizes.size() + 1); + thread_hist_sizes[0] = num_threads; + std::copy(hist_sizes.begin(), hist_sizes.end(), + thread_hist_sizes.begin() + 1); + Tensor thread_histograms = at::zeros(thread_hist_sizes, hist.dtype()); + TORCH_INTERNAL_ASSERT(thread_histograms.is_contiguous()); + + at::parallel_for(0, N, GRAIN_SIZE, [&](int64_t start, int64_t end) { + const auto tid = at::get_thread_num(); + auto hist_strides = thread_histograms.strides(); + input_t *hist_local_data = thread_histograms.data_ptr(); + + // View only this thread's local results + hist_local_data += hist_strides[0] * tid; + hist_strides = hist_strides.slice(1); + + for (const auto i : c10::irange(start, end)) { + bool skip_elt = false; + int64_t hist_index = 0; + + for (const auto dim : c10::irange(D)) { + const input_t elt = accessor_in[i][dim]; + + // Skips elements which fall outside the specified bins and NaN elements + if (!(elt >= leftmost_edge[dim] && elt <= rightmost_edge[dim])) { + skip_elt = true; + break; + } + + int64_t pos = -1; + + if (algorithm == BINARY_SEARCH) { + // Handles the general case via binary search on the bin edges. + pos = std::upper_bound(bin_seq[dim], bin_seq[dim] + num_bin_edges[dim], elt) + - bin_seq[dim] - 1; + } else if (algorithm == LINEAR_INTERPOLATION + || algorithm == LINEAR_INTERPOLATION_WITH_LOCAL_SEARCH) { + /* When bin_edges is known to be a linear progression, maps elt to + * the appropriate bin via simple division. + */ + pos = static_cast((elt - leftmost_edge[dim]) + * (num_bin_edges[dim] - 1) + / (rightmost_edge[dim] - leftmost_edge[dim])); + + /* Ensures consistency with bin_edges by checking the bins to the left and right + * of the selected position. Necessary for cases in which an element very close + * to a bin edge may be misclassified by simple division. + */ + if (algorithm == LINEAR_INTERPOLATION_WITH_LOCAL_SEARCH) { + int64_t pos_min = std::max(static_cast(0), pos - 1); + int64_t pos_max = std::min(pos + 2, num_bin_edges[dim]); + pos = std::upper_bound(bin_seq[dim] + pos_min, bin_seq[dim] + pos_max, elt) + - bin_seq[dim] - 1; + } + } else { + TORCH_INTERNAL_ASSERT(false); + } + + // Unlike other bins, the rightmost bin includes its right boundary + if (pos == (num_bin_edges[dim] - 1)) { + pos -= 1; + } + + hist_index += hist_strides[dim] * pos; + } + + if (!skip_elt) { + // In the unweighted case, the default weight is 1 + input_t wt = accessor_wt.has_value() ? accessor_wt.value()[i] : static_cast(1); + + hist_local_data[hist_index] += wt; + } + } + }); + + at::sum_out(hist, thread_histograms, /*dim=*/{0}); +} + +/* Some pre- and post- processing steps for the main algorithm. + * Initializes hist to 0, calls into the main algorithm, and normalizes output if necessary. + */ +template +void histogramdd_out_cpu_template(const Tensor& self, const std::optional& weight, bool density, + Tensor& hist, const TensorList& bin_edges) { + hist.fill_(0); + + const int64_t N = self.size(-1); + const int64_t M = std::accumulate(self.sizes().begin(), self.sizes().end() - 1, + (int64_t)1, std::multiplies()); + + const Tensor reshaped_input = self.reshape({M, N}); + + const auto reshaped_weight = weight.has_value() + ? std::optional(weight.value().reshape({M})) + : std::optional(); + + std::vector bin_edges_contig(bin_edges.size()); + for (const auto dim : c10::irange(bin_edges_contig.size())) { + bin_edges_contig[dim] = bin_edges[dim].contiguous(); + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, self.scalar_type(), "histogram_cpu", [&]() { + histogramdd_cpu_contiguous( + hist, bin_edges_contig, reshaped_input, reshaped_weight); + }); + + /* Divides each bin's value by the total count/weight in all bins, + * and by the bin's volume. + */ + if (density) { + const auto hist_sum = hist.sum().item(); + hist.div_(hist_sum); + + /* For each dimension, divides each bin's value + * by the bin's length in that dimension. + */ + for (const auto dim : c10::irange(N)) { + const auto bin_lengths = bin_edges[dim].diff(); + + // Used to reshape bin_lengths to align with the corresponding dimension of hist. + std::vector shape(N, 1); + shape[dim] = bin_lengths.numel(); + + hist.div_(bin_lengths.reshape(shape)); + } + } +} + +/* The general implementation of the histogram kernel. Maps each element of the input tensor + * to its corresponding bin by performing a binary search over the elements of bin_edges. + * + * Refer to histogramdd_out_cpu_template for more details. + */ +void histogramdd_kernel_impl(const Tensor& self, const std::optional& weight, bool density, + Tensor& hist, const TensorList& bin_edges) { + histogramdd_out_cpu_template(self, weight, density, hist, bin_edges); +} + +/* A faster version of the histogram kernel for cases in which bin_edges are known + * to form a linear progression. + * + * Refer to histogramdd_out_cpu_template for more details. + */ +void histogramdd_linear_kernel_impl(const Tensor& self, const std::optional& weight, + bool density, Tensor& hist, const TensorList& bin_edges, bool local_search) { + if (local_search) { + // histogramdd codepath: both hist and bin_edges are eventually returned as output, + // so we'll keep them consistent + histogramdd_out_cpu_template( + self, weight, density, hist, bin_edges); + } else { + // histc codepath: bin_edges are not returned to the caller + histogramdd_out_cpu_template( + self, weight, density, hist, bin_edges); + } +} + +template +void infer_bin_edges_from_input(const Tensor& input, const int64_t N, + std::vector &leftmost_edges, std::vector &rightmost_edges) { + // Calls aminmax on input with dim=0, reducing all but the innermost dimension of input. + auto [min, max] = aminmax(input, 0); + + TORCH_INTERNAL_ASSERT(min.is_contiguous() && max.is_contiguous()); + + const scalar_t *min_data = min.const_data_ptr(); + std::copy(min_data, min_data + N, leftmost_edges.begin()); + + const scalar_t *max_data = max.const_data_ptr(); + std::copy(max_data, max_data + N, rightmost_edges.begin()); +} + +void histogram_select_outer_bin_edges_impl(const Tensor& input, const int64_t N, + std::vector &leftmost_edges, std::vector &rightmost_edges) { + AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "histogramdd", [&]() { + infer_bin_edges_from_input(input, N, leftmost_edges, rightmost_edges); + }); +} + +} // namespace + +REGISTER_DISPATCH(histogramdd_stub, &histogramdd_kernel_impl) +REGISTER_DISPATCH(histogramdd_linear_stub, &histogramdd_linear_kernel_impl) +REGISTER_DISPATCH(histogram_select_outer_bin_edges_stub, &histogram_select_outer_bin_edges_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IndexKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IndexKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c12b12f56d0d0bcd7a1fe899a7eb824a97a0aa08 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IndexKernel.cpp @@ -0,0 +1,830 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +using namespace vec; + +void index_kernel(TensorIteratorBase& iter, IntArrayRef index_size, IntArrayRef index_stride) { + AT_DISPATCH_V2( + iter.dtype(), + "index_cpu", + AT_WRAP([&] { + cpu_index_kernel(iter, index_size, index_stride, [](char* dst, char* src, int64_t offset) { + *(scalar_t*)dst = c10::load((scalar_t*)(src + offset)); + }); + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + AT_EXPAND(AT_FLOAT8_TYPES), + AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), + kComplexHalf, + kBComplex32, + kHalf, + kBool, + kBFloat16); +} + +// Given a linear index, returns the offset of the tensor. +// Implements the same algorithm as its (legacy) GPU version cuda::detail::IndexToOffset +// OffsetCalculator implements yet again the same algorithm but in a column-major order +struct IndexToOffset { + const IntArrayRef sizes; + const IntArrayRef strides; + const int64_t ndim; + explicit IndexToOffset(const TensorBase & tensor) : + sizes(tensor.sizes()), strides(tensor.strides()), ndim(tensor.dim()) { + } + + int64_t get(int64_t linear_index) const { + int64_t offset = 0; + for (int64_t i = ndim - 1; i > 0; i--) { + offset += (linear_index % sizes[i]) * strides[i]; + linear_index /= sizes[i]; + } + return offset + linear_index * strides[0]; + } +}; + +template +void cpu_take_put_kernel( + TensorIterator& iter, + const TensorBase& indexed, + bool is_indexed_data_mutated, + const func_t& f, + bool serial_execution=false) { + // This kernel follows the same strategy as `cpu_index_kernel` + // Even though the indexed_tensor is const, we modify it through the data_ptr + // This is a bit dirty, but otherwise it would be necessary to unnecessarily add tensor + // with zero strides to `iter` which would not be much better + + // When launch the parallel version, set a relative small grain size less than the INTERNAL::GRAIN_SIZE + // to make the whole available thread numbers get more balanced work load and a better cache location. + // The grain size here is chosen by the op benchmark to overcome the thread launch overhead + // Perhaps tweak this number for `put_`? This number was tweaked for `index_put` + constexpr int parallel_grain_size = 3000; + const bool is_contiguous = indexed.is_contiguous(); + const auto numel = indexed.numel(); + const auto offset_indexed = IndexToOffset(indexed); + + auto* indexed_data = is_indexed_data_mutated ? + indexed.data_ptr() + : const_cast(indexed.const_data_ptr()); + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* iterated_data_bytes = data[0]; + auto* index_data_bytes = data[1]; + for ([[maybe_unused]] const auto elem : c10::irange(n)) { + auto idx = *reinterpret_cast(index_data_bytes); + auto& iterated = *reinterpret_cast(iterated_data_bytes); + + TORCH_CHECK_INDEX(idx >= -numel && idx < numel, + "out of range: tried to access index ", + idx, " on a tensor of ", numel, " elements."); + if (idx < 0) { + idx += numel; + } + if (!is_contiguous) { + idx = offset_indexed.get(idx); + } + f(iterated, indexed_data, idx); + iterated_data_bytes += strides[0]; + index_data_bytes += strides[1]; + } + }; + if (serial_execution) { + iter.serial_for_each(loop, {0, iter.numel()}); + } else { + iter.for_each(loop, parallel_grain_size); + } +} + +void put_kernel( + TensorIterator& iter, + const TensorBase & self, + const bool accumulate) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16, + iter.dtype(), "take_put_cpu", [&] { + // iter could be const, but for_each does not have a const version + if (accumulate) { + // nb. This deterministic issue the same as that of `index_put_kernel` + // See Note [Enabling Deterministic Operations] + // Parallel cpu_put_kernel with accumulation is nondeterministic, so we + // must enable serial execution if deterministic algorithms are enabled. + bool is_deterministic = at::globalContext().deterministicAlgorithms(); + bool use_parallel_for = (!is_deterministic) && ( + (iter.numel() >= internal::GRAIN_SIZE) && (at::get_num_threads() > 1)); + if (use_parallel_for && iter.dtype() == ScalarType::Float) { + cpu_take_put_kernel(iter, self, true, + [](float& iterated, float* indexed, const int64_t idx) { + cpu_atomic_add_float(indexed+idx, iterated); + }); + } else { + // TODO: investigate parallelization of the accumulate kernel. + // Unlike the non-accumulate case, this needs to be thread-safe. + cpu_take_put_kernel(iter, self, true, + [](scalar_t& iterated, scalar_t* indexed, const int64_t idx) { + indexed[idx] += c10::load(&iterated); + }, + /*serial_execution=*/true); + } + } else { + cpu_take_put_kernel(iter, self, true, + [](scalar_t& iterated, scalar_t* indexed, const int64_t idx) { + indexed[idx] = c10::load(&iterated); + }); + } + }); +} + +void take_kernel( + TensorIterator& iter, + const TensorBase & input) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16, + iter.dtype(), "take_cpu", [&] { + cpu_take_put_kernel(iter, input, false, + [](scalar_t& iterated, const scalar_t* indexed, const int64_t idx) { + iterated = c10::load(&(indexed[idx])); + }); + }); +} + +void index_put_kernel(TensorIterator& iter, IntArrayRef index_size, IntArrayRef index_stride, bool accumulate) { + // NOTE: duplicate indices are only supported if accumulate is true. + AT_DISPATCH_V2( + iter.dtype(), + "index_put", + AT_WRAP([&] { + // See Note [Enabling Deterministic Operations] + // Parallel cpu_index_kernel with accumulation is nondeterministic, so we + // must enable serial execution if deterministic algorithms are enabled. + const bool is_deterministic = at::globalContext().deterministicAlgorithms(); + if (accumulate) { + bool use_parallel_for = (!is_deterministic) && ( + (iter.numel() >= internal::GRAIN_SIZE) && (at::get_num_threads() > 1)); + if (use_parallel_for && iter.dtype() == ScalarType::Float) { + cpu_index_kernel(iter, index_size, index_stride, [](char* dst, char* src, int64_t offset) { + cpu_atomic_add_float((float*)(dst + offset), *(float*)src); + }); + } else { + // TODO: investigate parallelization of the accumulate kernel. Unlike the non-accumulate case, + // this needs to be thread-safe. + cpu_index_kernel(iter, index_size, index_stride, [](char* dst, char* src, int64_t offset) { + *(scalar_t*)(dst + offset) += c10::load(reinterpret_cast(src)); + }, /*serial_execution=*/true); + } + } else { + cpu_index_kernel(iter, index_size, index_stride, [](char* dst, char* src, int64_t offset) { + *(scalar_t*)(dst + offset) = c10::load(reinterpret_cast(src)); + }, /*serial_execution=*/is_deterministic); + } + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + // AT_EXPAND(AT_FLOAT8_TYPES), + // TODO(#113663): clean up accumulation behavior in float8 dtypes, accumulate=True + // should not be supported here, then reenable AT_FLOAT8_DTYPES + kFloat8_e4m3fn, + kFloat8_e5m2, + kFloat8_e4m3fnuz, + kFloat8_e5m2fnuz, + kComplexHalf, + kBComplex32, + kHalf, + kBool, + kBFloat16); +} + +void index_fill_kernel( + TensorIterator& iter, + int64_t dim, + int64_t self_dim_size, + int64_t self_dim_stride, + const Scalar& source) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16, kComplexHalf, kBComplex32, + iter.dtype(), "index_fill_cpu", [&] { + auto fill_val = source.to(); + auto handle_nonzero_idx_stride = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[0]; + auto* index_data_bytes = data[1]; + for ([[maybe_unused]] const auto elem : c10::irange(n)) { + auto* self_data = reinterpret_cast(self_data_bytes); + auto idx = *reinterpret_cast(index_data_bytes); + TORCH_CHECK_INDEX(idx >= -self_dim_size && idx < self_dim_size, + "index ", idx, " is out of bounds for dimension ", + dim, " with size ", self_dim_size); + if (idx < 0) { + idx += self_dim_size; + } + + self_data[idx * self_dim_stride] = fill_val; + + self_data_bytes += strides[0]; + index_data_bytes += strides[1]; + } + }; + auto handle_zero_idx_stride = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[0]; + auto* index_data_bytes = data[1]; + auto idx = *reinterpret_cast(index_data_bytes); + TORCH_CHECK_INDEX(idx >= -self_dim_size && idx < self_dim_size, + "index ", idx, " is out of bounds for dimension ", + dim, " with size ", self_dim_size); + if (idx < 0) { + idx += self_dim_size; + } + for ([[maybe_unused]] const auto elem : c10::irange(n)) { + auto* self_data = reinterpret_cast(self_data_bytes); + + self_data[idx * self_dim_stride] = fill_val; + + self_data_bytes += strides[0]; + } + }; + + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto idx_stride = strides[1]; + if (idx_stride) { + handle_nonzero_idx_stride(data, strides, n); + } + else { + handle_zero_idx_stride(data, strides, n); + } + }; + iter.for_each(loop); + }); +} + +void index_copy_kernel( + TensorIterator& iter, + int64_t dim, + int64_t self_dim_size, + int64_t self_dim_stride) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5(ScalarType::Half, ScalarType::Bool, ScalarType::BFloat16, kComplexHalf, kBComplex32, + iter.dtype(), "index_copy_cpu", [&] { + auto handle_nonzero_idx_stride = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[0]; + auto* index_data_bytes = data[1]; + auto* source_data_bytes = data[2]; + for ([[maybe_unused]] const auto elem : c10::irange(n)) { + auto* self_data = reinterpret_cast(self_data_bytes); + auto idx = *reinterpret_cast(index_data_bytes); + auto* source_data = reinterpret_cast(source_data_bytes); + TORCH_CHECK_INDEX(idx >= 0 && idx < self_dim_size, + "index_copy_(): index ", idx, " is out of bounds for dimension ", + dim, " with size ", self_dim_size); + + self_data[idx * self_dim_stride] = c10::load(source_data); + + self_data_bytes += strides[0]; + index_data_bytes += strides[1]; + source_data_bytes += strides[2]; + } + }; + auto handle_zero_idx_stride = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[0]; + auto* index_data_bytes = data[1]; + auto* source_data_bytes = data[2]; + auto idx = *reinterpret_cast(index_data_bytes); + TORCH_CHECK_INDEX(idx >= 0 && idx < self_dim_size, + "index_copy_(): index ", idx, " is out of bounds for dimension ", + dim, " with size ", self_dim_size); + for ([[maybe_unused]] const auto elem : c10::irange(n)) { + auto* self_data = reinterpret_cast(self_data_bytes); + auto* source_data = reinterpret_cast(source_data_bytes); + + self_data[idx * self_dim_stride] = c10::load(source_data); + + self_data_bytes += strides[0]; + source_data_bytes += strides[2]; + } + }; + + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto idx_stride = strides[1]; + if (idx_stride) { + handle_nonzero_idx_stride(data, strides, n); + } + else { + handle_zero_idx_stride(data, strides, n); + } + }; + bool is_deterministic = at::globalContext().deterministicAlgorithms(); + if (is_deterministic) { + iter.serial_for_each(loop, {0, iter.numel()}); + } else { + iter.for_each(loop); + } + }); +} + +template +void cpu_masked_fill_kernel(TensorIterator& iter, scalar_t value) { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + char* dst = data[0]; + char* mask = data[1]; + for (const auto i : c10::irange(n)) { + bool mask_value = c10::load(reinterpret_cast(mask + strides[1] * i)); + + if (mask_value) { + *(scalar_t*)(dst + strides[0] * i) = value; + } + } + }; + iter.for_each(loop); +} + +void masked_fill_kernel(TensorIterator& iter, const Scalar& value) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND5(kComplexHalf, kBComplex32, kBool, kBFloat16, kHalf, + iter.dtype(), "masked_fill", [&] { + scalar_t scalar_val = value.to(); + auto mask_dtype = iter.input_dtype(0); + TORCH_CHECK(mask_dtype == ScalarType::Bool, "masked_fill only supports boolean masks, " + "but got mask with dtype ", mask_dtype); + cpu_masked_fill_kernel(iter, scalar_val); + }); +} + +template +void cpu_masked_scatter_kernel(TensorIterator& iter, const TensorBase& source) { + std::ptrdiff_t source_cntr = 0; + const scalar_t* source_ptr = source.const_data_ptr(); + auto numel = source.numel(); + + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + char* dst = data[0]; + const int64_t dst_stride = strides[0]; + char* mask = data[1]; + const int64_t mask_stride = strides[1]; + for (const auto i : c10::irange(n)) { + auto mask_value = c10::load(reinterpret_cast(mask + mask_stride * i)); + + if (mask_value) { + TORCH_CHECK(source_cntr < numel, "Number of elements of source < number of ones in mask"); + *(scalar_t*)(dst + dst_stride * i) = c10::load(source_ptr); + source_ptr++; + source_cntr++; + } + } + }; + iter.serial_for_each(loop, {0, iter.numel()}); +} + +void masked_scatter_kernel(TensorIterator& iter, const TensorBase& source) { + TORCH_CHECK(iter.input_dtype() == ScalarType::Bool, "masked_scatter_ only supports boolean masks, " + "but got mask with dtype ", iter.input_dtype()); + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + ScalarType::Bool, + ScalarType::BFloat16, + ScalarType::Half, + iter.dtype(), + "masked_scatter", + [&] { + cpu_masked_scatter_kernel(iter, source); + }); +} + +template +void cpu_masked_select_serial_kernel(TensorIterator& iter, const func_t& f) { + int64_t offset = 0; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + char* dst = data[0]; + char* src = data[1]; + char* mask = data[2]; + for (const auto i : c10::irange(n)) { + mask_t mask_value = c10::load((mask_t*)(mask + strides[2] * i)); + if constexpr (!std::is_same_v) { + TORCH_CHECK(mask_value == 0 || mask_value == 1, "Mask tensor can take 0 and 1 values only"); + } + if (mask_value) { + int64_t offset_bytes = offset * sizeof(scalar_t); + f(dst, src + strides[1] * i, offset_bytes); + offset++; + } + } + }; + iter.serial_for_each(loop, {0, iter.numel()}); +} + +void masked_select_serial_kernel(TensorIterator& iter, int64_t result_stride) { + AT_DISPATCH_V2(iter.dtype(), "masked_select", AT_WRAP([&] { + auto mask_dtype = iter.input_dtype(1); + if (mask_dtype == ScalarType::Bool) { + cpu_masked_select_serial_kernel(iter, [result_stride](char* dst, char* src, int64_t offset) { + *(scalar_t*)(dst + offset*result_stride) = c10::load((scalar_t*)src); + }); + } else { + cpu_masked_select_serial_kernel(iter, [result_stride](char* dst, char* src, int64_t offset) { + *(scalar_t*)(dst + offset*result_stride) = c10::load((scalar_t*)src); + }); + } + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + AT_EXPAND(AT_FLOAT8_TYPES), + kComplexHalf, + kBComplex32, + kHalf, + kBool, + kBFloat16); +} + +template +void cpu_masked_select_kernel(TensorIterator& iter, const func_t& f) { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + char* dst = data[0]; + char* src = data[1]; + char* mask = data[2]; + char* mask_prefix_sum = data[3]; + for (const auto i : c10::irange(n)) { + mask_t mask_value = c10::load((mask_t*)(mask + strides[2] * i)); + if constexpr (!std::is_same_v) { + TORCH_CHECK(mask_value == 0 || mask_value == 1, "Mask tensor can take 0 and 1 values only"); + } + if (mask_value) { + int64_t offset = *(int64_t*)(mask_prefix_sum + strides[3] * i); + int64_t offset_bytes = (offset - 1) * sizeof(scalar_t); + f(dst, src + strides[1] * i, offset_bytes); + } + } + }; + iter.for_each(loop); +} + +void masked_select_kernel(TensorIterator& iter, int64_t result_stride) { + AT_DISPATCH_V2(iter.dtype(), "masked_select", AT_WRAP([&] { + auto mask_dtype = iter.input_dtype(1); + if (mask_dtype == ScalarType::Bool) { + cpu_masked_select_kernel(iter, [result_stride](char* dst, char* src, int64_t offset) { + *(scalar_t*)(dst + offset*result_stride) = c10::load((scalar_t*)src); + }); + } else { + cpu_masked_select_kernel(iter, [result_stride](char* dst, char* src, int64_t offset) { + *(scalar_t*)(dst + offset*result_stride) = *(scalar_t*)src; + }); + } + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + AT_EXPAND(AT_FLOAT8_TYPES), + kComplexHalf, + kBComplex32, + kHalf, + kBool, + kBFloat16); +} + +template +void cpu_hflip_vec(at::TensorIterator& iter) { + + auto loop2d = [&](char** base, const int64_t *strides, int64_t size0, int64_t size1) { + + // Here ntensors is defined for output and 1 input. But tensor iterator has defined output, input + // and restrided_input (see aten/src/ATen/native/TensorTransformations.cpp#L64-L66) but we use only + // output and input. + static constexpr int ntensors = 2; + const int64_t *outer_strides = &strides[3]; + + std::array data_arr; + std::copy_n(base, ntensors, data_arr.data()); + + using Vec = Vectorized; + + constexpr auto stride = sizeof(scalar_t); + TORCH_INTERNAL_ASSERT(stride == -strides[0] && stride == strides[1]); + + for ([[maybe_unused]] const auto j : c10::irange(size1)) { + // vectorized loop with negative stride for output + int64_t n = size0; + int64_t i = 0; + + // data_arr[0] unaligned pre-pass + int64_t offset = (j * n + (n - i - Vec::size())) % 32; + offset = (offset >= n) ? n : offset; + for (; i < offset; i++) { + scalar_t* out_ptr = (scalar_t*)(data_arr[0] - i * stride); + *out_ptr = c10::load((scalar_t *)(data_arr[1] + i * stride)); + } + // Empirically found that it is faster to process 3 data items together vs 2 or 4 + for (; i <= n - 3 * Vec::size(); i += 3 * Vec::size()) { + auto out1 = Vec::loadu(data_arr[1] + i * stride); + auto out2 = Vec::loadu(data_arr[1] + (i + Vec::size()) * stride); + auto out3 = Vec::loadu(data_arr[1] + (i + 2 * Vec::size()) * stride); + // flip the vector: 1234 -> 4321 + out1 = flip(out1); + out2 = flip(out2); + out3 = flip(out3); + out1.store(data_arr[0] - (i + Vec::size() - 1) * stride); + out2.store(data_arr[0] - (i + 2 * Vec::size() - 1) * stride); + out3.store(data_arr[0] - (i + 3 * Vec::size() - 1) * stride); + } + if (i < n) { + for (; i < n; i++) { + scalar_t* out_ptr = (scalar_t*)(data_arr[0] - i * stride); + *out_ptr = c10::load((scalar_t *)(data_arr[1] + i * stride)); + } + } + + // advance: + for (const auto arg : c10::irange(ntensors)) { + data_arr[arg] += outer_strides[arg]; + } + } + }; + + int64_t grain_size = at::internal::GRAIN_SIZE; + iter.for_each(loop2d, grain_size); + iter.cast_outputs(); +} + +void cpu_vflip_memcpy(at::TensorIterator& iter) { + // This is a vertical flip specialization using memcpy to speed-up the runtime + + auto loop2d = [&](char** base, const int64_t *strides, int64_t size0, int64_t size1) { + + // Here ntensors is defined for output and 1 input. But tensor iterator has defined output, input + // and restrided_input (see aten/src/ATen/native/TensorTransformations.cpp#L64-L66) but we use only + // output and input. + static constexpr int ntensors = 2; + const int64_t *outer_strides = &strides[3]; + + std::array data_arr; + std::copy_n(base, ntensors, data_arr.data()); + + TORCH_INTERNAL_ASSERT(strides[0] == strides[1]); + const int64_t stride = strides[0]; + + for ([[maybe_unused]] const auto j : c10::irange(size1)) { + int64_t n = size0; + memcpy(data_arr[0], data_arr[1], n * stride); + + // advance: + for (const auto arg : c10::irange(data_arr.size())) { + data_arr[arg] += outer_strides[arg]; + } + } + }; + + int64_t grain_size = at::internal::GRAIN_SIZE; + iter.for_each(loop2d, grain_size); + iter.cast_outputs(); +} + +constexpr int64_t hflip_mask_size = 32; + +std::array generate_vec_hflip_reg_mask(int64_t data_stride) { + std::array mask; + for (const auto k : c10::irange(hflip_mask_size / 2)) { + int j = k / data_stride + 1; + int v = (j * data_stride - 1) - (k % data_stride); + v = std::min(v, (int) (hflip_mask_size / 2 - 1)); + mask[hflip_mask_size - 1 - k] = v; + mask[hflip_mask_size / 2 - 1 - k] = v; + } + return mask; +} + +int64_t vectorized_cpu_hflip_channels_last( + char * C10_RESTRICT *data, const int64_t data_size, const int64_t data_stride, const std::array & mdata) { + + int64_t i = 0; +#ifdef CPU_CAPABILITY_AVX2 + + constexpr auto vec_size = 256 / 8; + + if (data_size > vec_size) { + + // Example for num channels=3 and dtype=uint8 + // -> data_stride = 3 + // -> usable_vec_stride = 30 + // -> usable_vec_half_stride = 15 + // Data: (1 2 3) (4 5 6) (7 8 9) (10 11 12) (13 14 15) (16 17 18) (19 20 21) (22 23 24) (25 26 27) (28 29 30) (31 32 33) + // load by 2 parts + // R = [ (1 2 3) (4 5 6) (7 8 9) (10 11 12) (13 14 15) (16 | (16 17 18) (19 20 21) (22 23 24) (25 26 27) (28 29 30) (31 ] + // flip(R) -> + // R = [ 31 (28 29 30) (25 26 27) (22 23 24) (19 20 21) (16 17 18) | 16 (13 14 15) (10 11 12) (7 8 9) (4 5 6) (1 2 3) ] + // + // Write in 2 parts + // Output pointer: output_ptr = data[0] v + // - Init: + // (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) + // 0) Move to initial position: output_ptr = data[0] + data_stride - vec_size / 2; + // v + // (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) (X X X) + // - In the loop: + // 1) Write 1st block from output_ptr + // v + // |----> vec_size / 2 ---------------------------| + // Output part 1: (X X X) (X X X) (X X X) (X X X) (X X X) (X X 16) (13 14 15) (10 11 12) (7 8 9) (4 5 6) (1 2 3) + // 2) Write 2nd block from output_ptr - usable_vec_half_stride: + // v + // |-----> vec_size / 2 ----------------------------------| + // Output part 2: (X X 31) (28 29 30) (25 26 27) (22 23 24) (19 20 21) (16 17 18) (13 14 15) (10 11 12) (7 8 9) (4 5 6) (1 2 3) + // + // 3) Move to the next position: output_ptr -= usable_vec_stride + // + // - After the loop: + // 4) Move to write position + // v + // (X X 31) (28 29 30) (25 26 27) (22 23 24) (19 20 21) (16 17 18) (13 14 15) (10 11 12) (7 8 9) (4 5 6) (1 2 3) + + const __m256i mask = _mm256_loadu_si256((__m256i *) mdata.data()); + + const auto usable_vec_stride = 2 * (vec_size / 2 / data_stride) * data_stride; + const auto usable_vec_half_stride = usable_vec_stride / 2; + + auto output_ptr = data[0] + data_stride - vec_size / 2; + auto input_ptr = data[1]; + + for (; i < data_size - vec_size; i += usable_vec_stride) { + + // load 256-bits by two 128-bits parts + auto a0 = _mm_loadu_si128((__m128i *) (input_ptr + i)); + auto b0 = _mm256_castsi128_si256(a0); + auto a1 = _mm_loadu_si128((__m128i *) (input_ptr + i + usable_vec_half_stride)); + auto data_vec = _mm256_inserti128_si256(b0, a1, 1); + + auto reversed_vec = _mm256_shuffle_epi8(data_vec, mask); + + // write output in two parts + auto rev_vec_h = _mm256_extracti128_si256(reversed_vec, 0); + _mm_storeu_si128((__m128i *) (output_ptr - i), rev_vec_h); + auto rev_vec_l = _mm256_extracti128_si256(reversed_vec, 1); + _mm_storeu_si128((__m128i *) (output_ptr - i - usable_vec_half_stride), rev_vec_l); + } + + data[0] -= i; + data[1] += i; + } +#endif + return i; +} + +void cpu_hflip_channels_last_vec(at::TensorIterator& iter) { + + auto input_strides = iter.strides(1); + const auto data_stride = input_strides[1]; + + // Generate avx mask once + alignas(hflip_mask_size) auto mdata = generate_vec_hflip_reg_mask(data_stride); + + auto loop2d = [&](char** base, const int64_t *strides, int64_t size0, int64_t size1) { + + // Here ntensors is defined for output and 1 input. But tensor iterator has defined output, input + // and restrided_input (see aten/src/ATen/native/TensorTransformations.cpp#L64-L66) but we use only + // output and input. + static constexpr int ntensors = 2; + const int64_t *outer_strides = &strides[3]; + const int64_t stride = strides[0]; + + TORCH_INTERNAL_ASSERT(stride == strides[1]); + + auto c = -outer_strides[0]; + TORCH_INTERNAL_ASSERT(c == outer_strides[1]); + + char* C10_RESTRICT data[ntensors] = {base[0], base[1]}; + const int64_t size = size0 * size1; + + int64_t i = 0; + + if (c >= 2 && c <= 16) { + i = vectorized_cpu_hflip_channels_last(data, size * stride, c, mdata) / stride; + } + + auto data_stride = size0 * stride; + for (; i < size; i += size0) { + + memcpy(data[0], data[1], data_stride); + + // advance: + for (const auto arg : c10::irange(ntensors)) { + data[arg] += outer_strides[arg]; + } + } + + }; + + int64_t grain_size = at::internal::GRAIN_SIZE; + iter.for_each(loop2d, grain_size); + iter.cast_outputs(); +} + +void flip_kernel(TensorIterator& iter, const bool quantized) { + if (quantized) { + AT_DISPATCH_QINT_AND_SUB_BYTE_TYPES(iter.dtype(), "flip_quantized_cpu", + [&iter] { cpu_kernel(iter, + [](scalar_t a, scalar_t /*dummy input*/) -> scalar_t { + return a; + }); + }); + } else { + auto output_strides = iter.strides(0); + auto input_strides = iter.strides(1); + if (iter.ndim() > 0 && output_strides[0] == -iter.element_size(0) && input_strides[0] == iter.element_size(1)) { + // Special case: horizontal flip with vectorization and input is contiguous + // Context: horizontal flip leads to strides[0] < 0 and + // thus is_contiguous condition is not satisfied and non-vectorized code path is taken. + auto iter_dtype = iter.dtype(); + // Ignoring half and bfloat16 as cpu_hflip_vec is slower than cpu_kernel_vec + if (isIntegralType(iter_dtype, true) || iter_dtype == kDouble || iter_dtype == kFloat) { + // Replace AT_DISPATCH_ALL_TYPES_AND by manual if/else due to internal test failures: + // - "dtype 'Float' not selected for kernel tag hflip_cpu" + // - "dtype 'Long' not selected for kernel tag hflip_cpu" + // + // AT_DISPATCH_ALL_TYPES_AND(kBool, + // iter_dtype, "hflip_cpu", [&iter] { + // cpu_hflip_vec(iter); + // }); + + if (iter_dtype == kByte) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kChar) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kInt) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kLong) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kShort) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kBool) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kFloat) { + cpu_hflip_vec(iter); + return; + } else if (iter_dtype == kDouble) { + cpu_hflip_vec(iter); + return; + } + } + // other dtypes (float16, bfloat16, complex) are handled by cpu_kernel_vec (see below) + } else if (iter.has_contiguous_first_dim()) { + // Special cases: + // a) channels last hflip on (N, C, H, W) and outer_stride(=dtype_size * C) in [2, 16] + // b) flip dim=-2 on (N, ..., M, C) and outer_stride(=dtype_size * C) in [2, 16] + auto output_strides_2 = iter.strides(0); + auto input_strides_2 = iter.strides(1); + auto c = -output_strides_2[1]; + if (c >= 2 && c <= 16 && + c == input_strides_2[1] && + c == iter.element_size(0) * iter.shape()[0] // checks if dim=1 is contiguous as well + ) { + cpu_hflip_channels_last_vec(iter); + return; + } + // Special case: vertical flip using memcpy (faster than generic cpu_kernel_vec) + cpu_vflip_memcpy(iter); + return; + } + + AT_DISPATCH_V2( + iter.dtype(), + "flip_cpu", + AT_WRAP([&iter] { + cpu_kernel_vec(iter, + [](scalar_t a, scalar_t /*dummy input*/) -> scalar_t { + return a; + }, + [](Vectorized a, Vectorized /*dummy input*/) -> Vectorized { + return a; + }); + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), + kBool, + kHalf, + kBFloat16); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(index_stub, &index_kernel) +REGISTER_DISPATCH(index_fill_stub, &index_fill_kernel) +REGISTER_DISPATCH(index_copy_stub, &index_copy_kernel) +REGISTER_DISPATCH(index_put_stub, &index_put_kernel) +REGISTER_DISPATCH(put_stub, &put_kernel) +REGISTER_DISPATCH(take_stub, &take_kernel) +REGISTER_DISPATCH(masked_fill_stub, &masked_fill_kernel) +REGISTER_DISPATCH(masked_select_serial_stub, &masked_select_serial_kernel) +REGISTER_DISPATCH(masked_select_stub, &masked_select_kernel) +REGISTER_DISPATCH(masked_scatter_stub, &masked_scatter_kernel) +REGISTER_DISPATCH(flip_stub, &flip_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IndexKernelUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IndexKernelUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..7b1284bb4026f07c55e7b2496ec8ad7003fa1bc9 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IndexKernelUtils.h @@ -0,0 +1,85 @@ +#pragma once +#include +#include + +namespace at::native { + +inline bool is_constant_index(int ntensor, const int64_t* strides) { + AT_ASSERT(ntensor >= 3); + for (const auto arg : c10::irange(2, ntensor)) { + if (strides[arg] != 0) { + return false; + } + } + return true; +} + + +struct Indexer { + Indexer(int64_t num_indexers, char** indexers, const int64_t* indexer_strides, + IntArrayRef original_sizes, IntArrayRef original_strides) + : num_indexers(num_indexers) + , indexers(indexers) + , indexer_strides(indexer_strides) + , original_strides(original_strides.data()) + , original_sizes(original_sizes.data()) { + AT_ASSERT(static_cast(original_strides.size()) == num_indexers); + AT_ASSERT(static_cast(original_sizes.size()) == num_indexers); + } + + int64_t num_indexers; + char** indexers; + const int64_t* indexer_strides; + const int64_t* original_strides; + const int64_t* original_sizes; + + int64_t get(int64_t idx) { + int64_t offset = 0; + for (const auto j : c10::irange(num_indexers)) { + int64_t value = *(int64_t*)&indexers[j][idx * indexer_strides[j]]; + int64_t size = original_sizes[j]; + TORCH_CHECK_INDEX(value >= -size && value < size, + "index ", value, " is out of bounds for dimension ", j, " with size ", size); + if (value < 0) { + value += size; + } + offset += value * original_strides[j]; + } + return offset; + } +}; + +template +void cpu_index_kernel(TensorIteratorBase& iter, IntArrayRef index_size, IntArrayRef index_stride, + const func_t& f, bool serial_execution=false) +{ + int ntensor = iter.ntensors(); + // When launch the index parallel version, set a relative small grain size less than the INTERNAL::GRAIN_SIZE + // to make the whole available thread numbers get more balanced work load and a better cache location. + // The grain size here is chosen by the op benchmark to overcome the thread launch overhead + const int index_parallel_grain_size = 3000; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto indexer = Indexer(ntensor - 2, &data[2], &strides[2], index_size, index_stride); + char* dst = data[0]; + char* src = data[1]; + if (is_constant_index(ntensor, strides)) { + // specialization for when every element uses the same index + int64_t offset = indexer.get(0); + for (const auto i : c10::irange(n)) { + f(dst + strides[0] * i, src + strides[1] * i, offset); + } + } else { + for (const auto i : c10::irange(n)) { + int64_t offset = indexer.get(i); + f(dst + strides[0] * i, src + strides[1] * i, offset); + } + } + }; + if (serial_execution) { + iter.serial_for_each(loop, {0, iter.numel()}); + } else { + iter.for_each(loop, index_parallel_grain_size); + } +} +} // at +// native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Intrinsics.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Intrinsics.h new file mode 100644 index 0000000000000000000000000000000000000000..c85239e5a7067907af8c7e903208f2d4338c8213 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Intrinsics.h @@ -0,0 +1,33 @@ +#pragma once + +#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__)) +/* Clang-compatible compiler, targeting x86/x86-64 */ +#include +#elif defined(_MSC_VER) +/* Microsoft C/C++-compatible compiler */ +#include +#if _MSC_VER <= 1900 +#define _mm256_extract_epi64(X, Y) (((uint64_t*)&X)[Y]) +#endif +#elif defined(__GNUC__) && (defined(__x86_64__) || defined(__i386__)) +/* GCC-compatible compiler, targeting x86/x86-64 */ +#include +#elif defined(__GNUC__) && defined(__ARM_NEON__) +/* GCC-compatible compiler, targeting ARM with NEON */ +#include +#elif defined(__GNUC__) && defined(__IWMMXT__) +/* GCC-compatible compiler, targeting ARM with WMMX */ +#include +#elif (defined(__GNUC__) || defined(__xlC__)) && \ + (defined(__VEC__) || defined(__ALTIVEC__)) +/* XLC or GCC-compatible compiler, targeting PowerPC with VMX/VSX */ +#include +/* We need to undef those tokens defined by to avoid conflicts + with the C++ types. => Can still use __bool/__vector */ +#undef bool +#undef vector +#undef pixel +#elif defined(__GNUC__) && defined(__SPE__) +/* GCC-compatible compiler, targeting PowerPC with SPE */ +#include +#endif diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IsContiguous.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IsContiguous.h new file mode 100644 index 0000000000000000000000000000000000000000..6ff1afb8777f6af721d162b55399ffe958984086 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/IsContiguous.h @@ -0,0 +1,64 @@ +#pragma once + +namespace at::native { inline namespace CPU_CAPABILITY { + +// n: number of function arguments (arity) +// traits: function_traits (see FunctionTraits.h) +// s: index of scalar argument or -1 +template +struct IsContiguous { + static bool eval(const int64_t* strides) { + using type = typename traits::template arg::type; + return strides[stride_index] == (s == n ? 0 : sizeof(type)) && + IsContiguous::eval(strides); + } +}; + +// will be called when there is an output exists +template +struct IsContiguous<0, 0, traits, s> { + static bool eval(const int64_t* strides) { + return strides[0] == sizeof(typename traits::result_type); + } +}; + +// will be called when there is no output +template +struct IsContiguous<0, -1, traits, s> { + static bool eval(const int64_t* /*strides*/) { + return true; + } +}; + +// output and all inputs are contiguous +template < + typename traits, + std::enable_if_t>* = + nullptr> +static inline bool is_contiguous(const int64_t* strides) { + return IsContiguous::eval(strides); +} + +template >* = nullptr> +static inline bool is_contiguous(const int64_t* strides) { + return IsContiguous::eval(strides); +} + +// input at `s` is scalar (stride 0); output and other inputs are contiguous +// NB: output is typically at strides[0] so first input corresponds to s=1 +template >* = nullptr> +static inline bool is_contiguous_scalar(const int64_t* strides) { + static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds"); + return IsContiguous::eval(strides); +} + +template >* = nullptr> +static inline bool is_contiguous_scalar(const int64_t* strides) { + static_assert(s > 0 && s <= traits::arity, "scalar argument index out of bounds"); + return IsContiguous::eval(strides); +} + +}} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LerpKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LerpKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..667469249bbeba3a7b485564a90c3562d3e9fed3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LerpKernel.cpp @@ -0,0 +1,165 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include + +#include + +namespace at { +namespace native { +namespace { + +template +Vectorized is_lerp_weight_small(Vectorized weight) { + static_assert(!c10::is_complex::value, ""); + return weight.abs() < Vectorized(0.5); +} + +// is_lerp_weight_small doesn't work for complex because z.abs() returns a +// complex vector which can't be compared. Either implement it with z.abs_2_(), +// or fallback to the scalar function. +#if !(defined(CPU_CAPABILITY_DEFAULT) || defined(_MSC_VER) || defined(CPU_CAPABILITY_SVE256) || defined(CPU_CAPABILITY_SVE128)) +template +Vectorized> is_lerp_weight_small(Vectorized> weight) { + using vec_reg_t = decltype(weight.abs_2_()); + vec_reg_t mask = Vectorized(weight.abs_2_()) < Vectorized(0.25); + return Vectorized>(mask); +} +#else +template +Vectorized lerp_vec_map(Vectorized start, Vectorized end, Vectorized weight) { + using vec_t = Vectorized; + __at_align__ scalar_t start_arr[vec_t::size()]; + __at_align__ scalar_t end_arr[vec_t::size()]; + __at_align__ scalar_t weight_arr[vec_t::size()]; + __at_align__ scalar_t result_arr[vec_t::size()]; + + start.store(start_arr); + end.store(end_arr); + weight.store(weight_arr); + + for (auto i : c10::irange(vec_t::size())) { + result_arr[i] = lerp(start_arr[i], end_arr[i], weight_arr[i]); + } + return vec_t::loadu(result_arr); +} + +template +Vectorized> lerp_vec(Vectorized> start, Vectorized> end, Vectorized> weight) { + return lerp_vec_map(start, end, weight); +} +#endif + +template +Vectorized lerp_vec(Vectorized start, Vectorized end, Vectorized weight) { + using vec_t = Vectorized; + auto mask = is_lerp_weight_small(weight); + auto coeff = vec_t::blendv(weight - vec_t(1), weight, mask); + auto base = vec_t::blendv(end, start, mask); + return vec::fmadd(coeff, end - start, base); +} + +void lerp_scalar_kernel(at::TensorIteratorBase& iter, const Scalar& weight) { + if (iter.common_dtype() == kBFloat16) { + using bVec = Vectorized; + using fVec = Vectorized; + float weight_val = weight.to(); + auto weight_vec = fVec(weight_val); + at::native::cpu_kernel_vec( + iter, + [weight_val](BFloat16 self_val, BFloat16 end_val) -> BFloat16 { + return lerp(self_val, end_val, weight_val); + }, + [=](bVec self_vec, bVec end_vec) -> bVec { + auto [self_vec0, self_vec1] = convert_bfloat16_float(self_vec); + auto [end_vec0, end_vec1] = convert_bfloat16_float(end_vec); + auto result0 = lerp_vec(self_vec0, end_vec0, weight_vec); + auto result1 = lerp_vec(self_vec1, end_vec1, weight_vec); + return convert_float_bfloat16(result0, result1); + }); + } else if (iter.common_dtype() == kHalf) { + using hVec = Vectorized; + using fVec = Vectorized; + float weight_val = weight.to(); + auto weight_vec = fVec(weight_val); + at::native::cpu_kernel_vec( + iter, + [weight_val](Half self_val, Half end_val) -> Half { + return lerp(self_val, end_val, weight_val); + }, + [=](hVec self_vec, hVec end_vec) -> hVec { + auto [self_vec0, self_vec1] = convert_half_float(self_vec); + auto [end_vec0, end_vec1] = convert_half_float(end_vec); + auto result0 = lerp_vec(self_vec0, end_vec0, weight_vec); + auto result1 = lerp_vec(self_vec1, end_vec1, weight_vec); + return convert_float_half(result0, result1); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(iter.common_dtype(), "lerp_kernel_scalar", [&] { + auto weight_val = weight.to(); + at::native::cpu_kernel_vec( + iter, + [weight_val](scalar_t self_val, scalar_t end_val) { + return lerp(self_val, end_val, weight_val); + }, + [weight_val](Vectorized self, Vectorized end) { + const Vectorized weight(weight_val); + return lerp_vec(self, end, weight); + }); + }); + } +} + +void lerp_tensor_kernel(at::TensorIteratorBase& iter) { + if (iter.common_dtype() == kBFloat16) { + using bVec = Vectorized; + at::native::cpu_kernel_vec( + iter, + [=](BFloat16 self_val, BFloat16 end_val, BFloat16 weight_val) -> BFloat16 { + return lerp(self_val, end_val, weight_val); + }, + [=](bVec self_vec, bVec end_vec, bVec weight_vec) -> bVec { + auto [self_vec0, self_vec1] = convert_bfloat16_float(self_vec); + auto [end_vec0, end_vec1] = convert_bfloat16_float(end_vec); + auto [weight_vec0, weight_vec1] = convert_bfloat16_float(weight_vec); + auto result0 = lerp_vec(self_vec0, end_vec0, weight_vec0); + auto result1 = lerp_vec(self_vec1, end_vec1, weight_vec1); + return convert_float_bfloat16(result0, result1); + }); + } else if (iter.common_dtype() == kHalf) { + using hVec = Vectorized; + at::native::cpu_kernel_vec( + iter, + [=](Half self_val, Half end_val, Half weight_val) -> Half { + return lerp(self_val, end_val, weight_val); + }, + [=](hVec self_vec, hVec end_vec, hVec weight_vec) -> hVec { + auto [self_vec0, self_vec1] = convert_half_float(self_vec); + auto [end_vec0, end_vec1] = convert_half_float(end_vec); + auto [weight_vec0, weight_vec1] = convert_half_float(weight_vec); + auto result0 = lerp_vec(self_vec0, end_vec0, weight_vec0); + auto result1 = lerp_vec(self_vec1, end_vec1, weight_vec1); + return convert_float_half(result0, result1); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(iter.common_dtype(), "lerp_kernel_tensor", [&] { + at::native::cpu_kernel_vec( + iter, + [](scalar_t self_val, scalar_t end_val, scalar_t weight_val) { + return lerp(self_val, end_val, weight_val); + }, + [](Vectorized self_val, Vectorized end_val, Vectorized weight_val) { + return lerp_vec(self_val, end_val, weight_val); + }); + }); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(lerp_kernel_scalar_weight, &lerp_scalar_kernel) +REGISTER_DISPATCH(lerp_kernel_tensor_weight, &lerp_tensor_kernel) + +} // namespace native +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LinearAlgebraKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LinearAlgebraKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb43d2e83ee1336527d234ac4c0bf9e17bbd1bad --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LinearAlgebraKernel.cpp @@ -0,0 +1,89 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { namespace { + +void addr_kernel(TensorIterator &iter, + const Scalar& beta, const Scalar& alpha) { + if (iter.dtype() == ScalarType::Bool) { + using scalar_t = bool; + auto beta_val = beta.to(); + auto alpha_val = alpha.to(); + + // when beta is false, values in self should be ignored, + // nans and infs in self should not propagate. + if (beta_val == false) { + cpu_kernel(iter, + [=](scalar_t /*self_val*/, + scalar_t vec1_val, + scalar_t vec2_val) -> scalar_t { + return alpha_val && vec1_val && vec2_val; + } + ); + } else { + cpu_kernel(iter, + [=](scalar_t self_val, + scalar_t vec1_val, + scalar_t vec2_val) -> scalar_t { + return (beta_val && self_val) || (alpha_val && vec1_val && vec2_val); + } + ); + } + return; + } + + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, + iter.dtype(), "addr_cpu", [&]() { + using Vec = Vectorized; + + auto beta_val = beta.to(); + auto alpha_val = alpha.to(); + + auto beta_vec = Vec(beta_val); + auto alpha_vec = Vec(alpha_val); + + const scalar_t zero_val(0); + // when beta == 0, values in self should be ignored, + // nans and infs in self should not propagate. + if (beta_val == zero_val) { + cpu_kernel_vec(iter, + [=](scalar_t /*self_val*/, + scalar_t vec1_val, + scalar_t vec2_val) __ubsan_ignore_undefined__ -> scalar_t { + return alpha_val * vec1_val * vec2_val; + }, + [=](Vec /*self_vec*/, + Vec vec1_vec, + Vec vec2_vec) __ubsan_ignore_undefined__ { + return alpha_vec * vec1_vec * vec2_vec; + } + ); + } else { + cpu_kernel_vec(iter, + [=](scalar_t self_val, + scalar_t vec1_val, + scalar_t vec2_val) __ubsan_ignore_undefined__ -> scalar_t { + return beta_val * self_val + alpha_val * vec1_val * vec2_val; + }, + [=](Vec self_vec, + Vec vec1_vec, + Vec vec2_vec) __ubsan_ignore_undefined__ { + return beta_vec * self_vec + alpha_vec * vec1_vec * vec2_vec; + } + ); + } + } + ); +} + +} // anonymous namespace + +REGISTER_DISPATCH(addr_stub, &addr_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LogAddExp.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LogAddExp.h new file mode 100644 index 0000000000000000000000000000000000000000..ebed2b70ea820d0761110ea438905842f0877385 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LogAddExp.h @@ -0,0 +1,61 @@ +#pragma once + +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + +// custom min and max to be used in logcumsumexp for complex arguments +template +std::pair, c10::complex> _logcumsumexp_minmax(c10::complex x, c10::complex y) { + if (at::_isnan(y)) { // either real is nan or imag is nan + return std::make_pair(y, y); + } else if (at::_isnan(x)) { // either real is nan or imag is nan + return std::make_pair(x, x); + } else { + return (x.real() < y.real()) ? std::make_pair(x, y) : std::make_pair(y, x); + } +} + +template +scalar_t _log_add_exp_helper(scalar_t x, scalar_t y) { + // Reference : https://www.tensorflow.org/api_docs/python/tf/math/cumulative_logsumexp + scalar_t min = at::_isnan(y) ? y : std::min(x, y); // std::min returns first arg if one of the args is nan + scalar_t max = at::_isnan(y) ? y : std::max(x, y); // std::max returns first arg if one of the args is nan + if (min != max || std::isfinite(min)) { + // nan will be propagated here + return std::log1p(std::exp(min - max)) + max; + } else { + // special case to correctly handle infinite cases + return x; + } +} + +template +c10::complex _log_add_exp_helper(const c10::complex& x, const c10::complex& y) { + auto [min, max] = _logcumsumexp_minmax(x, y); + auto min_real = std::real(min); + auto max_real = std::real(max); + + if (at::_isnan(min)) { // either real is nan or imag is nan + // handling the "infectious" NaNs + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } else if (!std::isfinite(min_real) && (min_real == max_real)) { + if (min_real < 0) { + // handle the -inf case, the imaginary part here does not really matter as the exp(value) + // will be around 0.0 and the angle (i.e. the imaginary part) cannot be determined. + // It does not matter if we're taking the exp of this value + return min; + } else { + // handle the +inf case, we don't need the special precision for log1p for small values + // and to avoid producing nan in case of real(max) == real(min) == +inf + return std::log(std::exp(min) + std::exp(max)); + } + } else { + return std::log1p(std::exp(min - max)) + max; + } +} + +} // end namespace +} //end at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LogSoftmaxKernelImpl.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LogSoftmaxKernelImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..0c979702030c5b41b1e0d09e64ba1ba091886ff5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/LogSoftmaxKernelImpl.h @@ -0,0 +1,337 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { +template +int64_t vec_log_softmax_lastdim_chunk_size(int64_t grain_size, int64_t outer_size, int64_t dim_size) { + // Coincidentally, at::internal::GRAIN_SIZE is 32768, which is equal to the + // size of L1D cache on many processors. Some processors have 48 KB L1D cache + // nowadays, so maybe in the future, we can leverage the knowledge of a + // machine's L1D cache size. + int64_t MAX_CHUNK_SIZE = std::max( + 1, + grain_size / (sizeof(scalar_t) * dim_size)); + return std::min(MAX_CHUNK_SIZE, outer_size); +} + +template +void serial_vec_log_softmax_lastdim_range( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t dim_size, + int64_t chunk_size, + int64_t begin, + int64_t end) { + if (end <= begin) { + return; + } + using Vec = vec::Vectorized>; + // MSVC requires such a declaration of dynamic arrays + // Source: https://stackoverflow.com/a/33423538 + auto tmp_sum_scalar = std::make_unique(chunk_size); + auto max_input_arr = std::make_unique(chunk_size); + for (int64_t ii = begin; ii < end; ii += chunk_size) { + int64_t loop_end = chunk_size; + if (ii + chunk_size > end) { + loop_end = end - ii; + } + for (const auto j : c10::irange(loop_end)) { + int64_t i = ii + j; + const scalar_t* input_data = input_data_base + i * dim_size; + max_input_arr[j] = vec::reduce_all( + [](Vec& x, Vec& y) { return vec::maximum(x, y); }, + input_data, + dim_size); + } + for (const auto j : c10::irange(loop_end)) { + int64_t i = ii + j; + const scalar_t* input_data = input_data_base + i * dim_size; + scalar_t max_input = max_input_arr[j]; + tmp_sum_scalar[j] = vec::map_reduce_all( + [max_input](Vec x) { return (x - Vec(max_input)).exp(); }, + [](Vec x, Vec y) { return x + y; }, + input_data, + dim_size); + } + // See [Note AVX-SSE transitions] for why this should call the + // vectorized version (aside from perf improvements). + vec::map( + [](Vec x) { return x.log(); }, + tmp_sum_scalar.get(), + tmp_sum_scalar.get(), + loop_end); + for (const auto j : c10::irange(loop_end)) { + int64_t i = ii + j; + const scalar_t* input_data = input_data_base + i * dim_size; + scalar_t* output_data = output_data_base + i * dim_size; + scalar_t tmp_sum = tmp_sum_scalar[j]; + scalar_t max_input = max_input_arr[j]; + + // It's necessary to keep the order of the operations below. + // In some cases that input is large digits and the difference + // is small, if we compute `max_input` plus `tmp_sum` before, + // there would be a numerical problem. See an example in + // https://github.com/pytorch/pytorch/issues/11752#issuecomment-422883379 + vec::map( + [tmp_sum, max_input](Vec x) { + return x - Vec(max_input) - Vec(tmp_sum); + }, + output_data, + input_data, + dim_size); + } + } +} + +// Can't include ATen/Parallel.h. +// TODO: find a way to have only one copy of divup. +inline int64_t divup(int64_t x, int64_t y) { + return (x + y - 1) / y; +} + +template +std::pair vec_logsoftmax_chunk_size_and_num_chunks(int64_t inner_size, int64_t dim_size) { + using Vec = vec::Vectorized; + int64_t MAX_CHUNK_SIZE = std::max(BLOCK_SIZE / dim_size / sizeof(scalar_t), Vec::size()); + MAX_CHUNK_SIZE = MAX_CHUNK_SIZE / Vec::size() * Vec::size(); + int64_t CHUNK_SIZE = std::min(MAX_CHUNK_SIZE, inner_size); + int64_t num_chunks = divup(inner_size, CHUNK_SIZE); + return {CHUNK_SIZE, num_chunks}; +} + +template +std::enable_if_t>, void> +serial_vec_logsoftmax_range( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t inner_size, + int64_t chunk_size, + int64_t num_chunks, + int64_t dim_size, + int64_t begin, + int64_t end) { + using Vec = vec::Vectorized; + // thread local temp buffer which holds vertical reduction result: max and sum. + auto buffer = std::make_unique(chunk_size * 2); + scalar_t* input_max_data = buffer.get(); + scalar_t* tmp_sum_data = buffer.get() + chunk_size; + + for (int64_t i = begin; i < end; i++) { + int64_t outer_idx = i / num_chunks; + int64_t k = i % num_chunks; + int64_t inner_idx_begin = k * chunk_size; + int64_t size = std::min(chunk_size, inner_size - inner_idx_begin); + + // init + Vec zero_vec = Vec(scalar_t(0)); + Vec min_vec = Vec(-std::numeric_limits::infinity()); + int64_t d0 = 0; + for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) { + min_vec.store(input_max_data + d0); + zero_vec.store(tmp_sum_data + d0); + } + for (; d0 < size; d0++) { + input_max_data[d0] = -std::numeric_limits::infinity(); + tmp_sum_data[d0] = scalar_t(0); + } + + // compute max + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + const scalar_t* input_ptr = input_data_base + outer_idx * dim_size * inner_size + + dim_idx * inner_size + inner_idx_begin; + + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec data_vec = Vec::loadu(input_ptr + d1); + Vec max_vec = Vec::loadu(input_max_data + d1); + max_vec = Vec::blendv(max_vec, data_vec, data_vec > max_vec); + max_vec.store(input_max_data + d1); + } + for (; d1 < size; d1++) { + scalar_t data_val = input_ptr[d1]; + scalar_t max_val = input_max_data[d1]; + input_max_data[d1] = data_val > max_val ? data_val : max_val; + } + } + + // compute sum of (x - max).exp() + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + const scalar_t* input_ptr = input_data_base + outer_idx * dim_size * inner_size + + dim_idx * inner_size + inner_idx_begin; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + Vec data_vec = Vec::loadu(input_ptr + d2); + Vec sum_vec = Vec::loadu(tmp_sum_data + d2); + Vec max_vec = Vec::loadu(input_max_data + d2); + sum_vec += (data_vec - max_vec).exp(); + sum_vec.store(tmp_sum_data + d2); + } + for (; d2 < size; d2++) { + scalar_t data_val = input_ptr[d2]; + scalar_t max_val = input_max_data[d2]; + tmp_sum_data[d2] += std::exp(data_val - max_val); + } + } + + // apply log + vec::map([](Vec x) { return x.log(); }, tmp_sum_data, tmp_sum_data, size); + + // compute x - max - sum + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + int64_t offset = outer_idx * dim_size * inner_size + dim_idx * inner_size + inner_idx_begin; + const scalar_t* input_ptr = input_data_base + offset; + scalar_t* output_ptr = output_data_base + offset; + + int64_t d3 = 0; + for (; d3 < size - (size % Vec::size()); d3 += Vec::size()) { + Vec data_vec = Vec::loadu(input_ptr + d3); + Vec max_vec = Vec::loadu(input_max_data + d3); + Vec sum_vec = Vec::loadu(tmp_sum_data + d3); + Vec out_vec = data_vec - max_vec - sum_vec; + out_vec.store(output_ptr + d3); + } + for (; d3 < size; d3++) { + output_ptr[d3] = input_ptr[d3] - input_max_data[d3] - tmp_sum_data[d3]; + } + } + } +} + +template +std::enable_if_t>, void> +serial_vec_logsoftmax_range( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t inner_size, + int64_t chunk_size, + int64_t num_chunks, + int64_t dim_size, + int64_t begin, + int64_t end) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + auto buffer = std::make_unique(chunk_size * 2); + float* input_max_data = buffer.get(); + float* tmp_sum_data = buffer.get() + chunk_size; + + // thread local buffer that holds input data in float32 to save next 2 dtype conversion + auto input_buffer = std::make_unique(dim_size * chunk_size); + float* input_buffer_data = input_buffer.get(); + + // init + for (int64_t i = begin; i < end; i++) { + int64_t outer_idx = i / num_chunks; + int64_t k = i % num_chunks; + int64_t inner_idx_begin = k * chunk_size; + int64_t size = std::min(chunk_size, inner_size - inner_idx_begin); + + fVec zero_fvec = fVec(float(0)); + fVec min_fvec = fVec(-std::numeric_limits::infinity()); + int64_t d0 = 0; + for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) { + min_fvec.store(input_max_data + d0); + min_fvec.store(input_max_data + d0 + fVec::size()); + zero_fvec.store(tmp_sum_data + d0); + zero_fvec.store(tmp_sum_data + d0 + fVec::size()); + } + for (; d0 < size; d0++) { + input_max_data[d0] = -std::numeric_limits::infinity(); + tmp_sum_data[d0] = float(0); + } + + // compute max + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + const scalar_t* input_ptr = input_data_base + outer_idx * dim_size * inner_size + + dim_idx * inner_size + inner_idx_begin; + float* input_buffer_ptr = input_buffer_data + dim_idx * chunk_size; + + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec data_vec = Vec::loadu(input_ptr + d1); + auto [data_fvec0, data_fvec1] = vec::convert_to_float(data_vec); + fVec max_fvec0 = fVec::loadu(input_max_data + d1); + fVec max_fvec1 = fVec::loadu(input_max_data + d1 + fVec::size()); + max_fvec0 = fVec::blendv(max_fvec0, data_fvec0, data_fvec0 > max_fvec0); + max_fvec1 = fVec::blendv(max_fvec1, data_fvec1, data_fvec1 > max_fvec1); + max_fvec0.store(input_max_data + d1); + max_fvec1.store(input_max_data + d1 + fVec::size()); + + // cache the 'converted' float input + data_fvec0.store(input_buffer_ptr + d1); + data_fvec1.store(input_buffer_ptr + d1 + fVec::size()); + } + for (; d1 < size; d1++) { + float data_val = float(input_ptr[d1]); + float max_val = input_max_data[d1]; + input_max_data[d1] = data_val > max_val ? data_val : max_val; + input_buffer_ptr[d1] = data_val; + } + } + + // compute sum of (x - max).exp() + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + float* input_buffer_ptr = input_buffer_data + dim_idx * chunk_size; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + fVec data_fvec0 = fVec::loadu(input_buffer_ptr + d2); + fVec data_fvec1 = fVec::loadu(input_buffer_ptr + d2 + fVec::size()); + fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d2); + fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d2 + fVec::size()); + fVec max_fvec0 = fVec::loadu(input_max_data + d2); + fVec max_fvec1 = fVec::loadu(input_max_data + d2 + fVec::size()); + sum_fvec0 += (data_fvec0 - max_fvec0).exp(); + sum_fvec1 += (data_fvec1 - max_fvec1).exp(); + sum_fvec0.store(tmp_sum_data + d2); + sum_fvec1.store(tmp_sum_data + d2 + fVec::size()); + } + for (; d2 < size; d2++) { + float data_val = input_buffer_ptr[d2]; + float max_val = input_max_data[d2]; + tmp_sum_data[d2] += std::exp(data_val - max_val); + } + } + + // apply log + vec::map([](fVec x) { return x.log(); }, tmp_sum_data, tmp_sum_data, size); + + // compute x - max - sum + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + float* input_buffer_ptr = input_buffer_data + dim_idx * chunk_size; + scalar_t* output_ptr = output_data_base + outer_idx * dim_size * inner_size + + dim_idx * inner_size + inner_idx_begin; + + int64_t d3 = 0; + for (; d3 < size - (size % Vec::size()); d3 += Vec::size()) { + fVec data_fvec0 = fVec::loadu(input_buffer_ptr + d3); + fVec data_fvec1 = fVec::loadu(input_buffer_ptr + d3 + fVec::size()); + fVec max_fvec0 = fVec::loadu(input_max_data + d3); + fVec max_fvec1 = fVec::loadu(input_max_data + d3 + fVec::size()); + fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d3); + fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d3 + fVec::size()); + fVec out_fvec0 = data_fvec0 - max_fvec0 - sum_fvec0; + fVec out_fvec1 = data_fvec1 - max_fvec1 - sum_fvec1; + Vec out_vec = vec::convert_from_float(out_fvec0, out_fvec1); + out_vec.store(output_ptr + d3); + } + for (; d3 < size; d3++) { + output_ptr[d3] = scalar_t(input_buffer_ptr[d3] - input_max_data[d3] - tmp_sum_data[d3]); + } + } + } +} // namespace CPU_CAPABILITY +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Loops.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Loops.h new file mode 100644 index 0000000000000000000000000000000000000000..a32df5c8825e2bc8abded2d88d3aed37b1157487 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Loops.h @@ -0,0 +1,401 @@ +#pragma once + +// This file provides two functions to help write elementwise kernels: +// +// cpu_kernel(TensorIterator iter, ) +// cpu_kernel_vec(TensorIterator iter, , ) +// +// Both functions may generate vectorized code. The cpu_kernel implementation +// relies on the compiler's auto-vectorization. The cpu_kernel_vec +// implementation uses x86 SIMD intrinsics when available. These functions +// are only intended to be used in the ATen/native/cpu subdirectory, since files +// in other directories are not compiled with AVX/AVX2 enabled. See README.md +// for more details. +// +// For example, to write a multiplication kernel for float: +// +// cpu_kernel(iter, [](float a, float b) { return a * b; }); +// +// Or you may write: +// +// cpu_kernel_vec(iter, +// [](float a, float b) { return a * b; }, +// [](Vectorized a, Vectorized b) { return a * b; }); +// +// See BinaryOpsKernel.cpp for the complete implementation +// +// + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace at::native { inline namespace CPU_CAPABILITY { + +using namespace vec; + +template +typename traits::ArgsTuple +dereference_impl(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, + std::index_sequence /*unused*/) { + return std::make_tuple( + c10::load::type>( + data[INDEX] + i * strides[INDEX])...); +} + +template +typename traits::ArgsTuple +dereference(char* C10_RESTRICT data[], const int64_t* strides, int64_t i) { + using Indices = std::make_index_sequence; + return dereference_impl(data, strides, i, Indices{}); +} + +template +typename traits::ArgsTuple +dereference_vec_impl(char* C10_RESTRICT data[], + const typename traits::result_type& opt_scalar, + size_t S, + int64_t i, + std::index_sequence /*unused*/) { + using Vec = typename traits::result_type; + using scalar_t = typename Vec::value_type; + return std::make_tuple( + S == INDEX + 1 ? + opt_scalar : + Vec::loadu(data[INDEX] + i * sizeof(scalar_t))...); +} + +template +typename traits::ArgsTuple +dereference_vec(char* C10_RESTRICT data[], const typename traits::result_type& opt_scalar, size_t S, int64_t i) { + using Indices = std::make_index_sequence; + return dereference_vec_impl(data, opt_scalar, S, i, Indices{}); +} + +template ::result_type>>* = nullptr> +inline void +execute_op(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, int64_t n, func_t&& op) { + using traits = function_traits; + using result_type = typename traits::result_type; + for (; i < n; i++) { + result_type* out_ptr = (result_type*)(data[0] + i * strides[0]); + *out_ptr = std::apply(op, dereference( + &data[1], + &strides[1], + i)); + } +} + +template ::result_type>>* = nullptr> +inline void +execute_op(char* C10_RESTRICT data[], const int64_t* strides, int64_t i, int64_t n, func_t&& op) { + using traits = function_traits; + for (; i < n; i++) { + std::apply(op, dereference( + &data[0], + &strides[0], + i)); + } +} + +// Basic loop operation (one output, N inputs). May be auto-vectorized +// by the compiler. Supports inputs and outputs of different types. +template +inline void +basic_loop(char* C10_RESTRICT data[], const int64_t* strides_, int64_t i, int64_t n, func_t&& op) { + using traits = function_traits; + constexpr int ntensors = traits::arity + 1; + + // Copying strides to temporary array helps auto vectorization in older GCC + // versions. + int64_t strides[ntensors]; + for (const auto arg : c10::irange(ntensors)) { + strides[arg] = strides_[arg]; + } + + execute_op(data, strides, i, n, std::forward(op)); +} + +// the recursive variadic template for iterating over the returned tuple +template +struct TupleOutput { + static void handle(char *C10_RESTRICT data[], const int64_t *strides, int64_t i, + const T &tuple) { + TupleOutput::handle(data, strides, i, tuple); + + auto output = std::get(tuple); + using output_type = decltype(output); + output_type * out_ptr = (output_type *)(data[N - 1] + i * strides[N - 1]); + *out_ptr = output; + } +}; + +// Base case for the above recursive template +template +struct TupleOutput { + static void handle(char *C10_RESTRICT data[], const int64_t *strides, int64_t i, + const T &tuple) { + auto output = std::get<0>(tuple); + using output_type = decltype(output); + output_type* out_ptr = (output_type *)(data[0] + i * strides[0]); + *out_ptr = output; + } +}; + +template +void handle_tuple_outputs(char* C10_RESTRICT data[], + const int64_t* strides, + int64_t i, + const std::tuple &tuple) { + TupleOutput::handle(data, strides, i, tuple); +} + +// Loop operation for `cpu_kernel_multiple_outputs`. +// 1. Use `std::apply` to make dynamic method invocation +// for the lambda passed in `cpu_kernel_multiple_outputs`. +// 2. Iterate over the members of the returned tuple, set the corresponding +// output tensor by the tuple member in `handle_tuple_outputs` function. +template +inline void +multiple_outputs_loop(char* C10_RESTRICT data[], const int64_t* strides_, int64_t i, int64_t n, func_t&& op) { + using traits = function_traits; + + using result_type = typename traits::result_type; + constexpr int num_outputs = std::tuple_size_v; + constexpr int ntensors = traits::arity + num_outputs; + + // Copying strides to temporary array helps auto vectorization in older GCC + // versions. + int64_t strides[ntensors]; + for (const auto arg : c10::irange(ntensors)) { + strides[arg] = strides_[arg]; + } + + for (; i < n; i++) { + auto output = std::apply(op, dereference( + &data[num_outputs], + &strides[num_outputs], + i)); + handle_tuple_outputs(data, strides, i, output); + } +} + +// Explicitly vectorized loop implementation. All inputs and outputs must be +// the same type and contiguous with one exception: a single input may be +// a scalar (stride 0). It's position is indicated by the argument `S`. If `S` +// is 0, then there are no scalar inputs. +template +inline void +vectorized_loop(char** C10_RESTRICT data_, int64_t n, int64_t S, func_t&& op, vec_func_t&& vop) { + using traits = function_traits; + using scalar_t = typename function_traits::result_type; + using Vec = Vectorized; + constexpr int ntensors = traits::arity + 1; + + char* C10_RESTRICT data[ntensors]; + for (const auto arg : c10::irange(ntensors)) { + data[arg] = data_[arg]; + } + + Vec opt_scalar = Vec(S > 0 ? c10::load((scalar_t*)data[S]) : scalar_t(0)); + int64_t i = 0; + for (; i <= n - 2 * Vec::size(); i += 2 * Vec::size()) { + auto args1 = dereference_vec(&data[1], opt_scalar, S, i); + auto args2 = dereference_vec(&data[1], opt_scalar, S, i + Vec::size()); + auto out1 = std::apply(vop, std::move(args1)); + auto out2 = std::apply(vop, std::move(args2)); + out1.store(data[0] + i * sizeof(scalar_t)); + out2.store(data[0] + (i + Vec::size()) * sizeof(scalar_t)); + } + if (i < n) { + int64_t strides[ntensors]; + for (const auto arg : c10::irange(ntensors)) { + strides[arg] = (S > 0 && arg == S) ? 0 : sizeof(scalar_t); + } + basic_loop(data, strides, i, n, std::forward(op)); + } +} + + +template +inline void unroll_contiguous_scalar_checks( + const int64_t* /*strides*/, + std::index_sequence<> /*unused*/, + cb_t&& cb) { + cb(0); +} + +template +inline void unroll_contiguous_scalar_checks( + const int64_t* strides, + std::index_sequence /*unused*/, + cb_t&& cb) { + if (is_contiguous_scalar(strides)) { + cb(INDEX0 + 1); + } else { + unroll_contiguous_scalar_checks(strides, std::index_sequence{}, std::forward(cb)); + } +} + +template +struct VectorizedLoop2d { + op_t op; + vop_t vop; + + using traits = function_traits; + static constexpr int ntensors = traits::arity + 1; + using data_t = std::array; + + VectorizedLoop2d(op_t op, vop_t vop): + op(std::move(op)), vop(std::move(vop)) {} + + static void advance(data_t &data, const int64_t *outer_strides) { + for (const auto arg : c10::irange(data.size())) { + data[arg] += outer_strides[arg]; + } + } + + void operator()(char** base, const int64_t *strides, int64_t size0, int64_t size1) { + data_t data; + std::copy_n(base, ntensors, data.data()); + const int64_t *outer_strides = &strides[ntensors]; + + if (is_contiguous(strides)) { + for ([[maybe_unused]] const auto i : c10::irange(size1)) { + vectorized_loop(data.data(), size0, 0, op, vop); + advance(data, outer_strides); + } + } else { + using Indices = std::make_index_sequence; + unroll_contiguous_scalar_checks(strides, Indices{}, [&](size_t idx) { + if (idx) { + for ([[maybe_unused]] const auto i : c10::irange(size1)) { + vectorized_loop(data.data(), size0, idx, op, vop); + advance(data, outer_strides); + } + } else { + for ([[maybe_unused]] const auto i : c10::irange(size1)) { + basic_loop(data.data(), strides, 0, size0, op); + advance(data, outer_strides); + } + } + }); + } + } +}; + +template +VectorizedLoop2d make_vectorized_loop2d( + op_t &&op, vop_t &&vop) { + return VectorizedLoop2d(std::forward(op), std::forward(vop)); +} + +template +void cpu_kernel(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE, bool check_dynamic_casting = true) { + using traits = function_traits; + // this could be extended to work with void return types + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + // dynamic casting not currently supported on CPU + if (check_dynamic_casting) { + TORCH_INTERNAL_ASSERT(!needs_dynamic_casting::check(iter)); + } + + iter.for_each([&](char** data, const int64_t* strides, int64_t n) { + // basic loop can handle 1d slices with arbitrary strides, and 1d slices is all that + // iter.for_each is ever sending to the loop lambda + basic_loop(data, strides, 0, n, op); + }, grain_size); + iter.cast_outputs(); +} + +template +void cpu_kernel_opaque(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE) { + return cpu_kernel(iter, op, grain_size, false); +} + +// This function helps write elementwise kernels that requires multiple outputs. +// It follows the similar structure of cpu_kernel. +// Instead of `basic_loop` function, a new `multiple_outputs_loop` function is +// manipulated to handle multiple return values. +// For now `needs_dynamic_casting` check is not added as the passed lambda (`func_t`) +// of `multiple_outputs_loop` returns `std::tuple` instead of `scalar_t`. +// The `gpu_kernel_multiple_outputs` is also implemented without this check, +// We could extend `needs_dynamic_casting` to support both `std::tuple` and +// `thrust::tuple` in the future. +template +void cpu_kernel_multiple_outputs(TensorIteratorBase& iter, func_t&& op, int64_t grain_size = at::internal::GRAIN_SIZE) { + using traits = function_traits; + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity); + + iter.for_each([&](char** data, const int64_t* strides, int64_t n) { + multiple_outputs_loop(data, strides, 0, n, op); + }, grain_size); + iter.cast_outputs(); +} + +template +void cpu_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop, int64_t grain_size = at::internal::GRAIN_SIZE) { + using traits = function_traits; + // this could be extended to work with void return types + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + // dynamic casting not currently supported on CPU, but some kernels (like Fill) + // explicitly dynamic_cast, so we give the opt-out of checking. + if constexpr (check_dynamic_cast) { + TORCH_INTERNAL_ASSERT(!needs_dynamic_casting::check(iter)); + } + + iter.for_each(make_vectorized_loop2d(std::forward(op), std::forward(vop)), grain_size); + iter.cast_outputs(); +} + +template +void cpu_serial_kernel(TensorIteratorBase& iter, func_t&& op, const Range& range) { + using traits = function_traits; + constexpr bool result_void = std::is_void_v; + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity && + ((result_void && iter.noutputs() == 0) || (!result_void && iter.noutputs() == 1))); + // dynamic casting not currently supported on CPU + TORCH_INTERNAL_ASSERT(!needs_dynamic_casting::check(iter)); + + iter.serial_for_each([&](char** data, const int64_t* strides, int64_t n) { + basic_loop(data, strides, 0, n, op); + }, range); + iter.cast_outputs(); +} + +template +void cpu_serial_kernel(TensorIteratorBase& iter, func_t&& op) { + cpu_serial_kernel(iter, std::forward(op), {0, iter.numel()}); +} + +template +void cpu_serial_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop, const Range& range) { + using traits = function_traits; + // this could be extended to work with void return types + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + // dynamic casting not currently supported on CPU + TORCH_INTERNAL_ASSERT(!needs_dynamic_casting::check(iter)); + + iter.serial_for_each(make_vectorized_loop2d(std::forward(op), std::forward(vop)), range); + iter.cast_outputs(); +} + +template +void cpu_serial_kernel_vec(TensorIteratorBase& iter, func_t&& op, vec_func_t&& vop) { + cpu_serial_kernel_vec(iter, std::forward(op), std::forward(vop), {0, iter.numel()}); +} + +}} // namespace at::native:: diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxPoolKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxPoolKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c820655d1be723800d3bb13a73bcfa3b6635d66 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxPoolKernel.cpp @@ -0,0 +1,747 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +bool is_nan(scalar_t v) { + if (std::is_integral_v || std::is_same_v) { + return false; + } + return std::isnan(v); +} + +template +vec::Vectorized is_nan_vec(vec::Vectorized vec) { + return vec.isnan(); +} + +// TODO: use is_integral/is_same to check the scalar_t and simplify the implementation +// currently it does not work +template <> +vec::Vectorized is_nan_vec(vec::Vectorized vec) { + Vectorized ret(false); + return ret; +} + +template <> +vec::Vectorized is_nan_vec(vec::Vectorized vec) { + Vectorized ret(false); + return ret; +} + +template <> +vec::Vectorized is_nan_vec(vec::Vectorized vec) { + Vectorized ret(false); + return ret; +} + +template <> +vec::Vectorized is_nan_vec(vec::Vectorized vec) { + Vectorized ret(false); + return ret; +} + +template <> +vec::Vectorized is_nan_vec(vec::Vectorized vec) { + Vectorized ret(false); + return ret; +} + +template +inline +std::enable_if_t, void> +compute_internal( + const scalar_t* input_data, + scalar_t* out_data, + opmath_t* max_ptr, + vec::int_same_size_t* index_ptr, + int64_t* ind, + int64_t input_depth, int64_t input_height, int64_t input_width, int64_t channels, + int64_t n, + int64_t len, + int64_t size, + int64_t id0, int64_t id1, + int64_t ih0, int64_t ih1, + int64_t iw0, int64_t iw1, + int64_t dilationD, + int64_t dilationH, + int64_t dilationW) { + using Vec = vec::Vectorized; + using integer_t = vec::int_same_size_t; + using iVec = vec::Vectorized; + // Pass I: init out lane + iVec index0_vec = iVec(id0 * input_height * input_width + ih0 * input_width + iw0); + + scalar_t min_value = lower_bound(); + Vec out_vec = Vec(min_value); + int64_t d1 = 0; + for (; d1 < len; d1 += Vec::size()) { + index0_vec.store(index_ptr + d1); + out_vec.store(out_data + d1); + } + for (; d1 < size; d1++) { + ind[d1] = ih0 * input_width + iw0; + out_data[d1] = min_value; + } + // Pass II: compute local max + for (int64_t id = id0; id < id1; id += dilationD) { + for (int64_t ih = ih0; ih < ih1; ih += dilationH) { + for (int64_t iw = iw0; iw < iw1; iw += dilationW) { + const scalar_t* in = input_data + (n * input_depth * input_height * input_width + + id * input_height * input_width + ih * input_width + iw) * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += Vec::size()) { + iVec index_vec = iVec(id * input_height * input_width + ih * input_width + iw); + Vec val_vec = Vec::loadu(in + d2); + iVec maxindex_vec = iVec::loadu(index_ptr + d2); + Vec maxval_vec = Vec::loadu(out_data + d2); + + // true = all ones, false = all zeros + Vec mask = (val_vec > maxval_vec) | is_nan_vec(val_vec); + iVec imask = vec::cast(mask); + Vec out_vec = Vec::blendv(maxval_vec, val_vec, mask); + iVec ind_vec = iVec::blendv(maxindex_vec, index_vec, imask); + + out_vec.store(out_data + d2); + ind_vec.store(index_ptr + d2); + } + for (; d2 < size; d2++) { + int64_t index = id * input_height * input_width + ih * input_width + iw; + scalar_t val = in[d2]; + int64_t maxindex = ind[d2]; + scalar_t maxval = out_data[d2]; + + bool mask = (val > maxval) || is_nan(static_cast(val)); + out_data[d2] = mask ? val : maxval; + ind[d2] = mask ? index : maxindex; + } + } + } + } +} + +// std::is_same || std::is_same +template +inline +std::enable_if_t, void> +compute_internal( + const scalar_t* input_data, + scalar_t* out_data, + opmath_t* max_ptr, + vec::int_same_size_t* index_ptr, + int64_t* ind, + int64_t input_depth, int64_t input_height, int64_t input_width, int64_t channels, + int64_t n, + int64_t len, + int64_t size, + int64_t id0, int64_t id1, + int64_t ih0, int64_t ih1, + int64_t iw0, int64_t iw1, + int64_t dilationD, + int64_t dilationH, + int64_t dilationW) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + using iVec = vec::Vectorized; + // Pass I: init out lane + iVec index0_vec = iVec(id0 * input_height * input_width + ih0 * input_width + iw0); + fVec out_vec = fVec(-std::numeric_limits::infinity()); + int64_t d1 = 0; + for (; d1 < len; d1 += fVec::size()) { + index0_vec.store(index_ptr + d1); + out_vec.store(max_ptr + d1); + } + for (; d1 < size; d1++) { + ind[d1] = ih0 * input_width + iw0; + max_ptr[d1] = -std::numeric_limits::infinity(); + } + // Pass II: compute local max + for (int64_t id = id0; id < id1; id += dilationD) { + for (int64_t ih = ih0; ih < ih1; ih += dilationH) { + for (int64_t iw = iw0; iw < iw1; iw += dilationW) { + const scalar_t* in = input_data + (n * input_depth * input_height * input_width + + id * input_height * input_width + ih * input_width + iw) * channels; + + int64_t d2 = 0; + for (; d2 < len; d2 += Vec::size()) { + iVec index_ivec = iVec(id * input_height * input_width + ih * input_width + iw); + Vec val_bvec = Vec::loadu(in + d2); + auto [val_fvec0, val_fvec1] = convert_to_float(val_bvec); + + iVec maxindex_ivec0 = iVec::loadu(index_ptr + d2); + iVec maxindex_ivec1 = iVec::loadu(index_ptr + d2 + iVec::size()); + fVec maxval_fvec0 = fVec::loadu(max_ptr + d2); + fVec maxval_fvec1 = fVec::loadu(max_ptr + d2 + fVec::size()); + + // true = all ones, false = all zeros + fVec mask0 = (val_fvec0 > maxval_fvec0) | is_nan_vec(val_fvec0); + fVec mask1 = (val_fvec1 > maxval_fvec1) | is_nan_vec(val_fvec1); + iVec imask0 = vec::cast(mask0); + iVec imask1 = vec::cast(mask1); + + fVec max_fvec0 = fVec::blendv(maxval_fvec0, val_fvec0, mask0); + fVec max_fvec1 = fVec::blendv(maxval_fvec1, val_fvec1, mask1); + iVec ind_vec0 = iVec::blendv(maxindex_ivec0, index_ivec, imask0); + iVec ind_vec1 = iVec::blendv(maxindex_ivec1, index_ivec, imask1); + + max_fvec0.store(max_ptr + d2); + max_fvec1.store(max_ptr + d2 + fVec::size()); + // out_vec.store(out + d2); + ind_vec0.store(index_ptr + d2); + ind_vec1.store(index_ptr + d2 + iVec::size()); + } + for (; d2 < size; d2++) { + int64_t index = id * input_height * input_width + ih * input_width + iw; + opmath_t val = opmath_t(in[d2]); + int64_t maxindex = ind[d2]; + opmath_t maxval = max_ptr[d2]; + + bool mask = (val > maxval) || std::isnan(val); + max_ptr[d2] = mask ? val : maxval; + ind[d2] = mask ? index : maxindex; + } + } + } + } + // Convert max values from float to bfloat16/half + int64_t d3 = 0; + for (; d3 < len; d3 += Vec::size()) { + fVec max_fvec0 = fVec::loadu(max_ptr + d3); + fVec max_fvec1 = fVec::loadu(max_ptr + d3 + fVec::size()); + Vec max_bvec = convert_from_float(max_fvec0, max_fvec1); + max_bvec.store(out_data + d3); + } + for (; d3 < size; d3++) { + out_data[d3] = scalar_t(max_ptr[d3]); + } +} + +template +void cpu_max_pool( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef kWHD, + IntArrayRef dWHD, + IntArrayRef padWHD, + IntArrayRef dilWHD) { + size_t dims = is_3d ? 3 : 2; + TORCH_CHECK(kWHD.size() == dims && dWHD.size() == dims && padWHD.size() == dims && dilWHD.size() == dims, + "max pooling 2d/3d are not matched"); + int kW = kWHD[0]; + int kH = kWHD[1]; + int dW = dWHD[0]; + int dH = dWHD[1]; + int padW = padWHD[0]; + int padH = padWHD[1]; + int dilationW = dilWHD[0]; + int dilationH = dilWHD[1]; + + int kD = is_3d ? kWHD[dims - 1] : 1; + int dD = is_3d ? dWHD[dims - 1] : 1; + int padD = is_3d ? padWHD[dims - 1] : 0; + int dilationD = is_3d ? dilWHD[dims - 1] : 1; + + auto input = input_.contiguous(); + auto output = output_.contiguous(); + auto indices = indices_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t ndim = input.ndimension(); + // treat batch size and channels as one dimension + // + // MaxPool2d: + // ndim == 3: CHW + // ndim == 4: NCHW + // + // MaxPool3d: + // ndim == 4: CDHW + // ndim == 5: NCDHW + int64_t channels; + if (is_3d) { + channels = ndim == 4 ? input.size(0) : input.size(0) * input.size(1); + } else { + channels = ndim == 3 ? input.size(0) : input.size(0) * input.size(1); + } + int64_t input_depth = is_3d ? input.size(-3) : 1; + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_depth = is_3d ? output.size(-3) : 1; + int64_t output_height = output.size(-2); + int64_t output_width = output.size(-1); + + using opmath_t = at::opmath_type; + // parallel on dim N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (int64_t c = begin; c < end; c++) { + const scalar_t* input_ptr = input_data + c * input_depth * input_height * input_width; + scalar_t* output_ptr = output_data + c * output_depth * output_height * output_width; + int64_t* indices_ptr = indices_data + c * output_depth * output_height * output_width; + + for (int64_t od = 0; od < output_depth; od++) { + int64_t id0 = od * dD - padD; + int64_t id1 = std::min(id0 + (kD - 1) * dilationD + 1, input_depth); + while(id0 < 0) { id0 += dilationD; } + + for (int64_t oh = 0; oh < output_height; oh++) { + int64_t ih0 = oh * dH - padH; + int64_t ih1 = std::min(ih0 + (kH - 1) * dilationH + 1, input_height); + while(ih0 < 0) { ih0 += dilationH; } + + for (int64_t ow = 0; ow < output_width; ow++) { + int64_t iw0 = ow * dW - padW; + int64_t iw1 = std::min(iw0 + (kW - 1) * dilationW + 1, input_width); + while(iw0 < 0) { iw0 += dilationW; } + + // compute local max + int64_t maxindex = id0 * input_height * input_width + ih0 * input_width + iw0; + opmath_t maxval; + if (std::numeric_limits::has_infinity) { + maxval = -std::numeric_limits::infinity(); + } else { + maxval = std::numeric_limits::min(); + } + + for (int64_t id = id0; id < id1; id += dilationD) { + for (int64_t ih = ih0; ih < ih1; ih += dilationH) { + for (int64_t iw = iw0; iw < iw1; iw += dilationW) { + int64_t index = id * input_height * input_width + ih * input_width + iw; + opmath_t val = input_ptr[index]; + if ((val > maxval) || is_nan(static_cast(val))) { + maxval = val; + maxindex = index; + } + } + } + } + + // set output to local max and store location of max + int64_t i = od * output_height * output_width + oh * output_width + ow; + output_ptr[i] = scalar_t(maxval); + indices_ptr[i] = maxindex; + } + } + } + } + }); + + if (!output_.is_contiguous()) { + output_.copy_(output); + } + if (!indices_.is_contiguous()) { + indices_.copy_(indices); + } +} + +template +void cpu_max_pool_channels_last( + const Tensor& output_, + const Tensor& indices_, + const Tensor& input_, + IntArrayRef kWHD, + IntArrayRef dWHD, + IntArrayRef padWHD, + IntArrayRef dilWHD) { + size_t dims = is_3d ? 3 : 2; + TORCH_CHECK(kWHD.size() == dims && dWHD.size() == dims && padWHD.size() == dims && dilWHD.size() == dims, + "max pooling 2d/3d are not matched"); + int64_t ndim = input_.ndimension(); + // MaxPool2d: NHWC + // MaxPool3d: NDHWC + if (is_3d) { + TORCH_CHECK(ndim == 5, "max pooling 3d with channels last format supports tensors with 5 dims"); + } else { + TORCH_CHECK(ndim == 4, "max pooling 2d with channels last format supports tensors with 4 dims"); + } + + int kW = kWHD[0]; + int kH = kWHD[1]; + int dW = dWHD[0]; + int dH = dWHD[1]; + int padW = padWHD[0]; + int padH = padWHD[1]; + int dilationW = dilWHD[0]; + int dilationH = dilWHD[1]; + + int kD = is_3d ? kWHD[dims - 1] : 1; + int dD = is_3d ? dWHD[dims - 1] : 1; + int padD = is_3d ? padWHD[dims - 1] : 0; + int dilationD = is_3d ? dilWHD[dims - 1] : 1; + + auto memory_format = is_3d ? at::MemoryFormat::ChannelsLast3d : at::MemoryFormat::ChannelsLast; + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + auto indices_data = indices.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_depth = is_3d ? input.size(-3) : 1; + int64_t input_height = input.size(-2); + int64_t input_width = input.size(-1); + int64_t output_depth = is_3d ? output.size(-3) : 1; + int64_t output_height = output.size(-2); + int64_t output_width = output.size(-1); + + using opmath_t = at::opmath_type; + using Vec = vec::Vectorized; + using integer_t = vec::int_same_size_t; + // for the convenience of vectorization, use integer of the same size of scalar_t, + // e.g. int32_t for float, int64_t for double + // need to make sure doesn't overflow + TORCH_CHECK(input_depth * input_height * input_width <= std::numeric_limits::max()); + + // parallel on dim N, {D}, H, W + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + int64_t size = channels; + int64_t len = size - (size % Vec::size()); + // temp buffer holding index with integer_t + auto index_buffer = std::make_unique(len); + integer_t * index_ptr = index_buffer.get(); + // temp buffer holding max value with opmath_t + std::unique_ptr max_arr; + opmath_t* max_ptr = nullptr; + if (!std::is_same_v) { + max_arr = std::make_unique(size); + max_ptr = max_arr.get(); + } + + for (int64_t i = begin; i < end; i++) { + int64_t id0 = od * dD - padD; + int64_t ih0 = oh * dH - padH; + int64_t iw0 = ow * dW - padW; + int64_t id1 = std::min(id0 + (kD - 1) * dilationD + 1, input_depth); + int64_t ih1 = std::min(ih0 + (kH - 1) * dilationH + 1, input_height); + int64_t iw1 = std::min(iw0 + (kW - 1) * dilationW + 1, input_width); + while(id0 < 0) { id0 += dilationD; } + while(ih0 < 0) { ih0 += dilationH; } + while(iw0 < 0) { iw0 += dilationW; } + + scalar_t* out = output_data + i * channels; + int64_t* ind = indices_data + i * channels; + + compute_internal(input_data, out, max_ptr, index_ptr, ind, input_depth, input_height, input_width, channels, + n, len, size, id0, id1, ih0, ih1, iw0, iw1, + dilationD, dilationH, dilationW); + + // convert indice data type + vec::convert(index_buffer.get(), ind, len); + + // move on to next output index + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } + if (!indices_.is_contiguous(memory_format)) { + indices_.copy_(indices); + } +} + + +template +void cpu_max_pool_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + const Tensor& indices_) { + auto grad_output = grad_output_.contiguous(); + auto indices = indices_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + // treat batch size and channels as one dimension + // + // MaxPool2d: + // ndim == 3: CHW + // ndim == 4: NCHW + // + // MaxPool3d: + // ndim == 4: CDHW + // ndim == 5: NCDHW + int64_t ndim = grad_output.ndimension(); + int64_t channels; + if (is_3d) { + channels = ndim == 4 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + } else { + channels = ndim == 3 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + } + int64_t input_depth = is_3d ? grad_input.size(-3) : 1; + + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_depth = is_3d ? grad_output.size(-3) : 1; + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim of N, C + at::parallel_for(0, channels, 0, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + c * input_depth * input_height * input_width; + const scalar_t* grad_output_ptr = grad_output_data + c * output_depth * output_height * output_width; + const int64_t * indices_ptr = indices_data + c * output_depth * output_height * output_width; + + for (int64_t od = 0; od < output_depth; od++) { + for (int64_t oh = 0; oh < output_height; oh++) { + for (int64_t ow = 0; ow < output_width; ow++) { + // retrieve position of max + int64_t index = od * output_height * output_width + oh * output_width + ow; + int64_t maxindex = indices_ptr[index]; + if (maxindex != -1) { + // update gradient + grad_input_ptr[maxindex] += grad_output_ptr[index]; + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_max_pool_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + const Tensor& indices_) { + int64_t ndim = grad_output_.ndimension(); + if (is_3d) { + TORCH_CHECK(ndim == 5, "MaxPool3d backward with channels last format supports tensors with 5 dims."); + } else { + TORCH_CHECK(ndim == 4, "MaxPool2d backward with channels last format supports tensors with 4 dims."); + } + auto memory_format = is_3d ? at::MemoryFormat::ChannelsLast3d + : at::MemoryFormat::ChannelsLast; + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + auto indices = indices_.contiguous(memory_format); + + auto grad_input_data = grad_input.mutable_data_ptr(); + auto grad_output_data = grad_output.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + + // MaxPool2d: NHWC + // MaxPool3d: NDHWC + int64_t nbatch = grad_input.size(0); + int64_t channels = grad_input.size(1); + int64_t input_depth = is_3d ? grad_input.size(2) : 1; + int64_t input_height = grad_input.size(-2); + int64_t input_width = grad_input.size(-1); + int64_t output_depth = is_3d ? grad_output.size(2) : 1; + int64_t output_height = grad_output.size(-2); + int64_t output_width = grad_output.size(-1); + + // parallel on dim N + at::parallel_for(0, nbatch, 0, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + scalar_t* grad_input_ptr = grad_input_data + n * input_depth * input_height * input_width * channels; + const scalar_t* grad_output_ptr = grad_output_data + n * output_depth * output_height * output_width * channels; + const int64_t* indices_ptr = indices_data + n * output_depth * output_height * output_width * channels; + + for (int64_t od = 0; od < output_depth; od++) { + for (int64_t oh = 0; oh < output_height; oh++) { + for (int64_t ow = 0; ow < output_width; ow++) { + const scalar_t* gout = grad_output_ptr + (od * output_height * output_width + oh * output_width + ow) * channels; + const int64_t* ind = indices_ptr + (od * output_height * output_width + oh * output_width + ow) * channels; + // TODO: gcc vectorization + for (int64_t c = 0; c < channels; c++) { + int64_t maxindex = ind[c]; + if (maxindex != -1) { + grad_input_ptr[maxindex * channels + c] += gout[c]; + } + } + } + } + } + } + }); + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void max_pool2d_kernel_impl( + const Tensor& output, + const Tensor& indices, + const Tensor& input, + int kW, int kH, + int dW, int dH, + int padW, int padH, + int dilationW, int dilationH) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "max_pool2d", [&] { + cpu_max_pool(output, indices, input, {kW, kH}, {dW, dH}, {padW, padH}, {dilationW, dilationH}); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_ALL_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "max_pool2d_channels_last", [&] { + cpu_max_pool_channels_last(output, indices, input, {kW, kH}, {dW, dH}, {padW, padH}, {dilationW, dilationH}); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void max_pool3d_kernel_impl( + Tensor& output, + Tensor& indices, + const Tensor& input, + int kW, int kH, int kD, + int dW, int dH, int dD, + int padW, int padH, int padD, + int dilationW, int dilationH, int dilationD) { + if (input.ndimension() == 4) { + Tensor input_cl_check = input.unsqueeze(0); + // align with cuda: + // work around buggy behavior of suggest_memory_format here where + // suggested format of unsqueezed tensor is contiguous while it is + // really only contiguous in ChannelsLast3d + if ((!input_cl_check.is_contiguous()) && + input_cl_check.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + TORCH_CHECK(output.ndimension() == 4 && indices.ndimension() == 4); + DimVector out_sizes(output.sizes().begin(), output.sizes().end()); + out_sizes.insert(out_sizes.begin(), 1); + output.resize_(out_sizes, at::MemoryFormat::ChannelsLast3d); + DimVector indices_sizes(indices.sizes().begin(), indices.sizes().end()); + indices_sizes.insert(indices_sizes.begin(), 1); + indices.resize_(indices_sizes, at::MemoryFormat::ChannelsLast3d); + AT_DISPATCH_ALL_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "max_pool3d_channels_last", [&] { + cpu_max_pool_channels_last(output, indices, input_cl_check, + {kW, kH, kD}, {dW, dH, dD}, {padW, padH, padD}, {dilationW, dilationH, dilationD}); + }); + output.squeeze_(0); + indices.squeeze_(0); + return; + } + } + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "max_pool3d", [&] { + cpu_max_pool(output, indices, input, + {kW, kH, kD}, {dW, dH, dD}, {padW, padH, padD}, {dilationW, dilationH, dilationD}); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_ALL_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "max_pool3d_channels_last", [&] { + cpu_max_pool_channels_last(output, indices, input, + {kW, kH, kD}, {dW, dH, dD}, {padW, padH, padD}, {dilationW, dilationH, dilationD}); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } +} + +void max_pool2d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + const Tensor& indices) { + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "max_pool2d_backward", [&] { + cpu_max_pool_backward(grad_input, grad_output, indices); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "max_pool2d_backward_channels_last", [&] { + cpu_max_pool_backward_channels_last(grad_input, grad_output, indices); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void max_pool3d_backward_kernel_impl( + Tensor& grad_input, + const Tensor& grad_output, + const Tensor& indices) { + if (grad_output.ndimension() == 4) { + Tensor grad_output_cl_check = grad_output.unsqueeze(0); + // align with cuda: + // work around buggy behavior of suggest_memory_format here where + // suggested format of unsqueezed tensor is contiguous while it is + // really only contiguous in ChannelsLast3d + if ((!grad_output_cl_check.is_contiguous()) && + grad_output_cl_check.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + TORCH_CHECK(grad_input.ndimension() == 4 && indices.ndimension() == 4); + DimVector sizes(grad_input.sizes().begin(), grad_input.sizes().end()); + sizes.insert(sizes.begin(), 1); + grad_input.resize_(sizes, at::MemoryFormat::ChannelsLast3d); + auto _indices = indices.unsqueeze(0).contiguous(at::MemoryFormat::ChannelsLast3d); + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "max_pool3d_backward_channels_last", [&] { + cpu_max_pool_backward_channels_last(grad_input, grad_output_cl_check, _indices); + }); + grad_input.squeeze_(0); + return; + } + } + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "max_pool3d_backward", [&] { + cpu_max_pool_backward(grad_input, grad_output, indices); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, grad_output.scalar_type(), "max_pool3d_backward_channels_last", [&] { + cpu_max_pool_backward_channels_last(grad_input, grad_output, indices); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(max_pool2d_kernel, &max_pool2d_kernel_impl) +REGISTER_DISPATCH(max_pool2d_backward_kernel, &max_pool2d_backward_kernel_impl) +REGISTER_DISPATCH(max_pool3d_kernel, &max_pool3d_kernel_impl) +REGISTER_DISPATCH(max_pool3d_backward_kernel, &max_pool3d_backward_kernel_impl) +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxPooling.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxPooling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3f810320faf8d578d8900f21bf697b645e1a36c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxPooling.cpp @@ -0,0 +1,64 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +inline void max_pool1d_kernel( + scalar_t* C10_RESTRICT op, + const scalar_t* C10_RESTRICT ip, + const PoolingParams1D& p) { + for (const auto kj : c10::irange(p.KW)) { + int64_t oj = p.valid_output_start(kj); + int64_t oe = p.valid_output_end(kj); + int64_t ij = p.index(kj, oj); + for (; oj < oe; ++oj, ij += p.SJ) { + scalar_t val = ip[ij]; + bool update_max = std::isnan(val) || op[oj] < val; + op[oj] = update_max ? val : op[oj]; + } + } +} + +void max_pool1d_impl( + Tensor& output, + const Tensor& input, + const PoolingParams1D& p) { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, + ScalarType::Half, + input.scalar_type(), + "max_pool1d_impl", + [&] { + const Tensor in = input.contiguous(); + scalar_t* const OP = output.data_ptr(); + const scalar_t* const IP = in.const_data_ptr(); + + // Value used for padding + scalar_t FILL = std::numeric_limits::has_infinity + ? -std::numeric_limits::infinity() + : std::numeric_limits::lowest(); + + at::parallel_for(0, p.NB * p.NC, 0, [&](int64_t begin, int64_t end) { + for (const auto it : c10::irange(begin, end)) { + scalar_t* op = OP + it * p.OW; + const scalar_t* ip = IP + it * p.IW; + std::fill_n(op, p.OW, FILL); + max_pool1d_kernel(op, ip, p); + } + }); + }); +} + +} // namespace + +REGISTER_DISPATCH(max_pool1d_stub, &max_pool1d_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxUnpoolKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxUnpoolKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b51e619395e8e7ab8f7185661a294834e1e26e1a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxUnpoolKernel.cpp @@ -0,0 +1,278 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include + +#include + +namespace at::native { + +namespace { + +template +void cpu_max_unpool( + Tensor& output_, + const Tensor& input, + const Tensor& indices) { + auto output = output_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + auto output_data = output.data_ptr(); + + // NB: input tensor dimensions: + // MaxUnpool2d: + // dim = 3: CHW + // dim = 4: NCHW + // MaxUnpool3d: + // dim = 4: CDHW + // dim = 5: NCDHW + + int64_t numel = input.numel(); + int64_t ndim = input.ndimension(); + + // treat batch size and channels as one dimension + // and the feature map as another dimension + int64_t channels = 0; + [[maybe_unused]] int64_t output_depth = 0; + [[maybe_unused]] int64_t output_height = 0; + [[maybe_unused]] int64_t output_width = 0; + if constexpr (is_3d) { + TORCH_CHECK(ndim == 4 || ndim == 5, "MaxUnpool3d: expect input to be 4d or 5d tensor."); + channels = ndim == 4 ? input.size(0) : input.size(0) * input.size(1); + output_depth = output.size(-3); + output_height = output.size(-2); + output_width = output.size(-1); + } else { + TORCH_CHECK(ndim == 3 || ndim == 4, "MaxUnpool2d: expect input to be 3d or 4d tensor."); + channels = ndim == 3 ? input.size(0) : input.size(0) * input.size(1); + output_depth = 1; + output_height = output.size(-2); + output_width = output.size(-1); + } + int64_t input_image_size = numel / channels; + int64_t output_image_size = output.numel() / channels; + + std::optional optional_error_index; + + // parallel on dim N, C, D, H, W: [channels, input_image_size] + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t c = 0; + int64_t ip = 0; + data_index_init(begin, c, channels, ip, input_image_size); + + for (const auto i : c10::irange(begin, end)) { + scalar_t* output_ptr = output_data + c * output_image_size; + + int64_t maxp = indices_data[i]; + if (maxp < 0 || maxp >= output_image_size) { + optional_error_index = maxp; + std::atomic_thread_fence(std::memory_order_release); + } else { + output_ptr[maxp] = input_data[i]; + } + + // move on to next input index + data_index_step(c, channels, ip, input_image_size); + } + }); + + if (optional_error_index) { + if constexpr (is_3d) { + TORCH_CHECK(false, "Found an invalid max index: ", optional_error_index.value(), + " (output volumes are of size ", output_depth, + "x", output_height, "x", output_width, ")"); + } else { + TORCH_CHECK(false, "Found an invalid max index: ", optional_error_index.value(), + " (output volumes are of size ", output_height, + "x", output_width, ")"); + } + } + + if (!output_.is_contiguous()) { + output_.copy_(output); + } +} + +template +void cpu_max_unpool_channels_last( + Tensor& output_, + const Tensor& input, + const Tensor& indices) { + TORCH_CHECK(input.ndimension() == 4, + "max_unpool2d with channels last format supports tensors with 4 dims"); + auto memory_format = at::MemoryFormat::ChannelsLast; + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto indices_data = indices.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t input_height = input.size(2); + int64_t input_width = input.size(3); + int64_t output_height = output.size(2); + int64_t output_width = output.size(3); + int64_t input_image_size = input_height * input_width; + int64_t output_image_size = output_height * output_width; + + std::optional optional_error_index; + + // parallel on dim N, H, W + at::parallel_for(0, nbatch * input_image_size, 0, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t ip = 0; + data_index_init(begin, n, nbatch, ip, input_image_size); + + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + i * channels; + const int64_t* indices_ptr = indices_data + i * channels; + scalar_t* output_ptr = output_data + n * output_image_size * channels; + + // can't do scatter on avx2 (only available on avx512) + for (const auto c : c10::irange(channels)) { + int64_t maxp = indices_ptr[c]; + if (maxp < 0 || maxp >= output_image_size) { + optional_error_index = maxp; + std::atomic_thread_fence(std::memory_order_release); + } else { + output_ptr[maxp * channels + c] = input_ptr[c]; + } + } + + // move on to next input index + data_index_step(n, nbatch, ip, input_image_size); + } + }); + + if (optional_error_index) { + TORCH_CHECK(false, "Found an invalid max index: ", optional_error_index.value(), + " (output volumes are of size ", output_height, + "x", output_width, ")"); + } + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +void cpu_max_unpool_backward( + Tensor& grad_input_, + const Tensor& grad_output, + const Tensor& indices) { + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.data_ptr(); + auto indices_data = indices.data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + int64_t numel = grad_input.numel(); + int64_t ndim = grad_output.ndimension(); + + // treat batch size and channels as one dimension + // and the feature map as another dimension + int64_t channels = 0; + [[maybe_unused]] int64_t output_depth = 0; + [[maybe_unused]] int64_t output_height = 0; + [[maybe_unused]] int64_t output_width = 0; + if (is_3d) { + TORCH_CHECK(ndim == 4 || ndim == 5, "MaxUnpool3d_backward: expect grad_output to be 4d or 5d tensor."); + channels = ndim == 4 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + output_depth = grad_output.size(-3); + output_height = grad_output.size(-2); + output_width = grad_output.size(-1); + } else { + TORCH_CHECK(ndim == 3 || ndim == 4, "MaxUnpool2d_backward: expect grad_output to be 3d or 4d tensor."); + channels = ndim == 3 ? grad_output.size(0) : grad_output.size(0) * grad_output.size(1); + output_depth = 1; + output_height = grad_output.size(-2); + output_width = grad_output.size(-1); + } + int64_t input_image_size = numel / channels; + int64_t output_image_size = grad_output.numel() / channels; + + std::optional optional_error_index; + + // parallel on dim N, C, D, H, W + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t c = 0; + int64_t ip = 0; + data_index_init(begin, c, channels, ip, input_image_size); + + for (const auto i : c10::irange(begin, end)) { + scalar_t* grad_output_ptr = grad_output_data + c * output_image_size; + + int64_t maxp = indices_data[i]; + if (maxp < 0 || maxp >= output_image_size) { + optional_error_index = maxp; + std::atomic_thread_fence(std::memory_order_release); + } else { + grad_input_data[i] = grad_output_ptr[maxp]; + } + + // move on to next input index + data_index_step(c, channels, ip, input_image_size); + } + }); + + if (optional_error_index) { + if (is_3d) { + TORCH_CHECK(false, "invalid max index ", optional_error_index.value(), + ", odepth= ", output_depth, + ", owidth= ", output_width, + ", oheight= ", output_height); + } else { + TORCH_CHECK(false, "invalid max index ", optional_error_index.value(), + ", owidth= ", output_width, + ", oheight= ", output_height); + } + } + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +void max_unpool2d_kernel_impl( + Tensor& output, + const Tensor& input, + const Tensor& indices) { + switch(input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "max_unpool2d", [&] { + cpu_max_unpool(output, input, indices); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "max_unpool2d_channels_last", [&] { + cpu_max_unpool_channels_last(output, input, indices); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void max_unpool3d_kernel_impl( + Tensor& output, + const Tensor& input, + const Tensor& indices) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "max_unpool3d", [&] { + cpu_max_unpool(output, input, indices); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(max_unpool2d_kernel, &max_unpool2d_kernel_impl) +REGISTER_DISPATCH(max_unpool3d_kernel, &max_unpool3d_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxUnpoolKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxUnpoolKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..ca3d3aa0c6d8f71bc2223f5492b39f3f5e269e74 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MaxUnpoolKernel.h @@ -0,0 +1,14 @@ +#pragma once +#include + +namespace at { +class Tensor; + +namespace native { + +using max_unpooling_fn = void(*)(Tensor&, const Tensor&, const Tensor&); + +DECLARE_DISPATCH(max_unpooling_fn, max_unpool2d_kernel) +DECLARE_DISPATCH(max_unpooling_fn, max_unpool3d_kernel) + +}} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MultinomialKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MultinomialKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7f0b5a9f5b3f7e0b9e94caa227c99f593456d4e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/MultinomialKernel.cpp @@ -0,0 +1,229 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace at::native { +namespace { + +template +typename std::enable_if_t, void> +multinomial_with_replacement_apply( + Tensor& result, + const Tensor& self, + const int64_t n_sample, + std::optional generator) { + auto gen = get_generator_or_default( + generator, detail::getDefaultCPUGenerator()); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + + int64_t n_categories = self.size(-1); + int64_t n_dist = self.dim() > 1 ? self.size(-2) : 1; + + /* cumulative probability distribution vector */ + Tensor cum_dist = at::empty({n_categories}, self.options()); + + const scalar_t* const self_ptr = self.const_data_ptr(); + scalar_t* const cum_dist_ptr = cum_dist.data_ptr(); + int64_t* const result_ptr = result.data_ptr(); + + auto self_stride_0 = self.dim() > 1 ? self.stride(-2) : 0; + auto self_stride_1 = self.stride(-1); + + auto cum_dist_stride_0 = cum_dist.stride(0); + + auto result_dist_stride_0 = result.dim() > 1 ? result.stride(-2) : 0; + auto result_dist_stride_1 = result.stride(-1); + + for (const auto i : c10::irange(n_dist)) { + /* Get normalized cumulative distribution from prob distribution */ + scalar_t sum = 0; + for (const auto j : c10::irange(n_categories)) { + scalar_t val = self_ptr[i * self_stride_0 + j * self_stride_1]; + TORCH_CHECK( + val >= 0, + "invalid multinomial distribution (encountering probability entry < 0)"); +// NB: std::isfinite doesn't bode well with libc++ for half datatypes, +// so we manually cast it to a double and perform the check. +#if defined(_LIBCPP_VERSION) + TORCH_CHECK( + std::isfinite(static_cast(val)), + "invalid multinomial distribution (encountering probability entry = infinity or NaN)"); +#else + TORCH_CHECK( + std::isfinite(val), + "invalid multinomial distribution (encountering probability entry = infinity or NaN)"); +#endif + + sum += val; + cum_dist_ptr[j * cum_dist_stride_0] = sum; + } + + TORCH_CHECK( + sum > 0, + "invalid multinomial distribution (sum of probabilities <= 0)"); + + /* normalize cumulative probability distribution so that last val is 1 + i.e. doesn't assume original self row sums to one */ + if ((sum > 0) || ((sum < 1.00001) && (sum > 0.99999))) { + for (const auto j : c10::irange(n_categories)) { + cum_dist_ptr[j * cum_dist_stride_0] /= sum; + } + } + + for (const auto j : c10::irange(n_sample)) { + /* sample a probability mass from a uniform distribution */ + at::uniform_real_distribution uniform(0, 1); + double uniform_sample = uniform(gen); + /* Do a binary search for the slot in which the prob falls + ie cum_dist[row][slot-1] < uniform_prob < cum_distr[row][slot] */ + int64_t left_pointer = 0; + int64_t right_pointer = n_categories; + /* Make sure the last cumulative distribution bucket sums to 1 */ + cum_dist_ptr[(n_categories - 1) * cum_dist_stride_0] = 1; + + while (right_pointer - left_pointer > 0) { + int64_t mid_pointer = left_pointer + (right_pointer - left_pointer) / 2; + scalar_t cum_prob = cum_dist_ptr[mid_pointer * cum_dist_stride_0]; + if (cum_prob < uniform_sample) { + left_pointer = mid_pointer + 1; + } else { + right_pointer = mid_pointer; + } + } + auto sample_idx = left_pointer; + + /* store in result tensor (will be incremented for lua compat by wrapper) + */ + result_ptr[i * result_dist_stride_0 + j * result_dist_stride_1] = + sample_idx; + } + } +} + +template +typename std::enable_if_t, void> +multinomial_with_replacement_apply( + Tensor& result, + const Tensor& self, + const int64_t n_sample, + std::optional generator) { + auto gen = get_generator_or_default( + generator, detail::getDefaultCPUGenerator()); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + + int64_t n_categories = self.size(-1); + int64_t n_dist = self.dim() > 1 ? self.size(-2) : 1; + + /* cumulative probability distribution vector */ + Tensor cum_dist = at::empty({n_categories}, self.options().dtype(kFloat)); + + const scalar_t* const self_ptr = self.const_data_ptr(); + float* const cum_dist_ptr = cum_dist.data_ptr(); + int64_t* const result_ptr = result.data_ptr(); + + auto self_stride_0 = self.dim() > 1 ? self.stride(-2) : 0; + auto self_stride_1 = self.stride(-1); + + auto cum_dist_stride_0 = cum_dist.stride(0); + + auto result_dist_stride_0 = result.dim() > 1 ? result.stride(-2) : 0; + auto result_dist_stride_1 = result.stride(-1); + + for (const auto i : c10::irange(n_dist)) { + /* Get normalized cumulative distribution from prob distribution */ + float sum = 0; + for (const auto j : c10::irange(n_categories)) { + float val = self_ptr[i * self_stride_0 + j * self_stride_1]; + TORCH_CHECK( + val >= 0, + "invalid multinomial distribution (encountering probability entry < 0)"); +// NB: std::isfinite doesn't bode well with libc++ for half datatypes, +// so we manually cast it to a double and perform the check. +#if defined(_LIBCPP_VERSION) + TORCH_CHECK( + std::isfinite(static_cast(val)), + "invalid multinomial distribution (encountering probability entry = infinity or NaN)"); +#else + TORCH_CHECK( + std::isfinite(val), + "invalid multinomial distribution (encountering probability entry = infinity or NaN)"); +#endif + + sum += val; + cum_dist_ptr[j * cum_dist_stride_0] = sum; + } + + TORCH_CHECK( + sum > 0, + "invalid multinomial distribution (sum of probabilities <= 0)"); + + /* normalize cumulative probability distribution so that last val is 1 + i.e. doesn't assume original self row sums to one */ + if ((sum > 0) || ((sum < 1.00001) && (sum > 0.99999))) { + for (const auto j : c10::irange(n_categories)) { + cum_dist_ptr[j * cum_dist_stride_0] /= sum; + } + } + + for (const auto j : c10::irange(n_sample)) { + /* sample a probability mass from a uniform distribution */ + at::uniform_real_distribution uniform(0, 1); + double uniform_sample = uniform(gen); + /* Do a binary search for the slot in which the prob falls + ie cum_dist[row][slot-1] < uniform_prob < cum_distr[row][slot] */ + int64_t left_pointer = 0; + int64_t right_pointer = n_categories; + /* Make sure the last cumulative distribution bucket sums to 1 */ + cum_dist_ptr[(n_categories - 1) * cum_dist_stride_0] = 1; + + while (right_pointer - left_pointer > 0) { + int64_t mid_pointer = left_pointer + (right_pointer - left_pointer) / 2; + float cum_prob = cum_dist_ptr[mid_pointer * cum_dist_stride_0]; + if (cum_prob < uniform_sample) { + left_pointer = mid_pointer + 1; + } else { + right_pointer = mid_pointer; + } + } + auto sample_idx = left_pointer; + + /* store in result tensor (will be incremented for lua compat by wrapper) + */ + result_ptr[i * result_dist_stride_0 + j * result_dist_stride_1] = + sample_idx; + } + } +} + +void multinomial_with_replacement_kernel_impl( + Tensor& result, + const Tensor& self, + const int64_t n_sample, + std::optional gen) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, self.scalar_type(), "multinomial", [&] { + multinomial_with_replacement_apply( + result, self, n_sample, gen); + }); +} +} // namespace + +REGISTER_DISPATCH( + multinomial_with_replacement_stub, + &multinomial_with_replacement_kernel_impl) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/NativeMultiheadAttnKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/NativeMultiheadAttnKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51f4a053704a8c31e7b2cf2723175f9455b7731a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/NativeMultiheadAttnKernel.cpp @@ -0,0 +1,111 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void cpu_transform_bias_rescale_qkv( + scalar_t* q_k_v_data, + const scalar_t* qkv_data, + const scalar_t* qkv_bias_data, + int64_t B, + int64_t T, + int64_t D, + int64_t num_head) { + + int64_t dim_per_head = D / num_head; + + // shapes and strides: + // qkv : {B, T, 3, num_head, dim_per_head} + // qkv_bias : {3, num_head, dim_per_head} + // q_k_v : {3, B, num_head, T, dim_per_head} + // + int64_t i_strideB = T * 3 * D; + int64_t i_strideT = 3 * D; + int64_t o_stride = B * num_head * T * dim_per_head; + + // inv_sqrt_dim_per_head in accumulate type + using acc_t = at::opmath_type; + using Vec = vec::Vectorized; + const acc_t s = 1.0 / std::sqrt(static_cast(dim_per_head)); + + // parallel on {B, num_head, T} + int64_t grain_size = std::max(at::internal::GRAIN_SIZE / (3 * dim_per_head), (int64_t)1); + at::parallel_for(0, B * num_head * T, grain_size, [&](int64_t begin, int64_t end) { + int64_t b{0}, nh{0}, t{0}; + data_index_init(begin, b, B, nh, num_head, t, T); + + for (const auto i : c10::irange(begin, end)) { + const scalar_t* q_in_ptr = qkv_data + b * i_strideB + t * i_strideT + 0 * D + nh * dim_per_head; + const scalar_t* k_in_ptr = qkv_data + b * i_strideB + t * i_strideT + 1 * D + nh * dim_per_head; + const scalar_t* v_in_ptr = qkv_data + b * i_strideB + t * i_strideT + 2 * D + nh * dim_per_head; + + const scalar_t* q_bias_ptr = qkv_bias_data + 0 * D + nh * dim_per_head; + const scalar_t* k_bias_ptr = qkv_bias_data + 1 * D + nh * dim_per_head; + const scalar_t* v_bias_ptr = qkv_bias_data + 2 * D + nh * dim_per_head; + + // we can use global index i here for output + scalar_t* q_out_ptr = q_k_v_data + 0 * o_stride + i * dim_per_head; + scalar_t* k_out_ptr = q_k_v_data + 1 * o_stride + i * dim_per_head; + scalar_t* v_out_ptr = q_k_v_data + 2 * o_stride + i * dim_per_head; + + // q = (q + bias) * inv_sqrt_dim_per_head + vec::map2( + [s](Vec q, Vec q_bias) { return (q + q_bias) * Vec(s); }, + q_out_ptr, q_in_ptr, q_bias_ptr, dim_per_head); + + // k = k + bias + vec::map2([](Vec k, Vec k_bias) { return k + k_bias; }, + k_out_ptr, k_in_ptr, k_bias_ptr, dim_per_head); + + // v = v + bias + vec::map2([](Vec v, Vec v_bias) { return v + v_bias; }, + v_out_ptr, v_in_ptr, v_bias_ptr, dim_per_head); + + // move to the next index + data_index_step(b, B, nh, num_head, t, T); + } + }); +} + +void transform_bias_rescale_qkv_kernel_impl( + at::ScalarType type, + void* _q_k_v, + const void* _qkv, + const void* _qkv_bias, + int64_t B, + int64_t T, + int64_t D, + int64_t num_head) { + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, type, "transform_bias_rescale_qkv", [&] { + scalar_t* q_k_v = static_cast(_q_k_v); + const scalar_t* qkv = static_cast(_qkv); + const scalar_t* qkv_bias = static_cast(_qkv_bias); + cpu_transform_bias_rescale_qkv( + q_k_v, + qkv, + qkv_bias, + B, + T, + D, + num_head); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(transform_bias_rescale_qkv_stub, &transform_bias_rescale_qkv_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PaddingKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PaddingKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2a908869c9eb5b54ec43501542d069b61eb67ff --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PaddingKernel.cpp @@ -0,0 +1,729 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +struct PaddingParams { + int ndim; + int64_t nbatch; + int64_t channels; + + // use vectorized logic on width when output index is in [pad, input_width + pad), + // applies only to Channels First format when pad_l and pad_r are both positive. + bool is_padding_positive_width; + + c10::SmallVector ishape; + c10::SmallVector oshape; + c10::SmallVector pads; + c10::SmallVector offsets; + + PaddingParams(const Tensor& input, const Tensor& output, IntArrayRef padding) { + ndim = padding.size() / 2; + + bool is_batch = input.dim() == ndim + 2; + nbatch = is_batch ? input.size(0) : 1; + channels = is_batch ? input.size(1) : input.size(0); + + is_padding_positive_width = padding[0] >= 0 && padding[1] >=0; + + // handle sizes with batch-mode and non-batch-mode + int ind = is_batch ? 2 : 1; + for (const auto d : c10::irange(ndim)) { + ishape.emplace_back(input.size(ind + d)); + oshape.emplace_back(output.size(ind + d)); + } + + // padding is organized in order of: + // { left, right, top, bottom, front, back } + // + // re-organize into order of: + // { depth, height, width} + // + if (ndim == 1) { + pads.emplace_back(padding[0]); + } else if (ndim == 2) { + pads.emplace_back(padding[2]); + pads.emplace_back(padding[0]); + } else { + pads.emplace_back(padding[4]); + pads.emplace_back(padding[2]); + pads.emplace_back(padding[0]); + } + for (const auto d : c10::irange(ndim)) { + int64_t pad = pads[d]; + auto i_start = std::max(int64_t(0), -pad); + auto o_start = std::max(int64_t(0), pad); + offsets.emplace_back(i_start - o_start); + } + } +}; + +struct ReflectionPad { + static int64_t index(int64_t j, int64_t size, int64_t pad, int64_t offset) { + int64_t i; + if (j < pad) { + i = pad * 2 - j; + } else if (j >= pad && j < size + pad) { + i = j; + } else { + i = (size + pad - 1) * 2 - j; + } + return i + offset; + } +}; + +struct ReplicationPad { + static int64_t index(int64_t j, int64_t size, int64_t pad, int64_t offset) { + int64_t i; + if (j < pad) { + i = pad; + } else if (j >= pad && j < size + pad) { + i = j; + } else { + i = size + pad - 1; + } + return i + offset; + } +}; + +template +inline void copy_stub(scalar_t* out, const scalar_t* in, int64_t size) { + using Vec = Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec in_vec = Vec::loadu(in + d); + in_vec.store(out + d); + } + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (; d < size; d++) { + out[d] = in[d]; + } +} + +template +inline void add_stub(scalar_t* grad_in, const scalar_t* grad_out, int64_t size) { + using Vec = Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec grad_vec = Vec::loadu(grad_in + d) + Vec::loadu(grad_out + d); + grad_vec.store(grad_in + d); + } + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (; d < size; d++) { + grad_in[d] += grad_out[d]; + } +} + +template +void cpu_padding( + const Tensor& output_, + const Tensor& input_, + PaddingParams& p) { + + auto input = input_.contiguous(); + auto output = output_.contiguous(); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + // fold nbatch and channels into single dimension for channels first. + int64_t channels = p.nbatch * p.channels; + + int ndim = p.ndim; + int64_t input_depth = ndim == 3 ? p.ishape[ndim - 3] : 1; + int64_t input_height = ndim >=2 ? p.ishape[ndim - 2] : 1; + int64_t input_width = p.ishape[ndim - 1]; + int64_t output_depth = ndim == 3 ? p.oshape[ndim - 3] : 1; + int64_t output_height = ndim >= 2 ? p.oshape[ndim - 2] : 1; + int64_t output_width = p.oshape[ndim - 1]; + int64_t pad_d = ndim == 3 ? p.pads[ndim - 3] : 0; + int64_t pad_h = ndim >= 2 ? p.pads[ndim - 2] : 0; + int64_t pad_w = p.pads[ndim - 1]; + int64_t offset_d = ndim == 3 ? p.offsets[ndim - 3] : 0; + int64_t offset_h = ndim >= 2 ? p.offsets[ndim - 2] : 0; + int64_t offset_w = p.offsets[ndim - 1]; + + // do vectorized copy when output is overlapped with input on W, + // only applies to positive padding + auto loop = [=](scalar_t* out, const scalar_t* in, bool positive_padding) { + if (positive_padding) { + for (const auto ow : c10::irange(pad_w)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + out[ow] = in[iw]; + } + copy_stub(out + pad_w, in, input_width); + for (const auto ow : c10::irange(input_width + pad_w, output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + out[ow] = in[iw]; + } + } else { + for (const auto ow : c10::irange(output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + out[ow] = in[iw]; + } + } + }; + + if (ndim == 1) { + // parallel on N,C,W + at::parallel_for(0, channels * output_width, 1, [&](int64_t begin, int64_t end) { + int64_t c{0}, ow{0}; + data_index_init(begin, c, channels, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + output_data[i] = input_data[c * input_width + iw]; + data_index_step(c, channels, ow, output_width); + } + }); + } else if (ndim == 2) { + // parallel on N,C,H, vectorize on W + at::parallel_for(0, channels * output_height, 1, [&](int64_t begin, int64_t end) { + int64_t c{0}, oh{0}; + data_index_init(begin, c, channels, oh, output_height); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + scalar_t* output_ptr = output_data + i * output_width; + const scalar_t* input_ptr = input_data + c * input_height * input_width + ih * input_width; + + loop(output_ptr, input_ptr, p.is_padding_positive_width); + data_index_step(c, channels, oh, output_height); + } + }); + } else if (ndim == 3) { + // parallel on N,C,D,H, vectorize on W + at::parallel_for(0, channels * output_depth * output_height, 1, [&](int64_t begin, int64_t end) { + int64_t c{0}, od{0}, oh{0}; + data_index_init(begin, c, channels, od, output_depth, oh, output_height); + + for (const auto i : c10::irange(begin, end)) { + int64_t id = PaddingType::index(od, input_depth, pad_d, offset_d); + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + scalar_t* output_ptr = output_data + i * output_width; + const scalar_t* input_ptr = input_data + c * input_depth * input_height * input_width + + id * input_height * input_width + ih * input_width; + + loop(output_ptr, input_ptr, p.is_padding_positive_width); + data_index_step(c, channels, od, output_depth, oh, output_height); + } + }); + } else { + TORCH_INTERNAL_ASSERT(false, "expect input dim to be 1d, 2d or 3d."); + } + + if (!output_.is_contiguous()) { + output_.copy_(output); + } +} + +template +void cpu_padding_channels_last( + const Tensor& output_, + const Tensor& input_, + PaddingParams& p) { + + auto memory_format = p.ndim == 2 + ? at::MemoryFormat::ChannelsLast + : at::MemoryFormat::ChannelsLast3d; + + auto input = input_.contiguous(memory_format); + auto output = output_.contiguous(memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = p.nbatch; + int64_t channels = p.channels; + + int ndim = p.ndim; + int64_t input_depth = ndim == 3 ? p.ishape[ndim - 3] : 1; + int64_t input_height = ndim >=2 ? p.ishape[ndim - 2] : 1; + int64_t input_width = p.ishape[ndim - 1]; + int64_t output_depth = ndim == 3 ? p.oshape[ndim - 3] : 1; + int64_t output_height = ndim >= 2 ? p.oshape[ndim - 2] : 1; + int64_t output_width = p.oshape[ndim - 1]; + int64_t pad_d = ndim == 3 ? p.pads[ndim - 3] : 0; + int64_t pad_h = ndim >= 2 ? p.pads[ndim - 2] : 0; + int64_t pad_w = p.pads[ndim - 1]; + int64_t offset_d = ndim == 3 ? p.offsets[ndim - 3] : 0; + int64_t offset_h = ndim >= 2 ? p.offsets[ndim - 2] : 0; + int64_t offset_w = p.offsets[ndim - 1]; + + if (ndim == 2) { + // parallel on N,H,W, vectorize on C + at::parallel_for(0, nbatch * output_height * output_width, 1, [&](int64_t begin, int64_t end) { + int64_t n{0}, oh{0}, ow{0}; + data_index_init(begin, n, nbatch, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + + scalar_t* output_ptr = output_data + i * channels; + const scalar_t* input_ptr = input_data + (n * input_height * input_width + ih * input_width + iw) * channels; + copy_stub(output_ptr, input_ptr, channels); + + data_index_step(n, nbatch, oh, output_height, ow, output_width); + } + }); + } else if (ndim == 3) { + // parallel on N,D,H,W, vectorize on C + at::parallel_for(0, nbatch * output_depth * output_height * output_width, 1, [&](int64_t begin, int64_t end) { + int64_t n{0}, od{0}, oh{0}, ow{0}; + data_index_init(begin, n, nbatch, od, output_depth, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t id = PaddingType::index(od, input_depth, pad_d, offset_d); + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + + scalar_t* output_ptr = output_data + i * channels; + const scalar_t* input_ptr = input_data + (n * input_depth * input_height * input_width + + id * input_height * input_width + ih * input_width + iw) * channels; + copy_stub(output_ptr, input_ptr, channels); + + data_index_step(n, nbatch, od, output_depth, oh, output_height, ow, output_width); + } + }); + } else { + TORCH_INTERNAL_ASSERT(false, "expect input dim to be 2d or 3d."); + } + + if (!output_.is_contiguous(memory_format)) { + output_.copy_(output); + } +} + +template +void cpu_padding_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + PaddingParams& p) { + + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.data_ptr(); + + // fold nbatch and channels into single dimension for channels first. + int64_t channels = p.nbatch * p.channels; + + int ndim = p.ndim; + int64_t input_depth = ndim == 3 ? p.ishape[ndim - 3] : 1; + int64_t input_height = ndim >=2 ? p.ishape[ndim - 2] : 1; + int64_t input_width = p.ishape[ndim - 1]; + int64_t output_depth = ndim == 3 ? p.oshape[ndim - 3] : 1; + int64_t output_height = ndim >= 2 ? p.oshape[ndim - 2] : 1; + int64_t output_width = p.oshape[ndim - 1]; + int64_t pad_d = ndim == 3 ? p.pads[ndim - 3] : 0; + int64_t pad_h = ndim >= 2 ? p.pads[ndim - 2] : 0; + int64_t pad_w = p.pads[ndim - 1]; + int64_t offset_d = ndim == 3 ? p.offsets[ndim - 3] : 0; + int64_t offset_h = ndim >= 2 ? p.offsets[ndim - 2] : 0; + int64_t offset_w = p.offsets[ndim - 1]; + + if (ndim == 1) { + // parallel on N,C, sequential on W + at::parallel_for(0, channels, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + for (const auto ow : c10::irange(output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + grad_input_data[c * input_width + iw] += grad_output_data[c * output_width + ow]; + } + } + }); + } else if (ndim == 2) { + // parallel on N,C, sequential on H,W + at::parallel_for(0, channels, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + const scalar_t* grad_output_ptr = grad_output_data + c * output_height * output_width; + scalar_t* grad_input_ptr = grad_input_data + c * input_height * input_width; + + for (const auto oh : c10::irange(output_height)) { + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + grad_input_ptr[ih * input_width + iw] += grad_output_ptr[oh * output_width + ow]; + } + } + } + }); + } else if (p.ndim == 3) { + // parallel on N,C, sequential on D,H,W + at::parallel_for(0, channels, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + const scalar_t* grad_output_ptr = grad_output_data + c * output_depth *output_height * output_width; + scalar_t* grad_input_ptr = grad_input_data + c * input_depth * input_height * input_width; + + for (const auto od : c10::irange(output_depth)) { + int64_t id = PaddingType::index(od, input_depth, pad_d, offset_d); + for (const auto oh : c10::irange(output_height)) { + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + grad_input_ptr[id * input_height * input_width + ih * input_width + iw] += + grad_output_ptr[od * output_height * output_width + oh * output_width + ow]; + } + } + } + } + }); + } else { + TORCH_INTERNAL_ASSERT(false, "expect input dim to be 1d, 2d, or 3d."); + } + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_padding_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + PaddingParams& p) { + + auto memory_format = p.ndim == 2 + ? at::MemoryFormat::ChannelsLast + : at::MemoryFormat::ChannelsLast3d; + + auto grad_input = grad_input_.contiguous(memory_format); + auto grad_output = grad_output_.contiguous(memory_format); + + auto grad_input_data = grad_input.data_ptr(); + auto grad_output_data = grad_output.const_data_ptr(); + + int64_t nbatch = p.nbatch; + int64_t channels = p.channels; + + int ndim = p.ndim; + int64_t input_depth = ndim == 3 ? p.ishape[ndim - 3] : 1; + int64_t input_height = ndim >=2 ? p.ishape[ndim - 2] : 1; + int64_t input_width = p.ishape[ndim - 1]; + int64_t output_depth = ndim == 3 ? p.oshape[ndim - 3] : 1; + int64_t output_height = ndim >= 2 ? p.oshape[ndim - 2] : 1; + int64_t output_width = p.oshape[ndim - 1]; + int64_t pad_d = ndim == 3 ? p.pads[ndim - 3] : 0; + int64_t pad_h = ndim >= 2 ? p.pads[ndim - 2] : 0; + int64_t pad_w = p.pads[ndim - 1]; + int64_t offset_d = ndim == 3 ? p.offsets[ndim - 3] : 0; + int64_t offset_h = ndim >= 2 ? p.offsets[ndim - 2] : 0; + int64_t offset_w = p.offsets[ndim - 1]; + + if (ndim == 2) { + // parallel on N, sequential on H,W, vectorize on C + at::parallel_for(0, nbatch, 1, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + for (const auto oh : c10::irange(output_height)) { + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + scalar_t* grad_input_ptr = grad_input_data + + (n * input_height * input_width + ih * input_width + iw) * channels; + const scalar_t* grad_output_ptr = grad_output_data + + (n * output_height * output_width + oh * output_width + ow) * channels; + add_stub(grad_input_ptr, grad_output_ptr, channels); + } + } + } + }); + } else if (ndim == 3) { + // parallel on N, sequential on D,H,W, vectorize on C + at::parallel_for(0, nbatch, 1, [&](int64_t begin, int64_t end) { + for (const auto n : c10::irange(begin, end)) { + for (const auto od : c10::irange(output_depth)) { + int64_t id = PaddingType::index(od, input_depth, pad_d, offset_d); + for (const auto oh : c10::irange(output_height)) { + int64_t ih = PaddingType::index(oh, input_height, pad_h, offset_h); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = PaddingType::index(ow, input_width, pad_w, offset_w); + scalar_t* grad_input_ptr = grad_input_data + + (n * input_depth * input_height * input_width + id * input_height * input_width + + ih * input_width + iw) * channels; + const scalar_t* grad_output_ptr = grad_output_data + + (n * output_depth * output_height * output_width + od * output_height * output_width + + oh * output_width + ow) * channels; + add_stub(grad_input_ptr, grad_output_ptr, channels); + } + } + } + } + }); + } else { + TORCH_INTERNAL_ASSERT(false, "expect input dim to be 2d or 3d."); + } + + if (!grad_input_.is_contiguous(memory_format)) { + grad_input_.copy_(grad_input); + } +} + +// non-batch mode 4d input will be considered as Contiguous in format of CDHW +at::MemoryFormat padding_memory_format_3d(const Tensor& input) { + return input.dim() == 4 ? at::MemoryFormat::Contiguous : input.suggest_memory_format(); +} + +// reflection padding +void reflection_pad1d_kernel_impl(const Tensor& output, const Tensor& input, IntArrayRef padding) { + PaddingParams param{input, output, padding}; + if (input.is_quantized()) { + AT_DISPATCH_QINT_TYPES(input.scalar_type(), "qreflection_pad1d", [&] { + cpu_padding(output, input, param); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "reflection_pad1d", [&] { + cpu_padding(output, input, param); + }); + } +} + +void reflection_pad1d_backward_kernel_impl( + const Tensor& grad_input, const Tensor& grad_output, IntArrayRef padding) { + PaddingParams param{grad_input, grad_output, padding}; + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "reflection_pad1d_backward", [&] { + cpu_padding_backward(grad_input, grad_output, param); + }); +} + +void reflection_pad2d_kernel_impl(const Tensor& output, const Tensor& input, IntArrayRef padding) { + PaddingParams param{input, output, padding}; + if (input.is_quantized()) { + // original quantized impl doesn't have channels last support, + // if this is intended, make a switch here. + AT_DISPATCH_QINT_TYPES(input.scalar_type(), "qreflection_pad2d", [&] { + cpu_padding(output, input, param); + }); + } else { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "reflection_pad2d", [&] { + cpu_padding(output, input, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "reflection_pad2d_channels_last", [&]{ + cpu_padding_channels_last(output, input, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + } +} + +void reflection_pad2d_backward_kernel_impl( + const Tensor& grad_input, const Tensor& grad_output, IntArrayRef padding) { + PaddingParams param{grad_input, grad_output, padding}; + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "reflection_pad2d_backward", [&] { + cpu_padding_backward(grad_input, grad_output, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "reflection_pad2d_backward_channels_last", [&]{ + cpu_padding_backward_channels_last(grad_input, grad_output, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void reflection_pad3d_kernel_impl(const Tensor& output, const Tensor& input, IntArrayRef padding) { + PaddingParams param{input, output, padding}; + switch (padding_memory_format_3d(input)) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kHalf, kBFloat16, input.scalar_type(), + "reflection_pad3d", [&] { + cpu_padding(output, input, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kHalf, kBFloat16, input.scalar_type(), + "reflection_pad3d_channels_last", [&]{ + cpu_padding_channels_last(output, input, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } +} + +void reflection_pad3d_backward_kernel_impl( + const Tensor& grad_input, const Tensor& grad_output, IntArrayRef padding) { + PaddingParams param{grad_input, grad_output, padding}; + switch (padding_memory_format_3d(grad_output)) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, grad_output.scalar_type(), + "reflection_pad3d_backward", [&] { + cpu_padding_backward(grad_input, grad_output, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, grad_output.scalar_type(), + "reflection_pad3d_backward_channels_last", [&]{ + cpu_padding_backward_channels_last(grad_input, grad_output, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } +} + +// replication padding +void replication_pad1d_kernel_impl(const Tensor& output, const Tensor& input, IntArrayRef padding) { + PaddingParams param{input, output, padding}; + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf,input.scalar_type(), + "replication_pad1d", [&] { + cpu_padding(output, input, param); + }); +} + +void replication_pad1d_backward_kernel_impl( + const Tensor& grad_input, const Tensor& grad_output, IntArrayRef padding) { + PaddingParams param{grad_input, grad_output, padding}; + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "replication_pad1d_backward", [&] { + cpu_padding_backward(grad_input, grad_output, param); + }); +} + +void replication_pad2d_kernel_impl(const Tensor& output, const Tensor& input, IntArrayRef padding) { + PaddingParams param{input, output, padding}; + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "replication_pad2d", [&] { + cpu_padding(output, input, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "replication_pad2d_channels_last", [&]{ + cpu_padding_channels_last(output, input, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void replication_pad2d_backward_kernel_impl( + const Tensor& grad_input, const Tensor& grad_output, IntArrayRef padding) { + PaddingParams param{grad_input, grad_output, padding}; + switch (grad_output.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "replication_pad2d_backward", [&] { + cpu_padding_backward(grad_input, grad_output, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "replication_pad2d_backward_channels_last", [&]{ + cpu_padding_backward_channels_last(grad_input, grad_output, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void replication_pad3d_kernel_impl(const Tensor& output, const Tensor& input, IntArrayRef padding) { + PaddingParams param{input, output, padding}; + switch (padding_memory_format_3d(input)) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "replication_pad3d", [&] { + cpu_padding(output, input, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, input.scalar_type(), + "replication_pad3d_channels_last", [&]{ + cpu_padding_channels_last(output, input, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } +} + +void replication_pad3d_backward_kernel_impl( + const Tensor& grad_input, const Tensor& grad_output, IntArrayRef padding) { + PaddingParams param{grad_input, grad_output, padding}; + switch (padding_memory_format_3d(grad_output)) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "replication_pad3d_backward", [&] { + cpu_padding_backward(grad_input, grad_output, param); + }); + break; + } + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), + "replication_pad3d_backward_channels_last", [&]{ + cpu_padding_backward_channels_last(grad_input, grad_output, param); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast3d, Contiguous"); + } +} + +} // anonymous namespace + +// reflection padding +REGISTER_DISPATCH(reflection_pad1d_kernel, &reflection_pad1d_kernel_impl) +REGISTER_DISPATCH(reflection_pad1d_backward_kernel, &reflection_pad1d_backward_kernel_impl) +REGISTER_DISPATCH(reflection_pad2d_kernel, &reflection_pad2d_kernel_impl) +REGISTER_DISPATCH(reflection_pad2d_backward_kernel, &reflection_pad2d_backward_kernel_impl) +REGISTER_DISPATCH(reflection_pad3d_kernel, &reflection_pad3d_kernel_impl) +REGISTER_DISPATCH(reflection_pad3d_backward_kernel, &reflection_pad3d_backward_kernel_impl) + +// replication padding +REGISTER_DISPATCH(replication_pad1d_kernel, &replication_pad1d_kernel_impl) +REGISTER_DISPATCH(replication_pad1d_backward_kernel, &replication_pad1d_backward_kernel_impl) +REGISTER_DISPATCH(replication_pad2d_kernel, &replication_pad2d_kernel_impl) +REGISTER_DISPATCH(replication_pad2d_backward_kernel, &replication_pad2d_backward_kernel_impl) +REGISTER_DISPATCH(replication_pad3d_kernel, &replication_pad3d_kernel_impl) +REGISTER_DISPATCH(replication_pad3d_backward_kernel, &replication_pad3d_backward_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PixelShuffleKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PixelShuffleKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6df75206fb5469174595aa02cbc7bf7d2127cd2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PixelShuffleKernel.cpp @@ -0,0 +1,253 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void cpu_pixel_shuffle( + TensorBase& output, + const TensorBase& input, + int64_t upscale_factor) { + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + // [(B1...Bn), C, H, W] => [N, C, H, W] + int64_t channels = input.size(-3); + int64_t height = input.size(-2); + int64_t width = input.size(-1); + int64_t sub_channels = channels / (upscale_factor * upscale_factor); + int64_t numel = input.numel(); + int64_t nbatch = numel / (channels * height * width); + int64_t S = upscale_factor; + + // input strides + int64_t stride_n = channels * height * width; + int64_t stride_c = S * S * height * width; + int64_t stride_s1 = S * height * width; + int64_t stride_s2 = height * width; + int64_t stride_h = width; + + // input tensor shape of [n, c, s1, s2, h, w] + // output tensor shape of [n, c, h, s1, w, s2] + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t n{0}, c{0}, h{0}, s1{0}, w{0}, s2{0}; + data_index_init(begin, n, nbatch, c, sub_channels, h, height, s1, S, w, width, s2, S); + + for (const auto i : c10::irange(begin, end)) { + int64_t input_offset = n * stride_n + c * stride_c + s1 * stride_s1 + + s2 * stride_s2 + h * stride_h + w; + output_data[i] = c10::load(&input_data[input_offset]); + + data_index_step(n, nbatch, c, sub_channels, h, height, s1, S, w, width, s2, S); + } + }); +} + +template +void cpu_pixel_shuffle_channels_last( + TensorBase& output, + const TensorBase& input, + int64_t upscale_factor) { + TORCH_CHECK(input.ndimension() == 4, + "pixel shuffle with channels last format supports tensors with 4 dims"); + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t channels = input.size(1); + int64_t height = input.size(2); + int64_t width = input.size(3); + int64_t sub_channels = channels / (upscale_factor * upscale_factor); + int64_t S = upscale_factor; + + // input tensor shape of [n, h, w, c, s1, s2] + // output tensor shape of [n, h, s1, w, s2, c] + using Vec = vec::Vectorized; + at::parallel_for(0, nbatch * height, 0, [&](int64_t begin, int64_t end) { + // temp buffer holding each channel lane + auto buffer = std::make_unique(channels); + scalar_t* buffer_ptr = buffer.get(); + + int64_t n{0}, h{0}; + data_index_init(begin, n, nbatch, h, height); + for (const auto i : c10::irange(begin, end)) { + for (const auto w : c10::irange(width)) { + const scalar_t* input_ptr = input_data + n * height * width * channels + h * width * channels + w * channels; + + // step 1: transpose each channel lane + // from: [c, s1*s2] + // to: [s1*s2, c] + utils::transpose(sub_channels, S * S, input_ptr, S * S, buffer_ptr, sub_channels); + + // step 2: copy from temp buffer to output + for (const auto s1 : c10::irange(S)) { + scalar_t* x_ptr = buffer_ptr + s1 * S * sub_channels; + scalar_t* y_ptr = output_data + i * width * channels + s1 * width * S * sub_channels + w * S * sub_channels; + + int64_t size = S * sub_channels; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec data_vec = Vec::loadu(x_ptr + d); + data_vec.store(y_ptr + d); + } + for (; d < size; d++) { + y_ptr[d] = x_ptr[d]; + } + } + } + + data_index_step(n, nbatch, h, height); + } + }); +} + +template +void cpu_pixel_unshuffle( + TensorBase& output, + const TensorBase& input, + int64_t downscale_factor) { + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + // [(B1...Bn), C, H, W] => [N, C, H, W] + int64_t sub_channels = input.size(-3); + int64_t height = input.size(-2) / downscale_factor; + int64_t width = input.size(-1) / downscale_factor; + int64_t channels = sub_channels * downscale_factor * downscale_factor; + int64_t numel = input.numel(); + int64_t nbatch = numel / (channels * height * width); + int64_t S = downscale_factor; + + // input strides + int64_t stride_n = channels * height * width; + int64_t stride_c = height * S * width * S; + int64_t stride_h = S * width * S; + int64_t stride_s1 = width * S; + int64_t stride_w = S; + int64_t stride_s2 = 1; + + // input tensor shape of [n, c, h, s1, w, s2] + // output tensor shape of [n, c, s1, s2, h, w] + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t n{0}, c{0}, s1{0}, s2{0}, h{0}, w{0}; + data_index_init(begin, n, nbatch, c, sub_channels, s1, S, s2, S, h, height, w, width); + + for (const auto i : c10::irange(begin, end)) { + int64_t input_offset = n * stride_n + c * stride_c + h * stride_h + + s1 * stride_s1 + w * stride_w + s2 * stride_s2; + output_data[i] = c10::load(&input_data[input_offset]); + + data_index_step(n, nbatch, c, sub_channels, s1, S, s2, S, h, height, w, width); + } + }); +} + +template +void cpu_pixel_unshuffle_channels_last( + TensorBase& output, + const TensorBase& input, + int64_t downscale_factor) { + TORCH_CHECK(input.ndimension() == 4, + "pixel unshuffle with channels last format supports tensors with 4 dims"); + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t nbatch = input.size(0); + int64_t sub_channels = input.size(1); + int64_t height = input.size(2) / downscale_factor; + int64_t width = input.size(3) / downscale_factor; + int64_t channels = sub_channels * downscale_factor * downscale_factor; + int64_t numel = input.numel(); + int64_t S = downscale_factor; + + // input strides + int64_t stride_n = height * width * channels; + int64_t stride_h = S * width * S * sub_channels; + int64_t stride_s1 = width * S * sub_channels; + int64_t stride_w = S * sub_channels; + int64_t stride_s2 = sub_channels; + int64_t stride_c = 1; + + // input tensor shape of [n, h, s1, w, s2, c] + // output tensor shape of [n, h, w, c, s1, s2] + at::parallel_for(0, numel, 0, [&](int64_t begin, int64_t end) { + int64_t n{0}, h{0}, w{0}, c{0}, s1{0}, s2{0}; + data_index_init(begin, n, nbatch, h, height, w, width, c, sub_channels, s1, S, s2, S); + + for (const auto i : c10::irange(begin, end)) { + int64_t input_offset = n * stride_n + h * stride_h + s1 * stride_s1 + + w * stride_w + s2 * stride_s2 + c * stride_c; + output_data[i] = c10::load(&input_data[input_offset]); + + data_index_step(n, nbatch, h, height, w, width, c, sub_channels, s1, S, s2, S); + } + }); +} + +void pixel_shuffle_kernel_impl( + TensorBase& output, + const TensorBase& input, + int64_t upscale_factor) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, + input.scalar_type(), "pixel_shuffle", [&] { + cpu_pixel_shuffle(output, input, upscale_factor); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, + input.scalar_type(), "pixel_shuffle_channels_last", [&] { + cpu_pixel_shuffle_channels_last(output, input, upscale_factor); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +void pixel_unshuffle_kernel_impl( + TensorBase& output, + const TensorBase& input, + int64_t downscale_factor) { + switch (input.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + // input tensor shape of [N, C, Hr, Wr] + // output tensor shape of [N, Crr, H, W] + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, + input.scalar_type(), "pixel_unshuffle", [&] { + cpu_pixel_unshuffle(output, input, downscale_factor); + }); + break; + } + case at::MemoryFormat::ChannelsLast: { + // input tensor shape of [N, Hr, Wr, C] + // output tensor shape of [N, H, W, Crr] + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, + input.scalar_type(), "pixel_unshuffle_channels_last", [&] { + cpu_pixel_unshuffle_channels_last(output, input, downscale_factor); + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(pixel_shuffle_kernel, &pixel_shuffle_kernel_impl) +REGISTER_DISPATCH(pixel_unshuffle_kernel, &pixel_unshuffle_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PixelShuffleKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PixelShuffleKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..50be85c97c58e486b4307f616da30672f61b63a4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PixelShuffleKernel.h @@ -0,0 +1,14 @@ +#pragma once +#include + +namespace at { +class TensorBase; +} + +namespace at::native { + +using pixel_shuffle_fn = void(*)(TensorBase&, const TensorBase&, int64_t); +DECLARE_DISPATCH(pixel_shuffle_fn, pixel_shuffle_kernel) +DECLARE_DISPATCH(pixel_shuffle_fn, pixel_unshuffle_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PointwiseOpsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PointwiseOpsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c02f1e20bf7fa783968557aee20f7a4b9c366a7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PointwiseOpsKernel.cpp @@ -0,0 +1,246 @@ +// Ternary and higher-order pointwise operations +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +namespace at::native { +namespace { + +void addcmul_cpu_kernel(TensorIteratorBase& iter, const Scalar& value) { + ScalarType dtype = iter.common_dtype(); + if (at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(dtype, "addcmul_cpu_out", [&]() { + float float_val = value.to(); + auto float_vec = Vectorized(float_val); + cpu_kernel_vec( + iter, + [=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t { + return float(self_val) + float_val * float(t1_val) * float(t2_val); + }, + [=](Vectorized self_vec, + Vectorized t1_vec, + Vectorized t2_vec) -> Vectorized { + auto [self_vec0, self_vec1] = convert_to_float(self_vec); + auto [t1_vec0, t1_vec1] = convert_to_float(t1_vec); + auto [t2_vec0, t2_vec1] = convert_to_float(t2_vec); + self_vec0 = self_vec0 + float_vec * t1_vec0 * t2_vec0; + self_vec1 = self_vec1 + float_vec * t1_vec1 * t2_vec1; + return convert_from_float(self_vec0, self_vec1); + }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND(at::ScalarType::ComplexHalf, + dtype, "addcmul_cpu_out", [&] { + scalar_t scalar_val = value.to(); + auto scalar_vec = Vectorized(scalar_val); + cpu_kernel_vec( + iter, + [=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t { + return self_val + scalar_val * t1_val * t2_val; + }, + [=](Vectorized self_vec, + Vectorized t1_vec, + Vectorized t2_vec) { + return self_vec + scalar_vec * t1_vec * t2_vec; + }); + }); + } +} + +void addcdiv_cpu_kernel(TensorIteratorBase& iter, const Scalar& value) { + ScalarType dtype = iter.common_dtype(); + if (at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(dtype, "addcdiv_cpu_out", [&]() { + float float_val = value.to(); + auto float_vec = Vectorized(float_val); + cpu_kernel_vec( + iter, + [=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t { + return float(self_val) + float_val * float(t1_val) / float(t2_val); + }, + [=](Vectorized self_vec, + Vectorized t1_vec, + Vectorized t2_vec) -> Vectorized { + auto [self_vec0, self_vec1] = convert_to_float(self_vec); + auto [t1_vec0, t1_vec1] = convert_to_float(t1_vec); + auto [t2_vec0, t2_vec1] = convert_to_float(t2_vec); + self_vec0 = self_vec0 + float_vec * t1_vec0 / t2_vec0; + self_vec1 = self_vec1 + float_vec * t1_vec1 / t2_vec1; + return convert_from_float(self_vec0, self_vec1); + }); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX(dtype, "addcdiv_cpu_out", [&] { + scalar_t scalar_val = value.to(); + auto scalar_vec = Vectorized(scalar_val); + cpu_kernel_vec( + iter, + [=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t { + return self_val + scalar_val * t1_val / t2_val; + }, + [=](Vectorized self_vec, + Vectorized t1_vec, + Vectorized t2_vec) { + return self_vec + scalar_vec * t1_vec / t2_vec; + }); + }); + } +} + +void smooth_l1_backward_cpu_kernel(TensorIterator& iter, const Scalar& norm, double beta) { + ScalarType dtype = iter.dtype(0); + if (at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(dtype, "smooth_l1_backward_cpu_out", [&]() { + auto norm_val = norm.to(); + float beta_val(beta); + auto norm_val_vec = Vectorized(norm_val); + auto beta_val_vec = Vectorized(beta_val); + const auto neg_1_vec = Vectorized(-1); + const auto zero_vec = Vectorized(0); + const auto pos_1_vec = Vectorized(1); + cpu_kernel_vec(iter, + [=](scalar_t input, scalar_t target, scalar_t grad_output) -> scalar_t { + const auto x = float(input) - float(target); + if (x <= -beta) { + return -norm_val * float(grad_output); + }else if (x >= beta){ + return norm_val * float(grad_output); + }else{ + return norm_val * x * float(grad_output) / beta; + } + }, + [norm_val_vec, beta_val_vec, neg_1_vec, zero_vec, pos_1_vec]( + Vectorized input, Vectorized target, Vectorized grad_output) -> Vectorized { + // using two blendv calls to simulate the 3 cases + // 1 if x >= beta + // -1 if x <= -beta + // x / beta if |x| < beta + auto [input0, input1] = convert_to_float(input); + auto [target0, target1] = convert_to_float(target); + auto [grad_output0, grad_output1] = convert_to_float(grad_output); + auto x = input0 - target0; + auto pos_or_neg_1_vec = Vectorized::blendv( + neg_1_vec, pos_1_vec, x > zero_vec); + auto x_abs = x.abs(); + auto output = Vectorized::blendv( + x / beta_val_vec, pos_or_neg_1_vec, x_abs >= beta_val_vec); + input0 = norm_val_vec * output * grad_output0; + + x = input1 - target1; + pos_or_neg_1_vec = Vectorized::blendv( + neg_1_vec, pos_1_vec, x > zero_vec); + x_abs = x.abs(); + output = Vectorized::blendv( + x / beta_val_vec, pos_or_neg_1_vec, x_abs >= beta_val_vec); + input1 = norm_val_vec * output * grad_output1; + return convert_from_float(input0, input1); + } + ); + }); + } else { + AT_DISPATCH_ALL_TYPES(dtype, "smooth_l1_backward_cpu_out", [&] { + auto norm_val = norm.to(); + scalar_t beta_val(beta); + auto norm_val_vec = Vectorized(norm_val); + auto beta_val_vec = Vectorized(beta_val); + const auto neg_1_vec = Vectorized(-1); + const auto zero_vec = Vectorized(0); + const auto pos_1_vec = Vectorized(1); + cpu_kernel_vec(iter, + [=](scalar_t input, scalar_t target, scalar_t grad_output) -> scalar_t { + const auto x = input - target; + if (x <= -beta) + return -norm_val * grad_output; + else if (x >= beta) + return norm_val * grad_output; + else + return norm_val * x * grad_output / beta; + }, + [norm_val_vec, beta_val_vec, neg_1_vec, zero_vec, pos_1_vec]( + Vectorized input, Vectorized target, Vectorized grad_output) -> Vectorized { + // using two blendv calls to simulate the 3 cases + // 1 if x >= beta + // -1 if x <= -beta + // x / beta if |x| < beta + const auto x = input - target; + const auto pos_or_neg_1_vec = Vectorized::blendv( + neg_1_vec, pos_1_vec, x > zero_vec); + const auto x_abs = x.abs(); + const auto output = Vectorized::blendv( + x / beta_val_vec, pos_or_neg_1_vec, x_abs >= beta_val_vec); + return norm_val_vec * output * grad_output; + } + ); + }); + } +} + +void huber_backward_cpu_kernel(TensorIterator& iter, const Scalar& norm, double delta) { + ScalarType dtype = iter.dtype(0); + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, dtype, "huber_backward_cpu_out", [&] { + auto norm_val = norm.to(); + scalar_t delta_val(delta); + auto norm_val_vec = Vectorized(norm_val); + auto delta_val_vec = Vectorized(delta_val); + const auto neg_1_vec = Vectorized(-1); + const auto zero_vec = Vectorized(0); + const auto pos_1_vec = Vectorized(1); + cpu_kernel_vec(iter, + [=](scalar_t input, scalar_t target, scalar_t grad_output) -> scalar_t { + const auto x = input - target; + if (x <= -delta) { + return -norm_val * grad_output * delta; + } else if (x >= delta) { + return norm_val * grad_output * delta; + } else { + return norm_val * x * grad_output; + } + }, + [norm_val_vec, delta_val_vec, neg_1_vec, zero_vec, pos_1_vec]( + Vectorized input, Vectorized target, Vectorized grad_output) -> Vectorized { + // using two blendv calls to simulate the 3 cases + // delta if x >= delta + // -delta if x <= -delta + // x if |x| < delta + const auto x = input - target; + const auto pos_or_neg_1_vec = Vectorized::blendv( + neg_1_vec, pos_1_vec, x > zero_vec); + const auto x_abs = x.abs(); + const auto output = Vectorized::blendv( + x, pos_or_neg_1_vec * delta_val_vec, x_abs >= delta_val_vec); + return norm_val_vec * output * grad_output; + } + ); + }); +} + +void mse_backward_cpu_kernel(TensorIterator& iter, const Scalar& value) { + ScalarType dtype = iter.dtype(0); + AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, dtype, "mse_backward_cpu_out", [&] { + scalar_t scalar_val = value.to(); + auto scalar_vec = Vectorized(scalar_val); + cpu_kernel_vec( + iter, + [=](scalar_t self_val, scalar_t t1_val, scalar_t t2_val) -> scalar_t { + return scalar_val * (self_val - t1_val) * t2_val; + }, + [=](Vectorized self_vec, + Vectorized t1_vec, + Vectorized t2_vec) { + return scalar_vec * (self_vec - t1_vec) * t2_vec; + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(addcmul_stub, &addcmul_cpu_kernel) +REGISTER_DISPATCH(addcdiv_stub, &addcdiv_cpu_kernel) +REGISTER_DISPATCH(smooth_l1_backward_stub, &smooth_l1_backward_cpu_kernel) +REGISTER_DISPATCH(huber_backward_stub, &huber_backward_cpu_kernel) +REGISTER_DISPATCH(mse_backward_stub, &mse_backward_cpu_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PowKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PowKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1813ccda0cbb2cef1ba7df407d6e6c7ca0b9038e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/PowKernel.cpp @@ -0,0 +1,153 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native { + +inline namespace CPU_CAPABILITY { + +static void pow_tensor_tensor_kernel(TensorIteratorBase& iter) { + const auto dtype = iter.common_dtype(); + if (isFloatingType(dtype) || isComplexType(dtype)) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kHalf, kBFloat16, dtype, "pow", [&]() { + + using Vec = Vectorized; + cpu_kernel_vec(iter, + [=](scalar_t base, scalar_t exp) -> scalar_t { + return std::pow(base, exp); + }, + [&](Vec base, Vec exp) -> Vec { + return base.pow(exp); + } + ); + }); + } else { + AT_DISPATCH_INTEGRAL_TYPES(dtype, "pow", [&]() { + cpu_kernel(iter, + [=](scalar_t base, scalar_t exp) -> scalar_t { + return native::powi(base, exp); + } + ); + }); + } +} + +// The source-code of kernels for float, double and complex types is similar, +// barring a small distinction - even if the output dtype is float, a double +// exponent can be used. But Complex types' computation doesn't allow standard +// & double-precision to be mixed, since std::pow takes either complex64 inputs, +// or complex128 inputs, but not both. So, in order to provide a common path for +// float, double & complex types, template parameter cast_scalar_t is being used +// to resolve the aforementioned distinction. This approach also allows BFloat16 +// to use this common-path. Half cannot currently use it, as AVX2 support for +// sqrt & rsqrt doesn't currently exist for it. +template +void pow_tensor_scalar_optimized_kernel(TensorIteratorBase& iter, const exp_scalar_t exp) { + using Vec = Vectorized; + // .5 (sqrt), -.5 (rsqrt) and -1 (reciprocal) specializations are handled + // in pow_tensor_scalar_kernel + if (exp == 2.0) { + cpu_kernel_vec(iter, + [](scalar_t base) -> scalar_t { + return base * base; + }, + [](Vec base) -> Vec { return base * base; } + ); + } else if (exp == 3.0) { + cpu_kernel_vec(iter, + [](scalar_t base) -> scalar_t { + return base * base * base; + }, + [](Vec base) -> Vec { return base * base * base; } + ); + } else if (exp == -2.0) { + cpu_kernel_vec(iter, + [](scalar_t base) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return static_cast(1.0) / (base * base); }, + [](Vec base) -> Vec { return (base * base).reciprocal(); } + ); + } else { + cpu_kernel_vec(iter, + [=](scalar_t base) -> scalar_t { + return std::pow(base, static_cast(exp)); + }, + [=](Vec base) -> Vec { + return base.pow(static_cast(exp)); + } + ); + } +} + +static void pow_tensor_scalar_kernel( + TensorIteratorBase& iter, + const Scalar& exp_scalar) { + // prevent multiple calls to iter.common_dtype() + const auto dtype = iter.common_dtype(); + + if (dtype == ScalarType::Float || dtype == ScalarType::Double || + dtype == kBFloat16 || isComplexType(dtype)) { + // Dispatch to fast specialization for sqrt, rsqrt and reciprocal + if (exp_scalar.equal(.5)) { + sqrt_kernel(iter); + return; + } else if (exp_scalar.equal(-0.5)) { + rsqrt_kernel(iter); + return; + } else if (exp_scalar.equal(-1.0)) { + reciprocal_kernel(iter); + return; + } + } + + if (dtype == ScalarType::Float || dtype == ScalarType::Double) { + AT_DISPATCH_FLOATING_TYPES(dtype, "pow", [&]() { + pow_tensor_scalar_optimized_kernel( + iter, exp_scalar.to()); + }); + } else if (isComplexType(dtype)) { + AT_DISPATCH_COMPLEX_TYPES(dtype, "pow", [&]() { + pow_tensor_scalar_optimized_kernel( + iter, exp_scalar.to>()); + }); + } else if (dtype == ScalarType::Half) { + [&]() { + using scalar_t = + c10::impl::ScalarTypeToCPPTypeT; + const auto exp = exp_scalar.to(); + using Vec = Vectorized; + cpu_kernel_vec(iter, + [=](scalar_t base) -> scalar_t { + return std::pow(base, exp); + }, + [=](Vec base) -> Vec { return base.pow(exp); } + ); + }(); + } else if (dtype == ScalarType::BFloat16) { + AT_DISPATCH_FLOATING_TYPES_AND(kBFloat16, dtype, "pow", [&]() { + pow_tensor_scalar_optimized_kernel( + iter, exp_scalar.to()); + }); + } else { + AT_DISPATCH_INTEGRAL_TYPES(dtype, "pow", [&]() { + const scalar_t exp = exp_scalar.to(); + cpu_kernel(iter, [=](scalar_t base) -> scalar_t { + return native::powi(base, exp); + }); + }); + } +} + +} // anonymous namespace + +ALSO_REGISTER_AVX512_DISPATCH(pow_tensor_tensor_stub, &CPU_CAPABILITY::pow_tensor_tensor_kernel) +ALSO_REGISTER_AVX512_DISPATCH(pow_tensor_scalar_stub, &CPU_CAPABILITY::pow_tensor_scalar_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/README.md b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8a730c726cf46dfcbb27e3ace75be8490f5afdcd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/README.md @@ -0,0 +1,90 @@ +The most important things to know: + +**Don't add a kernel to this folder unless you want it to be +compiled multiple times for different instruction sets.** Yes, +this folder is named `cpu`, but that doesn't mean put any old +CPU kernel it. Only put CPU kernels which need to be compiled +multiple times to take advantage of AVX512/AVX2/SSE instructions, but +only on processors that support them. + +**Ensure that all implementations in this folder are put in an +anonymous namespace.** The files in this folder are compiled multiple +times with different headers. It's important that these functions have +internal linkage so that kernels for different architectures don't get +combined during linking. It's sufficient to label functions "static", +but class methods must be an unnamed namespace to have internal linkage +(since static means something different in the context of classes). + +**The basic recipe is to define your kernel, and then register +it using DECLARE/REGISTER DISPATCH.** Writing a kernel requires +three steps: + +1. Declare your dispatch in a header file using + `DECLARE_DISPATCH(fn_type, fnNameImpl)` + where `fn_type` is the function pointer type of the kernel (e.g., + defined as `using fn_type = void(*)(Tensor&, const Tensor&)` + and `fnNameImpl` is the name of your dispatch registry. + (It doesn't really matter where you put this declaration.) + +2. Define your dispatch in a C++ file that is NOT in the cpu + directory (dispatch must be defined exactly once) using + `DEFINE_DISPATCH(fnNameImpl)` (matching the name of your declaration.) + Include the header file that declares the dispatch in this C++ + file. Conventionally, we define the dispatch in the same file + we will define our native function in. + +3. Define a native function which calls into the dispatch using + `fnNameImpl(kCPU, arguments...)`, where the arguments are + the arguments according to the `fn_type` you defined in the + declaration. + +4. Write your actual kernel (e.g., `your_kernel`) in the + cpu directory, and register it to + the dispatch using `REGISTER_DISPATCH(fnNameImpl, &your_kernel)`, if + it does not perform as well with AVX512, as it does with AVX2. + Otherwise, if it performs well with AVX512, register it with `ALSO_REGISTER_AVX512_DISPATCH(fnNameImpl, &your_kernel)`. + Compute-intensive kernels tend to perform better with AVX512, than with AVX2. + Comparing AVX2 & AVX512 variants of a kernel can be done by registering a kernel with `ALSO_REGISTER_AVX512_DISPATCH(fnNameImpl, &your_kernel)`, building from source, and then benchmarking the kernel's performance by running a benchmarking script with the environment variables `ATEN_CPU_CAPABILITY=avx2` and `ATEN_CPU_CAPABILITY=avx512`, respectively. + tcmalloc/jemalloc can be preloaded for minimal run-to-run variation. + +There are plenty of existing examples, look at them for more details. + +---- + +TODO: Clarify and add more documentation all around. + +All of the `*.cpp` files in this folder will be compiled under all compiler +flags specified by `CPU_CAPABILITY_FLAGS` in `aten/src/ATen/CMakeLists.txt`. + +The purpose of this is to allow the compilation with various compiler +flags to enable features such as AVX2 or AVX512 instructions, while using +runtime dispatch, which makes sure only valid instructions will be used on any +given platform. + +vec.h provides a generic implementation of vec type that allows +the programmer to write code packing various primitives (such as floats) +within 256bit & 512bits registers. vec defines various operators such as ++ and * and provides functions to allow operations such as max, min, etc. + +As an example `ReduceOpsKernel.cpp` implements a generic `kernel_` that reduces +an entire array using a given associative binary operation such as +. + +More explicitly, calling `kernel_` with template argument `std::plus` will cause +it to sum up the entire array into a single value. + +`ReduceOpsKernel.cpp` uses the `CPU_CAPABILITY_*` macros to "know" under which +compiler flags it is currently compiled. This allows the programmer to write +generic code, which will be compiled under multiplied compilation settings. + +`../ReduceOps.cpp` now includes the header `ReduceOpsKernel.h`, which contains +a generic definition of `sumImplAll`. This function allows the user to reduce +over a dimension or all dimensions. The appropriate capability is chosen at +runtime using cpuinfo. If the current platform has AVX2, `sumImpl` will be set +to `sumImplAll`. + +At runtime, the following environment variables control which codepath is taken: + +x64 options: +ATEN_CPU_CAPABILITY=avx2 # Force AVX2 codepaths to be used +ATEN_CPU_CAPABILITY=avx # Force AVX codepaths to be used +ATEN_CPU_CAPABILITY=default # Use oldest supported vector instruction set diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/RangeFactoriesKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/RangeFactoriesKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..215c84058220ecc177172e351065a91040f50e05 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/RangeFactoriesKernel.cpp @@ -0,0 +1,77 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +namespace at::native { +namespace { + +using namespace vec; + +void arange_kernel(TensorIterator& iter, const Scalar& scalar_start, const Scalar& scalar_steps, const Scalar& scalar_step) { + AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "arange_cpu", [&]() { + using accscalar_t = at::acc_type; + auto start = scalar_start.to(); + auto steps = scalar_steps.to(); + auto step = scalar_step.to(); + at::parallel_for(0, steps, internal::GRAIN_SIZE, [&](int64_t p_begin, int64_t p_end) { + int64_t idx(p_begin); + TensorIterator it(iter); + cpu_serial_kernel_vec( + it, + [start, step, &idx]() -> scalar_t { + return start + step * (idx++); + }, + [start, step, &idx]() -> Vectorized { + Vectorized res; + res = Vectorized::arange(start + step * idx, step); + idx += Vectorized::size(); + return res; + }, {p_begin, p_end}); + }); + }); +} + +void linspace_kernel(TensorIterator& iter, const Scalar& scalar_start, const Scalar& scalar_end, int64_t steps) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kHalf, kBFloat16, iter.dtype(), "linspace_cpu", [&]() { + // step should be of double type for all integral types + using step_t = std::conditional_t, double, scalar_t>; + const scalar_t start = scalar_start.to(); + const scalar_t end = scalar_end.to(); + // Cast `end` and `start` to `step_t`, since range can be larger than scalar_t for integral types + const step_t step = (static_cast(end) - static_cast(start)) / (steps - 1); + int64_t halfway = steps / 2; + at::parallel_for(0, steps, internal::GRAIN_SIZE, [&](int64_t p_begin, int64_t p_end) { + int64_t idx(p_begin); + TensorIterator it(iter); + // Remove vectorization implementation, due to the precision issue between integer and double. + // Will not harm the performance. + cpu_serial_kernel( + it, + [start, end, step, halfway, steps, &idx]() -> scalar_t { + if (idx < halfway) { + return start + step * (idx++); + } else { + return end - step * (steps - (idx++) - 1); + } + }, {p_begin, p_end}); + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(arange_stub, &arange_kernel) +REGISTER_DISPATCH(linspace_stub, &linspace_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Reduce.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Reduce.h new file mode 100644 index 0000000000000000000000000000000000000000..6ec2faf3360bbc29752f4c40357dc1cb192491dd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Reduce.h @@ -0,0 +1,310 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +namespace at::native { inline namespace CPU_CAPABILITY { + +using namespace vec; + +#define VEC_LOOP_HEADER(func_t, data) \ + using scalar_t = typename function_traits::result_type; \ + using Vec = Vectorized; \ + char* out_ptr = data[0]; \ + (void) out_ptr; + +// reduction that is contiguous over the input in dim 0 +template +inline bool is_contiguous_reduction(const int64_t* strides) { + return strides[0] == 0 && + strides[1] == sizeof(typename traits::arg2_t); +} + +// reduction that is contiguous over the input in dim 1 +template +inline bool is_outer_reduction(const int64_t* strides) { + return strides[0] == 0 && + strides[2] == sizeof(typename traits::result_type) && + strides[3] == sizeof(typename traits::arg2_t); +} + +template +inline void vectorized_reduction(char** data, int64_t n, int64_t stride, + func_t op, vec_func_t vop, bool reduce) { + VEC_LOOP_HEADER(func_t, data) + const char* in1_ptr = data[1]; + Vec acc[4]; + for (const auto j : c10::irange(4)) { + acc[j] = Vec::loadu(in1_ptr + j * Vec::size() * sizeof(scalar_t)); + } + for (const auto i : c10::irange(1, n)) { + const char* ptr = in1_ptr + stride * i; + acc[0] = vop(acc[0], Vec::loadu(ptr + (0 * Vec::size() * sizeof(scalar_t)))); + acc[1] = vop(acc[1], Vec::loadu(ptr + (1 * Vec::size() * sizeof(scalar_t)))); + acc[2] = vop(acc[2], Vec::loadu(ptr + (2 * Vec::size() * sizeof(scalar_t)))); + acc[3] = vop(acc[3], Vec::loadu(ptr + (3 * Vec::size() * sizeof(scalar_t)))); + } + if (reduce) { + scalar_t buffer[Vec::size()]; + acc[0] = vop(vop(acc[0], acc[1]), vop(acc[2], acc[3])); + acc[0].store(buffer); + for (const auto j : c10::irange(1, Vec::size())) { + buffer[0] = op(buffer[0], buffer[j]); + } + auto dst = (scalar_t*)out_ptr; + *dst = op(*dst, buffer[0]); + } else { + for (const auto j : c10::irange(4)) { + auto dst = out_ptr + j * Vec::size() * sizeof(scalar_t); + acc[j] = vop(acc[j], Vec::loadu(dst)); + acc[j].store(dst); + } + } +} + +template +inline void UNARY_OUTER_LOOP(char* data[2], const int64_t strides[2], int64_t n, F f) { + for ([[maybe_unused]] const auto j : c10::irange(n)) { + f(); + data[0] += strides[0]; + data[1] += strides[1]; + } +} + +// computes the reduction out = op(out, in) +template +inline void vectorized_inner_reduction(char** data, int64_t n, func_t op, vec_func_t vop) { + VEC_LOOP_HEADER(func_t, data) + constexpr int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t); + int64_t count = n / (4 * Vec::size()); + if (count > 0) { + vectorized_reduction(data, count, vector_stride, op, vop, /*reduce=*/true); + } + char* ptrs[3] = { data[0], data[0], data[1] }; + int64_t strides[] = { 0, 0, sizeof(scalar_t) }; + basic_loop(ptrs, strides, count * 4 * Vec::size(), n, op); +} + +// computes the reduction out = op(out, in) +template +inline void vectorized_outer_reduction(char** data, int64_t inner_stride, int64_t size0, int64_t size1, func_t op, vec_func_t vop) { + VEC_LOOP_HEADER(func_t, data) + + // reduce down each column of 4 * Vec::size() elements. + constexpr int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t); + int64_t outer_stride[2] = { vector_stride, vector_stride }; + UNARY_OUTER_LOOP(data, outer_stride, size1 / (4 * Vec::size()), [&] { + vectorized_reduction(data, size0, inner_stride, op, vop, /*reduce=*/false); + }); + + // reduce down the remaining columns + int64_t step[] = { sizeof(scalar_t), sizeof(scalar_t) }; + int64_t remaining = size1 % (4 * Vec::size()); + UNARY_OUTER_LOOP(data, step, remaining, [&] { + char* ptrs[3] = { data[0], data[0], data[1] }; + int64_t strides[] = { 0, 0, inner_stride }; + basic_loop(ptrs, strides, 0, size0, op); + }); +} + +template +static void set_result(const int index, const res_t result, const TensorIteratorBase &iter, const int num_outputs) { + // static_assert(std::is_same_v, "data types must match"); + if (index < num_outputs) { + char *out = (char *) iter.data_ptr(index); + *(res_t *) out = result; + } +} + +template +static void set_results(const res_t result, const TensorIteratorBase &iter, const int num_outputs) { + AT_ASSERT(num_outputs == 1); + set_result(0, result, iter, num_outputs); +} + +template +inline std::enable_if_t +for_each_in_tuple(const std::tuple& /*t*/, const TensorIteratorBase& /*iter*/, const int /*num_outputs*/) { + return i; +} + +template +inline std::enable_if_t +for_each_in_tuple(const std::tuple& t, const TensorIteratorBase &iter, const int num_outputs) { + if (i < (size_t)num_outputs) { + set_result(i, std::get(t), iter, num_outputs); + return for_each_in_tuple(t, iter, num_outputs); + } + return i; +} + +template +static void set_results(const std::tuple& result, const TensorIteratorBase &iter, const int num_outputs) { + AT_ASSERT(num_outputs >= 1); + std::size_t result_size = for_each_in_tuple(result, iter, num_outputs); + AT_ASSERT((size_t)num_outputs == result_size); +} + +template +struct all_same : std::conjunction< + std::is_same... +> {}; + +// data_t is the input/output data type. +// acc_t is a type that contains all the necessary data +// to continue reducing. +// index_t is a one-dimensional index +// +// ops_t is such that &ops_t::reduce, &ops_t::combine, and &ops_t::project exist and satisfy +// the following. +// reduce: (acc_t, data_t, index_t) -> acc_t adds one data point to the accumulated value. +// combine: (acc_t, acc_t) -> acc_t combines two accumulated values into one. +// project: acc_t -> out_t finishes the reduction, getting the required output. +// +// Additionally, acc_t must be default-constructible: +// acc_t {} is an identity for combine, +// and project(acc_t {}) is the value of the operation on zero elements. +// +// The point of `combine` is to support parallelization - +// the idea is to one sequence of `reduce` calls per thread of execution, +// and then to combine them at the end with `combine`. +// +// If there is more than one output element, +// our parallelization strategy is to use one thread for each of them, +// which means that `combine` will never be called. +// +// If, on the other hand, there is only one, then we split the input into +// into several pieces, reduce each separately, and then combine them. + +template +void binary_kernel_reduce(TensorIteratorBase& iter, ops_t ops, init_t init) { + using rf_t = decltype(&ops_t::reduce); + using cf_t = decltype(&ops_t::combine); + using pf_t = decltype(&ops_t::project); + using r_traits = binary_function_traits; + using c_traits = binary_function_traits; + using p_traits = unary_function_traits; + using acc_t = typename p_traits::arg1_t; + using data_t = typename r_traits::arg2_t; + static_assert( + all_same< + acc_t, + init_t, + typename r_traits::arg1_t, + typename r_traits::result_type, + typename c_traits::arg1_t, + typename c_traits::arg2_t, + typename c_traits::result_type>::value, + "all accumulate types must match"); + static_assert( + std::is_default_constructible_v, + "the accumulate type must be default-constructible" + ); + const int num_outputs = iter.noutputs(); + iter.foreach_reduced_elt([&ops, &init, num_outputs](TensorIteratorBase &sub_iter) { + auto reduction_body = [&ops, &sub_iter, num_outputs](acc_t acc, int64_t begin, int64_t end) -> acc_t { + int ntensors = sub_iter.ntensors(); + sub_iter.serial_for_each([&acc, &ops, num_outputs, ntensors, begin](char** data, const int64_t* strides, int64_t size) { + AT_ASSERT(ntensors - num_outputs == 1); + char *in = data[ntensors - 1]; + int64_t stride = strides[ntensors - 1]; + for (const auto i : c10::irange(size)) { + acc = ops.reduce(acc, c10::load(in), begin + i); + in += stride; + } + }, {begin, end}); + return ops.translate_idx(acc, sub_iter.view_offsets()[0]); + }; + acc_t total_acc = init; + auto numel = sub_iter.numel(); + if (numel < at::internal::GRAIN_SIZE || at::get_num_threads() == 1 || + at::in_parallel_region()) { + total_acc = reduction_body(total_acc, 0, numel); + } else { + int max_threads = at::get_num_threads(); + AT_ASSERT(max_threads > 0); + static_assert( + !std::is_same_v, + "Concurrently modifying different references into std::vector is UB." + ); + std::vector buffer((unsigned)max_threads, init); + at::parallel_for(0, numel, internal::GRAIN_SIZE, + [&](int64_t begin, int64_t end) { + auto& acc = buffer[at::get_thread_num()]; + acc = reduction_body(acc, begin, end); + } + ); + for (const auto i : c10::irange(max_threads)) { + total_acc = ops.combine(total_acc, buffer[i]); + } + } + set_results(ops.project(total_acc), sub_iter, num_outputs); + }); +} + +template +void binary_kernel_reduce_vec(TensorIteratorBase& iter, func_t op, vec_func_t vop, double ident = 0) { + using traits = binary_function_traits; + static_assert( + all_same< + typename traits::result_type, + typename traits::arg1_t, + typename traits::arg2_t>::value, + "all types must match"); + + iter.output_base().fill_(ident); + iter.parallel_reduce([&](char** data, const int64_t* strides, int64_t size0, int64_t size1) { + int64_t outer_strides[] = { strides[2], strides[3] }; + if (is_contiguous_reduction(strides)) { + // input is contiguous in dim 0, output is reduced in dim 0 + UNARY_OUTER_LOOP(data, outer_strides, size1, [&] { + vectorized_inner_reduction(data, size0, op, vop); + }); + } else if (is_outer_reduction(strides)) { + // input and output are contiguous in dim 1 + int64_t inner_stride = strides[1]; // stride of input in dim 0 + vectorized_outer_reduction(data, inner_stride, size0, size1, op, vop); + } else { + UNARY_OUTER_LOOP(data, outer_strides, size1, [&] { + char* ptrs[3] = { data[0], data[0], data[1] }; + int64_t inner_strides[3] = { strides[0], strides[0], strides[1] }; + basic_loop(ptrs, inner_strides, 0, size0, op); + }); + } + }); +} + +// when reduction is on most inner dimension (dim 0 in TensorIterator) +// and input has contiguous most inner dimension, `binary_kernel_reduce_lastdim` +// can be used. +inline bool is_reduce_lastdim(TensorIteratorBase& iter) { + return iter.num_reduce_dims() == 1 && iter.is_dim_reduced(0) + && iter.ninputs() == 1 && iter.strides(1)[0] == iter.element_size(1); +} + +template +void binary_kernel_reduce_lastdim(TensorIteratorBase& iter, reduce_func_t reduce_op) { + auto shape = iter.shape(); + int64_t dim_size = shape[0]; + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / dim_size); + TensorIterator sub_iter(iter); + // create sub iterator to parallel on all non-reduce-dims + sub_iter.narrow(0, 0, 1); + auto loop = [&](char** data, const int64_t* strides, int64_t size) { + char* out = data[0]; + char* in = data[1]; + for (int64_t i = 0; i < size; ++i) { + reduce_op(out, in, dim_size); + out += strides[0]; + in += strides[1]; + } + }; + sub_iter.for_each(loop, grain_size); +} + +}} // namespace at::native:: diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceAllOpsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceAllOpsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fab92fe90b694a1cb51be0ec4cc90154a7a2cebf --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceAllOpsKernel.cpp @@ -0,0 +1,227 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +using namespace vec; + +template +inline void reduce_all_impl_vec( + Tensor& output, + const Tensor& input, + const scalar_t ident_v, + func_t op, + vec_func_t vop) { + using Vec = Vectorized>; + const int64_t input_numel = input.numel(); + auto input_data = input.const_data_ptr(); + // NOTE: parallel_reduce not support bool type + scalar_t result = at::parallel_reduce(0, input_numel, internal::GRAIN_SIZE, ident_v, + [&](int64_t start, int64_t end, const scalar_t /*ident*/) -> scalar_t { + scalar_t partial_out = vec::reduce_all( + [=](Vec x, Vec y) { return vop(x, y); }, + input_data + start, + end - start); + return partial_out; + }, op); + output.fill_(result); +} + +// For operation not support in avx/avx2 +template +inline void reduce_all_impl( + Tensor& output, + const Tensor& input, + const scalar_t ident_v, + func_t op) { + const int64_t input_numel = input.numel(); + auto input_data = input.const_data_ptr(); + scalar_t result = at::parallel_reduce(0, input_numel, internal::GRAIN_SIZE, ident_v, + [&](int64_t start, int64_t end, const scalar_t ident) -> scalar_t { + scalar_t partial_out = ident; + for (const auto i : c10::irange(start, end)) { + partial_out = op(partial_out, input_data[i]); + } + return partial_out; + }, op); + output.fill_(result); +} + +void min_all_kernel_impl(Tensor& result, const Tensor& input) { + if (input.scalar_type() == ScalarType::Bool) { + TensorIterator iter = TensorIteratorConfig() + .add_input(input) + .build(); + bool result_data = true; + cpu_serial_kernel(iter, [&](const bool a) -> void { + result_data = result_data && a; + }); + result.fill_(result_data); + } else if(input.scalar_type() == ScalarType::Long) { + // for int64_t, vectorized implementation have performance issue, + // just use scalar path + reduce_all_impl(result, input, upper_bound(), + [=](int64_t a, int64_t b) -> int64_t { return min_impl(a, b); }); + } else { + AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "min_all", [&] { + using Vec = Vectorized>; + reduce_all_impl_vec(result, input, upper_bound(), + [=] (scalar_t a , scalar_t b) -> scalar_t { return min_impl(a, b); }, + [=](Vec a, Vec b) -> Vec { return minimum(a, b); }); + }); + } +} + +void max_all_kernel_impl(Tensor& result, const Tensor& input) { + if (input.scalar_type() == ScalarType::Bool) { + TensorIterator iter = TensorIteratorConfig() + .add_input(input) + .build(); + bool result_data = false; + cpu_serial_kernel(iter, [&](const bool a) -> void { + result_data = result_data || a; + }); + result.fill_(result_data); + } else if (input.scalar_type() == ScalarType::Long) { + // for int64_t, vectorized implementation have performance issue, + // just use scalar path + reduce_all_impl(result, input, lower_bound(), + [=](int64_t a, int64_t b) -> int64_t { return max_impl(a, b); }); + } else { + AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), "max_all", [&] { + using Vec = Vectorized>; + reduce_all_impl_vec(result, input, lower_bound(), + [=] (scalar_t a , scalar_t b) -> scalar_t { return max_impl(a, b); }, + [=](Vec a, Vec b) -> Vec { return maximum(a, b); }); + }); + } +} + +// For operation not support in avx/avx2 +template +inline void reduce_all_impl_two_outputs( + Tensor& output1, + Tensor& output2, + const Tensor& input, + const std::pair& ident_v, + func_t1 reduce_chunk_func, + func_t2 reduce_acc_func) { + using scalar_t_pair = std::pair; + const int64_t input_numel = input.numel(); + auto input_data = input.const_data_ptr(); + scalar_t_pair result = at::parallel_reduce(0, input_numel, internal::GRAIN_SIZE, ident_v, + [&](int64_t start, int64_t end, const scalar_t_pair& ident) -> scalar_t_pair { + scalar_t_pair partial_out(ident); + for (const auto i : c10::irange(start, end)) { + partial_out = reduce_chunk_func(partial_out, input_data[i]); + } + return partial_out; + }, + reduce_acc_func + ); + output1.fill_(result.first); + output2.fill_(result.second); +} + +template +inline void reduce_all_impl_vec_two_outputs( + Tensor& output1, + Tensor& output2, + const Tensor& input, + const std::pair& ident_v, + func_t reduce_acc_func, + vec_func_t1 reduce_chunk_func1, + vec_func_t2 reduce_chunk_func2) { + using Vec = Vectorized>; + using scalar_t_pair = std::pair; + const int64_t input_numel = input.numel(); + auto input_data = input.const_data_ptr(); + // NOTE: parallel_reduce not support bool type + std::pair result = at::parallel_reduce(0, input_numel, internal::GRAIN_SIZE, ident_v, + [&](int64_t start, int64_t end, const scalar_t_pair& /* ident */) -> scalar_t_pair { + scalar_t_pair partial_out = vec::reduce2_all( + [=](Vec x, Vec y) { return reduce_chunk_func1(x, y); }, + [=](Vec x, Vec y) { return reduce_chunk_func2(x, y); }, + input_data + start, + end - start); + return partial_out; + }, + reduce_acc_func + ); + output1.fill_(result.first); + output2.fill_(result.second); +} + +void aminmax_allreduce_kernel( + const Tensor& input, + Tensor& min_result, + Tensor& max_result) { + if (input.scalar_type() == ScalarType::Bool) { + TensorIterator iter = TensorIteratorConfig() + .add_input(input) + .build(); + bool min_result_data = true; + bool max_result_data = false; + cpu_serial_kernel(iter, [&](const bool a) -> void { + min_result_data = min_result_data && a; + max_result_data = max_result_data || a; + }); + min_result.fill_(min_result_data); + max_result.fill_(max_result_data); + } else if (input.scalar_type() == ScalarType::Long) { + // for int64_t, vectorized implementation have performance issue, + // just use scalar path + using int64_t_pair = std::pair; + reduce_all_impl_two_outputs(min_result, max_result, input, + int64_t_pair(upper_bound(), lower_bound()), + // reduce over chunk + [=](int64_t_pair a, int64_t b) -> int64_t_pair { + return int64_t_pair(min_impl(a.first, b), max_impl(a.second, b)); + }, + // combine two inputs + [=](int64_t_pair a, int64_t_pair b) -> int64_t_pair { + return int64_t_pair(min_impl(a.first, b.first), max_impl(a.second, b.second)); + } + ); + } else { + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "aminmax_cpu", [&] { + using Vec = Vectorized>; + using scalar_t_pair = std::pair; + reduce_all_impl_vec_two_outputs( + min_result, + max_result, + input, + scalar_t_pair(upper_bound(), lower_bound()), + [=] (scalar_t_pair a , scalar_t_pair b) -> scalar_t_pair { + return scalar_t_pair( + min_impl(a.first, b.first), max_impl(a.second, b.second)); + }, + [=](Vec a, Vec b) -> Vec { return minimum(a, b); }, + [=](Vec a, Vec b) -> Vec { return maximum(a, b); } + ); + }); + } +} + +} // namespace + +REGISTER_DISPATCH(min_all_stub, &min_all_kernel_impl) +REGISTER_DISPATCH(max_all_stub, &max_all_kernel_impl) +REGISTER_DISPATCH(aminmax_allreduce_stub, &aminmax_allreduce_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceOpsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceOpsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06fcfc8b9bdd1f8ba693a92dfcbbb14e5e053ad2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceOpsKernel.cpp @@ -0,0 +1,567 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include +#include + +namespace at::native { namespace { + +using namespace vec; + +template +inline void cpu_cum_base_kernel(const Tensor& result, + const Tensor& self, + int64_t dim, + const func_t& f, + scalar_t init_val) { + if (result.sizes() != self.sizes()) { + at::native::resize_output(result, self.sizes()); + } + if (self.numel() == 0) { + return; + } + const auto input_ndim = self.dim(); + if (input_ndim == 0) { + result.fill_(self); + return; + } + + // TODO This probably should be using at::native::make_reduction + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(self.sizes(), /*squash_dims=*/dim) + .add_output(result) + .add_const_input(self) + .build(); + + auto result_dim_stride = ensure_nonempty_stride(result, dim); + auto self_dim_stride = ensure_nonempty_stride(self, dim); + + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* result_data_bytes = data[0]; + const auto* self_data_bytes = data[1]; + + for ([[maybe_unused]] const auto i : c10::irange(n)) { + f((scalar_t*)result_data_bytes, + result_dim_stride, + (scalar_t*)self_data_bytes, + self_dim_stride, + init_val); + result_data_bytes += strides[0]; + self_data_bytes += strides[1]; + } + }; + + int64_t grain_size = internal::GRAIN_SIZE / std::max(int64_t{1}, self.size(dim)); + iter.for_each(loop, grain_size); +} + +void cumsum_cpu_kernel(const Tensor& result, const Tensor& self, int64_t dim) { + auto wrap_dim = maybe_wrap_dim(dim, self.dim()); + int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim); + + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, self.scalar_type(), "cumsum_out_cpu", [&] { + cpu_cum_base_kernel(result, self, wrap_dim, [&] ( + scalar_t* result_data, auto result_dim_stride, + const scalar_t* self_data, auto self_dim_stride, scalar_t init_val) { + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + auto cum_number = (at::acc_type)init_val; + for (const auto i : c10::irange(self_dim_size)) { + cum_number += self_data[i * self_dim_stride]; + result_data[i * result_dim_stride] = (scalar_t)cum_number; + } + }, /*init_val=*/ 0 + ); + }); +} + +void cumprod_cpu_kernel(const Tensor& result, const Tensor& self, int64_t dim) { + auto wrap_dim = maybe_wrap_dim(dim, self.dim()); + int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim); + + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, self.scalar_type(), "cumprod_out_cpu", [&] { + cpu_cum_base_kernel(result, self, wrap_dim, [&] ( + scalar_t* result_data, auto result_dim_stride, + const scalar_t* self_data, auto self_dim_stride, scalar_t init_val) { + // NOLINTNEXTLINE(bugprone-signed-char-misuse) + auto cum_number = (at::acc_type)init_val; + for (const auto i : c10::irange(self_dim_size)) { + cum_number *= self_data[i * self_dim_stride]; + result_data[i * result_dim_stride] = (scalar_t)cum_number; + } + }, /*init_val=*/ 1 + ); + }); +} + +void logcumsumexp_cpu_kernel(Tensor& result, const Tensor& self, int64_t dim) { + auto wrap_dim = maybe_wrap_dim(dim, self.dim()); + int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, self.scalar_type(), "logcumsumexp_out_cpu", [&] { + cpu_cum_base_kernel(result, self, wrap_dim, [&] ( + scalar_t* result_data, auto result_dim_stride, + const scalar_t* self_data, auto self_dim_stride, scalar_t init_val) { + using accscalar_t = at::acc_type; + auto cum_number = (accscalar_t)init_val; + for (const auto i : c10::irange(self_dim_size)) { + accscalar_t x = self_data[i * self_dim_stride]; + + cum_number = _log_add_exp_helper(x, cum_number); + result_data[i * result_dim_stride] = static_cast(cum_number); + } + }, /*init_val=*/ -std::numeric_limits::infinity() + ); + }); +} + +void std_var_kernel_impl(TensorIterator& iter, double correction, bool take_sqrt) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.dtype(), "std_cpu", [&] { + binary_kernel_reduce( + iter, + WelfordOps< + scalar_t, + double, + int64_t, + std::tuple>{correction, take_sqrt}, + WelfordData()); + }); +} + +void prod_kernel_impl(TensorIterator& iter) { + // Workaround for the error: '*' in boolean context, suggest '&&' instead + if (iter.dtype() == ScalarType::Bool) { + using scalar_t = bool; + binary_kernel_reduce_vec( + iter, + [=](scalar_t a, scalar_t b) + -> scalar_t { return a && b; }, + [=](Vectorized a, Vectorized b) + { return a && b; }, + /*ident=*/1); + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kBFloat16, kHalf, iter.dtype(), "prod_out_cpu", [&] { + binary_kernel_reduce_vec( + iter, + [=](scalar_t a, scalar_t b) + -> scalar_t { return a * b; }, + [=](Vectorized a, Vectorized b) + { return a * b; }, + /*ident=*/1); + }); + } +} + +template +inline void norm_two_reduce_step(Vectorized& acc_vec, Vectorized& data_vec) { + acc_vec += data_vec * data_vec; +} + +template <> +inline void norm_two_reduce_step(Vectorized& acc_fvec, Vectorized& data_bvec) { + auto [data_fvec0, data_fvec1] = convert_bfloat16_float(data_bvec); + acc_fvec += data_fvec0 * data_fvec0; + acc_fvec += data_fvec1 * data_fvec1; +} + +template ::type> +void norm_kernel_cpu_impl(TensorIterator& iter, const double& val) { + // This reduction accumulates results as the type `acc_t`. + using acc_t = at::opmath_type::type>; + if (val == 0.0) { + binary_kernel_reduce(iter, NormZeroOps(), acc_t(0)); + } else if (val == 1.0) { + binary_kernel_reduce(iter, NormOneOps(), acc_t(0)); + } else if (val == 2.0) { + binary_kernel_reduce(iter, NormTwoOps(), acc_t(0)); + } else if (val == INFINITY) { + binary_kernel_reduce(iter, AbsMaxOps(), acc_t(0)); + } else if (val == -INFINITY) { + binary_kernel_reduce(iter, AbsMinOps(), std::numeric_limits::infinity()); + } else { + binary_kernel_reduce(iter, NormOps{acc_t(val)}, acc_t(0)); + } +} + +void norm_kernel_tensor_iterator_impl( + TensorIterator& iter, + const Scalar& p) { + double val = 0; + if (p.isIntegral(false)) { + val = p.to(); + } else if (p.isFloatingPoint()) { + val = p.to(); + } else { + TORCH_CHECK(false, "norm_kernel_cpu expects norm to be integer or float"); + } + if (iter.numel() == 0) { + iter.output().fill_((val < 0) ? INFINITY : 0); + return; + } + + if (val == 2.0 && is_reduce_lastdim(iter) && + iter.dtype(0) == iter.input_dtype() && + (iter.input_dtype() == kFloat || iter.input_dtype() == kDouble || + iter.input_dtype() == kBFloat16)) { + // If we can vectorize over the last dimension and the dtype + // of the output is the same as that of the input, + // then we go through the vectorised path. + AT_DISPATCH_FLOATING_TYPES_AND(kBFloat16, iter.input_dtype(), "norm_cpu", [&] { + // use float as accumulate type for BFloat16 + using acc_t = at::opmath_type; + binary_kernel_reduce_lastdim(iter, [](char* result_data_bytes, char* self_data_bytes, int64_t size) { + scalar_t* result_data = (scalar_t*)result_data_bytes; + scalar_t* self_data = (scalar_t*)self_data_bytes; + + using Vec = Vectorized; + using fVec = Vectorized; + fVec acc_vec{acc_t(0)}; + acc_t buffer[fVec::size()]; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec data_vec = Vec::loadu(self_data + d); + norm_two_reduce_step(acc_vec, data_vec); + } + acc_vec.store(buffer); + for (int j = 1; j < fVec::size(); j++) { + buffer[0] = buffer[0] + buffer[j]; + } + for (; d < size; d++) { + acc_t data_val = acc_t(self_data[d]); + buffer[0] += data_val * data_val; + } + result_data[0] = scalar_t(std::sqrt(buffer[0])); + }); + }); + } else { + if (iter.input_dtype() == kHalf && iter.dtype(0) == kFloat) { + // type promotion that does cast and reduction in a single kernel + norm_kernel_cpu_impl(iter, val); return; + } else if (iter.input_dtype() == kBFloat16 && iter.dtype(0) == kFloat) { + // type promotion that does cast and reduction in a single kernel + norm_kernel_cpu_impl(iter, val); return; + } + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3(kHalf, kBFloat16, kComplexHalf, iter.input_dtype(), "norm_cpu", [&] { + norm_kernel_cpu_impl(iter, val); + }); + + // For complex outputs, the above kernels do not touch the imaginary values, + // so we must zero them out + if (isComplexType(iter.output().scalar_type())) { + at::imag(iter.output()).zero_(); + } + } +} + +void and_kernel_impl(TensorIterator& iter) { + if (iter.dtype() == ScalarType::Byte) { + // Refer [all, any : uint8 compatibility] + binary_kernel_reduce_vec( + iter, + [=](uint8_t a, uint8_t b) -> uint8_t { return (a && b) ? 1 : 0; }, + [=](Vectorized a, Vectorized b) { + // NB: != returns 0xFF rather than 0x01, so we must negate to get + // the desired result + return (a != Vectorized(0)).neg() & (b != Vectorized(0)).neg(); + }, + /*ident=*/true); + } else { + binary_kernel_reduce_vec( + iter, + [=](bool a, bool b) -> bool { return a && b; }, + [=](Vectorized a, Vectorized b) { + // Adding the implementation here instead of in vec256_base to avoid + // return value inconsistency. Other comparison operators in + // vec256_base return -1/0 (all bit 1 / all bit 0) as true/false to + // follow the AVX2 convention. This would be convenient when combined + // with other vectorized operations. For example, one can use the + // logical operation results as a mask for a bit operation to + // retrieve/reset multiple elements in a vector. + // + // In this method, users would expect, e.g., all(), to return 1/0 as + // true/false. + Vectorized c = Vectorized(); + + for (decltype(c.size()) i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] && b[i]; + } + return c; + }, + /*ident=*/true); + } +} + +void or_kernel_impl(TensorIterator& iter) { + if (iter.dtype() == ScalarType::Byte) { + // Refer [all, any : uint8 compatibility] + binary_kernel_reduce_vec( + iter, + [=](uint8_t a, uint8_t b) -> uint8_t { return (a || b) ? 1 : 0; }, + [=](Vectorized a, Vectorized b) { + return (a != Vectorized(0)).neg() | (b != Vectorized(0)).neg(); + }, + /*ident=*/false); + } else { + binary_kernel_reduce_vec( + iter, + [=](bool a, bool b) -> bool { return a || b; }, + [=](Vectorized a, Vectorized b) { + Vectorized c = Vectorized(); + + for (decltype(c.size()) i = 0; i != Vectorized::size(); i++) { + c[i] = a[i] || b[i]; + } + return c; + }, + /*ident=*/false); + } +} + +template +struct MinValuesOps: public at::native::MinOps { + using arg_t = typename MinOps::arg_t; + static scalar_t project(arg_t arg) { + return arg.first; + } +}; + +void min_values_kernel_impl(TensorIterator& iter) { + if (iter.dtype() == kLong) { + // This case is special because of Vectorized does not + // handle upper_bound(). + // See: https://github.com/pytorch/pytorch/issues/43254 + using scalar_t = int64_t; + binary_kernel_reduce( + iter, + MinValuesOps{}, + std::pair(upper_bound(), -1)); + return; + } + AT_DISPATCH_ALL_TYPES_AND3(kBFloat16, kHalf, kBool, iter.dtype(), "min_values_cpu", [&iter] { + binary_kernel_reduce_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return min_impl(a, b); }, + [](Vectorized a, Vectorized b) { return minimum(a, b); }, + static_cast(upper_bound())); + }); +} + +void max_values_kernel_impl(TensorIterator& iter) { + AT_DISPATCH_ALL_TYPES_AND3(kBFloat16, kHalf, kBool, iter.dtype(), "max_values_cpu", [&iter] { + binary_kernel_reduce_vec( + iter, + [](scalar_t a, scalar_t b) -> scalar_t { return max_impl(a, b); }, + [](Vectorized a, Vectorized b) { return maximum(a, b); }, + lower_bound()); + }); +} + +void argmax_kernel_impl(TensorIterator &iter) { + AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, iter.dtype(1), "argmax_cpu", [&] { + if (is_reduce_lastdim(iter)) { + using arg_t = std::pair; + auto op = ArgMaxOps{}; + binary_kernel_reduce_lastdim(iter, [&](char* result_data_bytes, char* self_data_bytes, int64_t size) { + int64_t* result_data = (int64_t*)result_data_bytes; + scalar_t* self_data = (scalar_t*)self_data_bytes; + + arg_t acc = arg_t(lower_bound(), 0); + for (int64_t i = 0; i < size; i++) { + acc = op.reduce(acc, self_data[i], i); + } + result_data[0] = acc.second; + }); + return; + } + binary_kernel_reduce( + iter, + ArgMaxOps{}, + std::pair(lower_bound(), 0)); + }); +} + +void argmin_kernel_impl(TensorIterator &iter) { + AT_DISPATCH_ALL_TYPES_AND2(kHalf, kBFloat16, iter.dtype(1), "argmin_cpu", [&] { + if (is_reduce_lastdim(iter)) { + using arg_t = std::pair; + auto op = ArgMinOps{}; + binary_kernel_reduce_lastdim(iter, [&](char* result_data_bytes, char* self_data_bytes, int64_t size) { + int64_t* result_data = (int64_t*)result_data_bytes; + scalar_t* self_data = (scalar_t*)self_data_bytes; + + arg_t acc = arg_t(upper_bound(), 0); + for (int64_t i = 0; i < size; i++) { + acc = op.reduce(acc, self_data[i], i); + } + result_data[0] = acc.second; + }); + return; + } + binary_kernel_reduce( + iter, + ArgMinOps{}, + std::pair(upper_bound(), 0)); + }); +} + +template +struct XorSumOps { + inline C10_DEVICE acc_t reduce(acc_t acc, scalar_t data, int64_t /*idx*/) const { + if (std::is_same::value) { + return acc ^ (data ? 1 : 0); + } else if ( + std::is_same::value || + std::is_same::value || + std::is_same::value || + std::is_same::value) { + union { + double d; + uint64_t u; + } converter; + converter.d = static_cast(data); + return acc ^ converter.u; + } else { + return acc ^ static_cast(data); + } + } + + inline C10_DEVICE acc_t combine(acc_t a, acc_t b) const { + return a ^ b; + } + + inline C10_DEVICE out_t project(acc_t a) const { + return a; + } + + static C10_DEVICE acc_t translate_idx(acc_t acc, int64_t /*base_idx*/) { + return acc; + } +}; + +void xor_sum_kernel_impl(TensorIterator& iter) { + // Use iter.dtype(1) to dispatch based on the type of the input tensor + AT_DISPATCH_ALL_TYPES_AND3( + kBFloat16, kHalf, kBool, iter.dtype(1), "xor_sum_cpu", [&] { + binary_kernel_reduce( + iter, XorSumOps(), static_cast(0)); + }); +} + +// powsum: computes sum(|x|^p) without the final root +template ::type> +void powsum_kernel_cpu_impl(TensorIterator& iter, const double& val) { + using acc_t = at::opmath_type::type>; + if (val == 2.0) { + binary_kernel_reduce(iter, NormTwoOps(), acc_t(0)); + } else { + binary_kernel_reduce(iter, NormOps{acc_t(val)}, acc_t(0)); + } +} + +void powsum_kernel_tensor_iterator_impl( + TensorIterator& iter, + const Scalar& p) { + double val = 0; + if (p.isIntegral(false)) { + val = p.to(); + } else if (p.isFloatingPoint()) { + val = p.to(); + } else { + TORCH_CHECK(false, "powsum_kernel_cpu expects ord to be integer or float"); + } + if (iter.numel() == 0) { + iter.output().fill_(0); + return; + } + + if (val == 2.0 && is_reduce_lastdim(iter) && + iter.dtype(0) == iter.input_dtype() && + (iter.input_dtype() == kFloat || iter.input_dtype() == kDouble || + iter.input_dtype() == kBFloat16)) { + // Vectorized path for L2 powsum (no sqrt at end) + AT_DISPATCH_FLOATING_TYPES_AND(kBFloat16, iter.input_dtype(), "powsum_cpu", [&] { + using acc_t = at::opmath_type; + binary_kernel_reduce_lastdim(iter, [](char* result_data_bytes, char* self_data_bytes, int64_t size) { + scalar_t* result_data = (scalar_t*)result_data_bytes; + scalar_t* self_data = (scalar_t*)self_data_bytes; + + using Vec = Vectorized; + using fVec = Vectorized; + fVec acc_vec{acc_t(0)}; + acc_t buffer[fVec::size()]; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec data_vec = Vec::loadu(self_data + d); + norm_two_reduce_step(acc_vec, data_vec); + } + acc_vec.store(buffer); + for (int j = 1; j < fVec::size(); j++) { + buffer[0] = buffer[0] + buffer[j]; + } + for (; d < size; d++) { + acc_t data_val = acc_t(self_data[d]); + buffer[0] += data_val * data_val; + } + result_data[0] = scalar_t(buffer[0]); // No sqrt! + }); + }); + } else { + if (iter.input_dtype() == kHalf && iter.dtype(0) == kFloat) { + powsum_kernel_cpu_impl(iter, val); return; + } else if (iter.input_dtype() == kBFloat16 && iter.dtype(0) == kFloat) { + powsum_kernel_cpu_impl(iter, val); return; + } + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3(kHalf, kBFloat16, kComplexHalf, iter.input_dtype(), "powsum_cpu", [&] { + powsum_kernel_cpu_impl(iter, val); + }); + + if (isComplexType(iter.output().scalar_type())) { + at::imag(iter.output()).zero_(); + } + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(std_var_stub, &std_var_kernel_impl) +REGISTER_DISPATCH(prod_stub, &prod_kernel_impl) +// mean implementation for CPU is in aten/src/ATen/native/ReduceOps.cpp +// but mean_stub must be defined for CPU as well +REGISTER_DISPATCH(mean_stub, nullptr) +REGISTER_DISPATCH(norm_stub, &norm_kernel_tensor_iterator_impl) +REGISTER_DISPATCH(powsum_stub, &powsum_kernel_tensor_iterator_impl) +REGISTER_DISPATCH(and_stub, &and_kernel_impl) +REGISTER_DISPATCH(or_stub, &or_kernel_impl) +REGISTER_DISPATCH(min_values_stub, &min_values_kernel_impl) +REGISTER_DISPATCH(max_values_stub, &max_values_kernel_impl) +REGISTER_DISPATCH(argmax_stub, &argmax_kernel_impl) +REGISTER_DISPATCH(argmin_stub, &argmin_kernel_impl) +REGISTER_DISPATCH(xor_sum_stub, &xor_sum_kernel_impl) + +REGISTER_DISPATCH(cumprod_stub, &cumprod_cpu_kernel) +REGISTER_DISPATCH(cumsum_stub, &cumsum_cpu_kernel) +REGISTER_DISPATCH(logcumsumexp_stub, &logcumsumexp_cpu_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..8844c03026ae2cd70cf1b9b4d703366f7e83b07b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReduceUtils.h @@ -0,0 +1,237 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + +using namespace vec; + +#define AT_DISPATCH_REDUCTION_TYPES(op, ...) \ + [&] { \ + switch (op) { \ + case ReductionType::SUM: { \ + static constexpr auto reduce = ReductionType::SUM; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::MEAN: { \ + static constexpr auto reduce = ReductionType::MEAN; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::MIN: { \ + static constexpr auto reduce = ReductionType::MIN; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::MAX: { \ + static constexpr auto reduce = ReductionType::MAX; \ + return __VA_ARGS__(); \ + } \ + case ReductionType::PROD: { \ + static constexpr auto reduce = ReductionType::PROD; \ + return __VA_ARGS__(); \ + } \ + } \ + }() + +template +inline vec_scalar_t init_value() { + using acc_t = vec_scalar_t; + acc_t val; + if (reduce == ReductionType::SUM || + reduce == ReductionType::MEAN) { + val = static_cast(0); + } else if (reduce == ReductionType::PROD) { + val = static_cast(1); + } else if (reduce == ReductionType::MAX) { + val = -std::numeric_limits::infinity(); + } else { + TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN); + val = std::numeric_limits::infinity(); + } + return val; +} + +template +inline vec_scalar_t init_value(const std::optional& initial) { + using acc_t = vec_scalar_t; + if (initial.has_value()) { + return initial.value().to(); + } else { + return init_value(); + } +} + +template +inline void init(scalar_t* out, int64_t size, const vec_scalar_t& val) { + using Vec = Vectorized>; + map( + [val](Vec x) { return Vec(val); }, + out, + out, + size); +} + +template +inline void init(scalar_t* out, int64_t size, const std::optional& initial) { + using acc_t = vec_scalar_t; + acc_t val = init_value(initial); + init(out, size, val); +} + +// overload with `include_self`, used by scatter_reduce +template +inline void init(scalar_t* out, int64_t size, bool include_self = false) { + using acc_t = vec_scalar_t; + if (!include_self) { + acc_t val = init_value(); + init(out, size, val); + } +} + +template +inline void _init(scalar_t* self_ptr, at::opmath_type* buffer_ptr, int64_t size, bool include_self) { + if (!include_self) { + init, reduce>(buffer_ptr, size, include_self); + } else { + vec::convert(self_ptr, buffer_ptr, size); + } +} + +template +inline std::enable_if_t, scalar_t> +_max(const scalar_t& x, const scalar_t& y) { + return at::_isnan(y) ? y : std::max(x, y); +} + +template +inline Vectorized _max(const Vectorized& x, const Vectorized& y) { + // vec::maximum propagates NaN + return vec::maximum(x, y); +} + +template +inline std::enable_if_t, Vec2> +_max(const vec_t& x, const vec_t& y) { + // vec::maximum propagates NaN + return maximum(x, y); +} + +template +inline std::enable_if_t, scalar_t> +_min(const scalar_t& x, const scalar_t& y) { + return at::_isnan(y) ? y : std::min(x, y); +} + +template +inline Vectorized _min(const Vectorized& x, const Vectorized& y) { + // vec::minimum propagates NaN + return vec::minimum(x, y); +} + +template +inline std::enable_if_t, Vec2> +_min(const vec_t& x, const vec_t& y) { + // vec::minimum propagates NaN + return minimum(x, y); +} + +template , int> = 0> +inline void map_acc( + const Op& vec_fun, + accumut* output_data, + const accumut* input_data, + const scalar_t* input_data2, + int64_t size) { + using Vec = vec::Vectorized; + using aVec = vec::Vectorized; + int64_t d = 0; + constexpr int64_t kVecSize = Vec::size(); + constexpr int64_t kaVecSize = aVec::size(); + for (d = 0; d < size - (size % kVecSize); d += kVecSize) { + Vec data2_vec = Vec::loadu(input_data2 + d); + auto [data2_avec0, data2_avec1] = convert_to_float(data2_vec); + aVec input_vec0 = aVec::loadu(input_data + d); + aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize); + vec_fun(input_vec0, data2_avec0).store(output_data + d); + vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize); + } + if (size - d > 0) { + int64_t tail_size = size - d; + Vec data2_vec = Vec::loadu(input_data2 + d, tail_size); + auto [data2_avec0, data2_avec1] = convert_to_float(data2_vec); + if (tail_size > kaVecSize) { + aVec input_vec0 = aVec::loadu(input_data + d); + aVec input_vec1 = aVec::loadu(input_data + d + kaVecSize, tail_size - kaVecSize); + vec_fun(input_vec0, data2_avec0).store(output_data + d); + vec_fun(input_vec1, data2_avec1).store(output_data + d + kaVecSize, tail_size - kaVecSize); + } else { + aVec input_vec0 = aVec::loadu(input_data + d, tail_size); + vec_fun(input_vec0, data2_avec0).store(output_data + d, tail_size); + } + } +} + +// for Max and Min, propagate NaN: +template +inline T update(const T& x, const T& y) { + if (reduce == ReductionType::SUM || + reduce == ReductionType::MEAN) { + return x + y; + } else if (reduce == ReductionType::PROD) { + return x * y; + } else if (reduce == ReductionType::MAX) { + return _max(x, y); + } else { + TORCH_INTERNAL_ASSERT(reduce == ReductionType::MIN); + return _min(x, y); + } +} + +template +inline void update(scalar_t* out, const scalar_t* data, int64_t K) { + using Vec = vec::Vectorized>; + map2( + [](Vec x, Vec y) { return update(x, y); }, + out, + out, + data, + K); +} + +template , int> = 0> +inline void update(at::opmath_type* out, const scalar_t* data, int64_t K) { + using opmath_t = at::opmath_type; + using Vec = vec::Vectorized; + map_acc( + [](Vec x, Vec y) { return update(x, y); }, + out, + out, + data, + K); +} + +template +inline void write(scalar_t* out, int64_t count, int64_t K) { + using Vec = vec::Vectorized>; + if (reduce == ReductionType::MEAN) { + if (count > 0) { + vec::map( + [count](Vec x) { return x / Vec(count); }, + out, + out, + K); + } + } +} + +} // namespace CPU_CAPABILITY +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14a0bd9b6ca5ce6274c9b5c48ad8538d93817617 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.cpp @@ -0,0 +1,502 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__aarch64__) && !defined(C10_MOBILE) +#include +#include +#endif + +namespace at::native { +inline namespace CPU_CAPABILITY { +#if !defined(C10_MOBILE) + +constexpr auto kF32RegisterPairsPerIteration = 4; +constexpr auto kF32RegistersPerIteration = kF32RegisterPairsPerIteration * 2; +constexpr auto kF32ElementsPerRegister = vec::Vectorized::size(); +constexpr auto kF32ElementsPerIteration = kF32RegistersPerIteration * kF32ElementsPerRegister; + +namespace { +template +constexpr int IntegerLog2(T n, int p = 0) { + return (n <= 1) ? p : IntegerLog2(n / 2, p + 1); +} +} // namespace + +/* + * NOTE [ GGML Copyright Notice ] + * The below reduce overload and fp16_dot_with_fp16_arith function is + * adapted from llama.cpp's ggml_vec_dot_f16 and surrounding utility + * functions, so here is the required copyright notice: + * + * MIT License + * + * Copyright (c) 2023-2024 The ggml authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#if !defined(__aarch64__) || defined( __ARM_FEATURE_FP16_SCALAR_ARITHMETIC) +constexpr auto kF16RegistersPerIteration = 16; +constexpr auto kF16ElementsPerRegister = vec::Vectorized::size(); +constexpr auto kF16ElementsPerIteration = kF16RegistersPerIteration * kF16ElementsPerRegister; + +float reduce(vec::VectorizedN& x) { + int offset = kF16RegistersPerIteration; + c10::ForcedUnroll{}([&offset, &x](auto idx) { + offset /= 2; + for (const auto i : c10::irange(offset)) { + x[i] = x[i] + x[offset + i]; + } + }); + const auto [t0, t1] = vec::convert_half_float(x[0]); + return vec::vec_reduce_all( + std::plus>(), + t0 + t1); +} + +float fp16_dot_with_fp16_arith(const Half* x, const Half* a, int len) { + vec::VectorizedN sum(0); + + const auto len_aligned = len & ~(kF16ElementsPerIteration - 1); + for (int j = 0; j < len_aligned ; j += kF16ElementsPerIteration) { + for (const auto k : c10::irange(kF16RegistersPerIteration)) { + const auto temp_x = vec::Vectorized::loadu(x + j + k * vec::Vectorized::size()); + const auto temp_a = vec::Vectorized::loadu(a + j + k * vec::Vectorized::size()); + sum[k] = vec::fmadd(temp_x, temp_a, sum[k]); + } + } + auto reduced_sum = reduce(sum); + + for (const auto j : c10::irange(len_aligned, len)) { + reduced_sum += x[j] * a[j]; + } + return reduced_sum; +} + +// Rather than unrolling to process multiple rows (transposed columns) +// of matrix A at once as done in fp16_gemv_trans_fp16_arith, unroll +// along an individual dot product. +static void fp16_gemv_trans_fp16_arith_by_dot_products(const int m, const int n, const Half* a, const int64_t lda, const Half *x, const float beta, Half* y, int incy) { + if (beta == 0.0f) { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + y[i * incy] = fp16_dot_with_fp16_arith(x, a + lda * i, m); + } + }); + } else if (beta == 1.0f) { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + y[i * incy] += fp16_dot_with_fp16_arith(x, a + lda * i, m); + } + }); + } else { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + y[i * incy] = beta * y[i * incy] + fp16_dot_with_fp16_arith(x, a + lda * i, m); + } + }); + } +} + +#endif // !defined(__aarch64__) || defined( __ARM_FEATURE_FP16_SCALAR_ARITHMETIC) + +float reduce(vec::Vectorized x) { + return vec::vec_reduce_all( + std::plus>(), + x); +} + +// The below reduce overload and fp16_dot_with_fp32_arith are adapted +// from llama.cpp's ggml_vec_dot_f32 and surrounding utility +// functions. See NOTE [ GGML Copyright Notice ] above for the +// required notice. +float reduce(vec::VectorizedN& x) { + int offset = kF32RegistersPerIteration; + c10::ForcedUnroll{}([&offset, &x](auto idx) { + offset /= 2; + for (const auto i : c10::irange(offset)) { + x[i] = x[i] + x[offset + i]; + } + }); + return reduce(x[0]); +} + +// We would have to write a separate SVE-specific path to use SVE +// BFDOT. Deferring that for now to get the NEON/ASIMD BFDOT path +// working. +#if __ARM_FEATURE_BF16_VECTOR_ARITHMETIC +#if defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256) && defined(__clang__) && __clang_major__ > 15 +// https://godbolt.org/z/z8P4Yncra +#define COMPILER_SUPPORTS_BF16_TARGET 1 +#elif defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256) && !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 10 +// https://gcc.gnu.org/gcc-10/changes.html +// https://godbolt.org/z/cdGG7vn8o +#define COMPILER_SUPPORTS_BF16_TARGET 1 +#else // defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256) && defined(__clang__) && __clang_major__ > 15 +#define COMPILER_SUPPORTS_BF16_TARGET 0 +#endif // defined(__aarch64__) && !defined(CPU_CAPABILITY_SVE256) && defined(__clang__) && __clang_major__ > 15 +#else // __ARM_FEATURE_BF16_VECTOR_ARITHMETIC +#define COMPILER_SUPPORTS_BF16_TARGET 0 +#endif // __ARM_FEATURE_BF16_VECTOR_ARITHMETIC + +#if COMPILER_SUPPORTS_BF16_TARGET +#define TARGET_ARM_BF16_ATTRIBUTE __attribute__((target("arch=armv8.2-a+bf16"))) + +TARGET_ARM_BF16_ATTRIBUTE C10_ALWAYS_INLINE void +dot_with_fp32_arith_main_inner_loop_bfdot( + const BFloat16* vec1, + const BFloat16* vec2, + vec::VectorizedN& sum, + int registerPairIndex) { + // NOTE[Intrinsics in bfdot variant]: We can't use + // vec::Vectorized::loadu here because linux-aarch64 GCC + // inexplicably can't convert Vectorized to + // bfloat16x8_t. I suspect a bug or incomplete + // __attribute__((target)) implementation. Intrinsics should be fine + // because we're using vbfdotq_f32 below anyway. + const auto temp_vec1 = vld1q_bf16( + reinterpret_cast( + &vec1[registerPairIndex * vec::Vectorized::size()])); + const auto temp_vec2 = vld1q_bf16( + reinterpret_cast( + &vec2[registerPairIndex * vec::Vectorized::size()])); + sum[registerPairIndex] = + vbfdotq_f32(sum[registerPairIndex], temp_vec1, temp_vec2); +} + +TARGET_ARM_BF16_ATTRIBUTE C10_ALWAYS_INLINE +void dot_with_fp32_arith_vectorized_tail_inner_loop_bfdot( + const at::BFloat16* vec1, + const at::BFloat16* vec2, + vec::Vectorized* tail_sum, + int idx) { + // See NOTE[Intrinsics in bfdot variant] above. + const auto temp_vec1 = vld1q_bf16(reinterpret_cast(&vec1[idx])); + const auto temp_vec2 = vld1q_bf16(reinterpret_cast(&vec2[idx])); + *tail_sum = vbfdotq_f32(*tail_sum, temp_vec1, temp_vec2); +} + +#else +#define TARGET_ARM_BF16_ATTRIBUTE +#endif // COMPILER_SUPPORTS_BF16_TARGET + +namespace { +// Returns (acc_low + a_low_half * b_low_half, acc_high + a_high_half * b_high_half) +std::pair, vec::Vectorized> fmadd( + const vec::Vectorized& a, + const vec::Vectorized& b, + const vec::Vectorized& acc_low, + const vec::Vectorized& acc_high) { +#if defined(__ARM_FEATURE_FP16_FML) && !defined(CPU_CAPABILITY_SVE256) + return std::make_pair(vfmlalq_low_f16(acc_low, a, b), vfmlalq_high_f16(acc_high, a, b)); +#else + const auto [a_float_low, a_float_high] = convert_half_float(a); + const auto [b_float_low, b_float_high] = convert_half_float(b); + return std::make_pair(fmadd(a_float_low, b_float_low, acc_low), fmadd(a_float_high, b_float_high, acc_high)); +#endif +} + +[[maybe_unused]] std::pair, vec::Vectorized> fmadd( + const vec::Vectorized& a, + const vec::Vectorized& b, + const vec::Vectorized& acc_low, + const vec::Vectorized& acc_high) { + const auto [a_float_low, a_float_high] = convert_bfloat16_float(a); + const auto [b_float_low, b_float_high] = convert_bfloat16_float(b); + return std::make_pair(fmadd(a_float_low, b_float_low, acc_low), fmadd(a_float_high, b_float_high, acc_high)); +} + +// Return a + b_low * c_low + b_high * c_high +vec::Vectorized fmadd(vec::Vectorized a, vec::Vectorized b, vec::Vectorized c) { +#if defined(__aarch64__) && defined(__ARM_FEATURE_FP16_FML) && !defined(__ARM_FEATURE_SVE256) + // NOTE: this instruction is an optional instruction in ARM v8.2 and + // v8.3, but mandatory in v8.4 per + // https://developer.arm.com/documentation/ddi0596/2021-03/SIMD-FP-Instructions/FMLAL--FMLAL2--vector---Floating-point-fused-Multiply-Add-Long-to-accumulator--vector--?lang=en + // I'm not certain that I have the right feature test macro. + vec::Vectorized first = vfmlalq_low_f16(a, b, c); + return vfmlalq_high_f16(first, b, c); +#else + const auto [b_float_low, b_float_high] = convert_half_float(b); + const auto [c_float_low, c_float_high] = convert_half_float(c); + const auto first = vec::fmadd(b_float_low, c_float_low, a); + return vec::fmadd(b_float_high, c_float_high, first); +#endif +} + +[[maybe_unused]] vec::Vectorized fmadd( + const vec::Vectorized& acc, + const vec::Vectorized& a, + const vec::Vectorized& b) { + const auto [a_float_low, a_float_high] = convert_bfloat16_float(a); + const auto [b_float_low, b_float_high] = convert_bfloat16_float(b); + return fmadd(a_float_high, b_float_high, fmadd(a_float_low, b_float_low, acc)); +} +} // namespace + +template +C10_ALWAYS_INLINE void dot_with_fp32_arith_main_inner_loop_no_bfdot( + const T* vec1, + const T* vec2, + vec::VectorizedN& sum, + int registerPairIndex) { + static_assert(std::is_same_v || std::is_same_v); + const auto temp_vec1 = vec::Vectorized::loadu(&vec1[registerPairIndex * vec::Vectorized::size()]); + const auto temp_vec2 = vec::Vectorized::loadu(&vec2[registerPairIndex * vec::Vectorized::size()]); + + const auto [result_low, result_high] = fmadd(temp_vec1, temp_vec2, sum[2 * registerPairIndex], sum[2 * registerPairIndex + 1]); + sum[2 * registerPairIndex] = result_low; + sum[2 * registerPairIndex + 1] = result_high; +} + +template +C10_ALWAYS_INLINE void dot_with_fp32_arith_vectorized_tail_inner_loop_no_bfdot( + const T* vec1, + const T* vec2, + vec::Vectorized* tail_sum, + int idx) { + const auto temp_vec1 = vec::Vectorized::loadu(&vec1[idx]); + const auto temp_vec2 = vec::Vectorized::loadu(&vec2[idx]); + *tail_sum = fmadd(*tail_sum, temp_vec1, temp_vec2); +} + +template +C10_ALWAYS_INLINE auto +dot_with_fp32_arith_main_loop_no_bfdot( + const T* vec1, + const T* vec2, + int64_t len) { + vec::VectorizedN sum(0); + const auto len_aligned = len & ~(kF32ElementsPerIteration - 1); + for (int j = 0; j < len_aligned ; j += kF32ElementsPerIteration) { + const auto* vec1_ = vec1 + j; + const auto* vec2_ = vec2 + j; + c10::ForcedUnroll{}([vec1_, vec2_, &sum](auto k) C10_ALWAYS_INLINE_ATTRIBUTE { + dot_with_fp32_arith_main_inner_loop_no_bfdot(vec1_, vec2_, sum, k); + }); + } + return reduce(sum); +} + +#if COMPILER_SUPPORTS_BF16_TARGET +template +struct ForcedUnrollTargetBFloat16 { + template + TARGET_ARM_BF16_ATTRIBUTE C10_ALWAYS_INLINE void operator()(const Func& f) const { + ForcedUnrollTargetBFloat16{}(f); + f(n - 1); + } +}; + +template <> +struct ForcedUnrollTargetBFloat16<1> { + template + TARGET_ARM_BF16_ATTRIBUTE C10_ALWAYS_INLINE void operator()(const Func& f) const { + f(0); + } +}; + +C10_ALWAYS_INLINE TARGET_ARM_BF16_ATTRIBUTE auto +dot_with_fp32_arith_main_loop_bfdot( + const BFloat16* vec1, + const BFloat16* vec2, + int64_t len) { + vec::VectorizedN sum(0); + const auto len_aligned = len & ~(kF32ElementsPerIteration - 1); + for (int j = 0; j < len_aligned ; j += kF32ElementsPerIteration) { + const auto* vec1_ = vec1 + j; + const auto* vec2_ = vec2 + j; + ForcedUnrollTargetBFloat16{}([vec1_, vec2_, &sum](auto k) + C10_ALWAYS_INLINE_ATTRIBUTE TARGET_ARM_BF16_ATTRIBUTE { + dot_with_fp32_arith_main_inner_loop_bfdot(vec1_, vec2_, sum, k); + }); + } + return reduce(sum); +} +#endif // COMPILER_SUPPORTS_BF16_TARGET + +static_assert( + (vec::Vectorized::size() & (vec::Vectorized::size() - 1)) == 0, + "Below code expects power-of-2 vector register size!"); + +// NOTE [GCC code duplication]: The first attempt at landing BFDOT support with +// TARGET_ARM_BF16_ATTRIBUTE failed because unlike clang, GCC will not +// allow inlining a non-bf16-specific function into a bf16-specific +// function. We can work around this by duplicating the code into the +// bfdot and non-bfdot callsites. The code is in this macro to avoid +// actual copy/paste. +#define DOT_WITH_FP32_ARITH_TAIL_AFTER_MAIN_LOOP_BODY(bfdot_suffix) \ + /* First-tier tail fixup: make sure we handle workloads that can */ \ + /* benefit from vectorization, but don't fit into our fully unrolled */ \ + /* loop above. */ \ + vec::Vectorized tail_sum(0); \ + const auto len_aligned = len & ~(kF32ElementsPerIteration - 1); \ + const auto len_aligned_vec = len & ~(vec::Vectorized::size() - 1); \ + for (int j = len_aligned; j < len_aligned_vec; j += vec::Vectorized::size()) { \ + dot_with_fp32_arith_vectorized_tail_inner_loop##bfdot_suffix(vec1, vec2, &tail_sum, j); \ + } \ + reduced_sum += reduce(tail_sum); \ + \ + /* Second-tier tail fixup: handle all workloads. */ \ + for (const auto j : c10::irange(len_aligned_vec, len)) { \ + /* Attempting to use Half here caused multiple test failures; */ \ + /* using float to unbreak. (Suspect we need a scalar FMA.) */ \ + float x1 = vec1[j]; \ + float x2 = vec2[j]; \ + reduced_sum += x1 * x2; \ + } \ + return reduced_sum + +#if COMPILER_SUPPORTS_BF16_TARGET +TARGET_ARM_BF16_ATTRIBUTE float +dot_with_fp32_arith_bfdot(const BFloat16* vec1, const BFloat16* vec2, int64_t len) { + auto reduced_sum = dot_with_fp32_arith_main_loop_bfdot(vec1, vec2, len); + DOT_WITH_FP32_ARITH_TAIL_AFTER_MAIN_LOOP_BODY(_bfdot); +} +#endif // COMPILER_SUPPORTS_BF16_TARGET + +template +C10_ALWAYS_INLINE float +dot_with_fp32_arith_no_bfdot(const T* vec1, const T* vec2, int64_t len) { + auto reduced_sum = dot_with_fp32_arith_main_loop_no_bfdot(vec1, vec2, len); + DOT_WITH_FP32_ARITH_TAIL_AFTER_MAIN_LOOP_BODY(_no_bfdot); +} +#undef DOT_WITH_FP32_ARITH_TAIL_AFTER_MAIN_LOOP_BODY + +float fp16_dot_with_fp32_arith(const Half* vec1, const Half* vec2, int64_t len) { + return dot_with_fp32_arith_no_bfdot(vec1, vec2, len); +} + +void fp16_gemv_trans_fp32_arith_by_dot_products(const int m, const int n, const Half* a, const int64_t lda, const Half *x, const float beta, Half* y, int incy) { + if (beta == 0.0f) { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + y[i * incy] = fp16_dot_with_fp32_arith(x, a + lda * i, m); + } + }); + } else if (beta == 1.0f) { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + // We need to accumulate in fp32; y[i * incy] += ... gets wrong results. + y[i * incy] = static_cast(y[i * incy]) + fp16_dot_with_fp32_arith(x, a + lda * i, m); + } + }); + } else { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + y[i * incy] = beta * y[i * incy] + fp16_dot_with_fp32_arith(x, a + lda * i, m); + } + }); + } +} + +void fp16_gemv_trans( + const int m, + const int n, + const float alpha, + const Half* a, + const int lda, + const Half* x, + const int incx, + const float beta, + Half* y, + const int incy) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(incx == 1 && alpha == 1.0); +#if !defined(__aarch64__) || defined(__ARM_FEATURE_FP16_SCALAR_ARITHMETIC) + if (at::globalContext().allowFP16ReductionCPU()) { + fp16_gemv_trans_fp16_arith_by_dot_products(m, n, a, lda, x, beta, y, incy); + return; + } +#endif + fp16_gemv_trans_fp32_arith_by_dot_products(m, n, a, lda, x, beta, y, incy); +} + +float bf16_dot_with_fp32_arith(const at::BFloat16* vec1, const at::BFloat16* vec2, int64_t len) { +#if COMPILER_SUPPORTS_BF16_TARGET + if (cpuinfo_has_arm_bf16()) { + return dot_with_fp32_arith_bfdot(vec1, vec2, len); + } else +#endif // COMPILER_SUPPORTS_BF16_TARGET + { + return dot_with_fp32_arith_no_bfdot(vec1, vec2, len); + } +} + +void bf16_gemv_trans_fp32_arith_by_dot_products(const int m, const int n, const at::BFloat16* a, const int64_t lda, const at::BFloat16 *x, at::BFloat16* y, int incy) { + parallel_for(0, n, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + y[i * incy] = bf16_dot_with_fp32_arith(x, a + lda * i, m); + } + }); +} + +void bf16_gemv_trans( + const int m, + const int n, + const at::BFloat16 alpha, + const at::BFloat16* a, + const int lda, + const at::BFloat16* x, + const int incx, + const at::BFloat16 beta, + at::BFloat16* y, + const int incy) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(incx == 1 && alpha == 1.0 && beta == 0.0); + bf16_gemv_trans_fp32_arith_by_dot_products(m, n, a, lda, x, y, incy); +} + +float fp16_dot( + const int64_t n, + const at::Half* x, + const int64_t incx, + const at::Half* y, + const int64_t incy) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(incx == 1 && incy == 1); + return fp16_dot_with_fp32_arith(x, y, n); +} + +float bf16_dot( + const int64_t n, + const at::BFloat16* x, + const int64_t incx, + const at::BFloat16* y, + const int64_t incy) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(incx == 1 && incy == 1); + return bf16_dot_with_fp32_arith(x, y, n); +} + +#endif // !defined(C10_MOBILE) +} // namespace CPU_CAPABILITY + +#if !defined(C10_MOBILE) +REGISTER_DISPATCH(fp16_gemv_trans_stub, &fp16_gemv_trans) +REGISTER_DISPATCH(bf16_gemv_trans_stub, &bf16_gemv_trans) +REGISTER_DISPATCH(fp16_dot_stub, &fp16_dot) +REGISTER_DISPATCH(bf16_dot_stub, &bf16_dot) +#endif //!defined(C10_MOBILE) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..006ff75f72716d7f57865d036d3d7a02a2298b28 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ReducedPrecisionFloatGemvFastPathKernel.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include + +namespace at::native { +#if !defined(C10_MOBILE) +using fp16_gemv_fn = void(*)(int, int, float, const Half*, int, const Half*, int, float, Half*, int); +DECLARE_DISPATCH(fp16_gemv_fn, fp16_gemv_trans_stub) + +using bf16_gemv_fn = void(*)(int, int, BFloat16, const BFloat16*, int, const BFloat16*, int, BFloat16, BFloat16*, int); +DECLARE_DISPATCH(bf16_gemv_fn, bf16_gemv_trans_stub) + +using fp16_dot_fn = float(*)(const int64_t, const Half*, const int64_t, const Half*, const int64_t); +DECLARE_DISPATCH(fp16_dot_fn, fp16_dot_stub) + +using bf16_dot_fn = float(*)(const int64_t, const BFloat16*, const int64_t, const BFloat16*, const int64_t); +DECLARE_DISPATCH(bf16_dot_fn, bf16_dot_stub) + +inline namespace CPU_CAPABILITY { +float fp16_dot_with_fp32_arith(const Half* vec1, const Half* vec2, int64_t len); +float bf16_dot_with_fp32_arith(const BFloat16* vec1, const BFloat16* vec2, int64_t len); +} // inline namespace CPU_CAPABILITY +#endif // !defined(C10_MOBILE) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/RenormKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/RenormKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb8909b1576137f7d29359bf0ec8cbf5e3ebbaea --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/RenormKernel.cpp @@ -0,0 +1,38 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +#include + +#include + +namespace at::native { +namespace { + +void renorm_scale_factor_impl(TensorIteratorBase& iter, double maxnorm) { + AT_DISPATCH_FLOATING_TYPES(iter.common_dtype(), "renorm_scale_factor_cpu", [&] { + using vec_t = at::vec::Vectorized; + const auto maxnorm_s = static_cast(maxnorm); + const auto maxnorm_v = vec_t(maxnorm_s); + const auto eps_v = vec_t(static_cast(1e-7)); + const auto one_v = vec_t(1.0); + cpu_kernel_vec( + iter, + [maxnorm_s](scalar_t norm) -> scalar_t { + const auto eps = static_cast(1e-7); + return (norm > maxnorm_s) ? + maxnorm_s / (norm + eps) : static_cast(1.0); + }, + [maxnorm_v, eps_v, one_v](vec_t norm) -> vec_t { + auto fct = maxnorm_v / (norm + eps_v); + return vec_t::blendv(one_v, fct, norm > maxnorm_v); + }); + }); +} + +} // namespace (anonymous) + +REGISTER_DISPATCH(renorm_scale_factor_stub, &renorm_scale_factor_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SampledAddmmKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SampledAddmmKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8db9785f404a7b3dcf356f1c0302e444078ac4f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SampledAddmmKernel.cpp @@ -0,0 +1,99 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void sampled_addmm_sparse_csr_kernel_impl( + const Tensor& mat1, + const Tensor& mat2, + const Scalar& beta, + const Scalar& alpha, + const Tensor& result) { + + int64_t nnz = result._nnz(); + + auto beta_ = beta.to(); + auto alpha_ = alpha.to(); + + const scalar_t* mat1_data = mat1.const_data_ptr(); + const scalar_t* mat2_data = mat2.const_data_ptr(); + + // mat1: {B, M, K} + // mat2: {B, N, K} + // crow: {B, M + 1} + // col, values: {B, nnz} + int64_t M = mat1.size(-2); + int64_t K = mat1.size(-1); + int64_t N = mat2.size(-2); + int64_t B = mat1.numel() / M / K; + + auto values = result.values().reshape({-1, nnz}); + auto crow = result.crow_indices().reshape({-1, M + 1}); + auto col = result.col_indices().reshape({-1, nnz}); + + auto values_acc = values.accessor(); + auto crow_acc = crow.accessor(); + auto col_acc = col.accessor(); + + // usually, collapse B and M is a better option, + // but for most commonly used case (mat1 and mat2 is 2d tensor), B = 1, + // balance partition M by using parallel_sparse_csr. + using Vec = vec::Vectorized; + for (const auto b : c10::irange(B)) { + auto crow_slice = crow_acc[b]; + auto col_slice = col_acc[b]; + auto values_slice = values_acc[b]; + const scalar_t* mat1_ptr = mat1_data + b * M * K; + const scalar_t* mat2_ptr = mat2_data + b * N * K; + + utils::parallel_sparse_csr(crow_slice, M, nnz, [&](int64_t begin, int64_t end) { + for (const auto m : c10::irange(begin, end)) { + int64_t row_start = crow_slice[m]; + int64_t row_end = crow_slice[m + 1]; + for (const auto e : c10::irange(row_start, row_end)) { + int64_t n = col_slice[e]; + scalar_t val = values_slice[e]; + scalar_t dot = vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + mat1_ptr + m * K, + mat2_ptr + n * K, + K); + val = alpha_ * dot + beta_ * val; + values_slice[e] = val; + } + } + }); + } +} + +void sampled_addmm_sparse_csr_kernel( + const Tensor& mat1, + const Tensor& mat2, + const Scalar& beta, + const Scalar& alpha, + const Tensor& result) { + const auto index_type = result.crow_indices().scalar_type(); + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(mat1.scalar_type(), "sampled_addmm_sparse_csr_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(index_type, "sampled_addmm_sparse_csr_index", [&]() { + sampled_addmm_sparse_csr_kernel_impl(mat1, mat2, beta, alpha, result); + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(sampled_addmm_sparse_csr_stub, &sampled_addmm_sparse_csr_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SampledAddmmKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SampledAddmmKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..29479c8211d20d67c9c2f7b18989a9f1418695f2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SampledAddmmKernel.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace at::native { + +using sampled_addmm_sparse_csr_fn = void(*)(const Tensor&, const Tensor&, const Scalar&, const Scalar&, const Tensor&); + +DECLARE_DISPATCH(sampled_addmm_sparse_csr_fn, sampled_addmm_sparse_csr_stub) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ScatterGatherKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ScatterGatherKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..783df48cce1b815b38965a0828924cfacf1e9e39 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/ScatterGatherKernel.cpp @@ -0,0 +1,1208 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_FBGEMM +#include +#endif +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +#ifdef _OPENMP +#include +#else +#define omp_get_max_threads() 1 +#define omp_get_num_threads() 1 +#define omp_get_thread_num() 0 +#endif + +namespace at::native { + +namespace { + +// Implement as functors since lambdas don't get optimized. +class ReduceMultiply { +public: + template + constexpr void operator() (at::opmath_type * self_data, scalar_t * src_data) const { + using opmath_t = at::opmath_type; + *self_data *= opmath_t(c10::load(src_data)); + } + + constexpr void operator() (bool * self_data, bool * src_data) const { + *self_data = c10::load(self_data) && c10::load(src_data); + } +}; +ReduceMultiply reduce_multiply; + +class ReduceAdd { +public: + template + constexpr void operator() (at::opmath_type * self_data, scalar_t * src_data) const { + using opmath_t = at::opmath_type; + *self_data += opmath_t(c10::load(src_data)); + } +}; +ReduceAdd reduce_add; + +class ReduceMean { +public: + template + constexpr void operator() (at::opmath_type * self_data, scalar_t * src_data) const { + using opmath_t = at::opmath_type; + *self_data += opmath_t(c10::load(src_data)); + } +}; +ReduceMean reduce_mean; + +class ReduceMaximum { +public: + template + constexpr void operator() (at::opmath_type * self_data, scalar_t * src_data) const { + using opmath_t = at::opmath_type; + auto self_value = c10::load(self_data); + auto src_value = c10::load(src_data); + *self_data = at::_isnan(src_value) ? opmath_t(src_value) : std::max(self_value, opmath_t(src_value)); + } +}; +ReduceMaximum reduce_maximum; + +class ReduceMinimum { +public: + template + constexpr void operator() (at::opmath_type * self_data, scalar_t * src_data) const { + using opmath_t = at::opmath_type; + auto self_value = c10::load(self_data); + auto src_value = c10::load(src_data); + *self_data = at::_isnan(src_value) ? opmath_t(src_value) : std::min(self_value, opmath_t(src_value)); + } +}; +ReduceMinimum reduce_minimum; + +class TensorAssign { +public: + template + constexpr void operator() (at::opmath_type * self_data, scalar_t * src_data) const { + using opmath_t = at::opmath_type; + *self_data = opmath_t(c10::load(src_data)); + } +}; +TensorAssign tensor_assign; + +template +struct _cpu_scatter_gather_dim_loop { + template + void operator()( + at::opmath_type* self_data, int64_t self_dim_stride, + int64_t* index_data, int64_t index_dim_stride, + scalar_t* src_data, int64_t src_dim_stride, + int64_t dim, int64_t index_dim_size, + int64_t index_upper_bound, + func_t& f + ) { + + for (const auto i : c10::irange(index_dim_size)) { + int64_t idx_dim = index_data[i * index_dim_stride]; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", index_data[i * index_dim_stride], + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound + ); + + f( + self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, + src_data + (is_scatter_like ? i : idx_dim) * src_dim_stride + ); + } + } + + template + void operator()( + at::opmath_type* self_data, int64_t self_dim_stride, + int64_t* index_data, int64_t index_dim_stride, + Scalar value, + int64_t dim, int64_t index_dim_size, + int64_t index_upper_bound, + func_t& f + ) { + + for (const auto i : c10::irange(index_dim_size)) { + int64_t idx_dim = index_data[i * index_dim_stride]; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", index_data[i * index_dim_stride], + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound + ); + auto temp = value.to(); + f( + self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, &temp + ); + } + } +}; + +inline void create_acc_buffer(Tensor& buffer, const Tensor& self, bool need_acc) { + if (need_acc) { + auto acc_type = at::toOpMathType(self.scalar_type()); + buffer = at::empty(self.sizes(), self.options().dtype(acc_type)); + buffer.copy_(self); + } else { + buffer = self; + } +} + +template +struct cpu_scatter_gather_base_kernel { + template + void operator()(const Tensor& self, int64_t dim, + const Tensor& _index, const Scalar& value, + const std::string& method_name, func_t& kernel_func) { + + Tensor buffer; + Tensor index = _index.to(ScalarType::Long); + bool need_acc = isReducedFloatingType(self.scalar_type()); + create_acc_buffer(buffer, self, need_acc); + + auto index_sizes = ensure_nonempty_vec(index.sizes().vec()); + auto index_strides = ensure_nonempty_vec(index.strides().vec()); + + // `dim` is traversed in the kernel, + // that is why index.stride(dim) = 0 and index.size(dim) = 1. + // Also, index.size(dim) = 1 makes sure that TensorIterator.DimCounter + // has the following form : (i_1,..., i_{dim-1}, 0, i_{dim+1},...,i_n). + index_sizes[dim] = 1; + index_strides[dim] = 0; + + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(index.sizes(), /*squash_dims=*/dim) + .add_output(buffer) + .add_const_input(index) + .build(); + + auto self_dim_stride = ensure_nonempty_stride(buffer, dim); + auto self_dim_size = ensure_nonempty_size(buffer, dim); + + auto index_dim_stride = ensure_nonempty_stride(index, dim); + auto index_dim_size = ensure_nonempty_size(index, dim); + + auto index_upper_bound = self_dim_size; + + // since the index dimension is squashed, need to alter the grain size according + // to keep equal granularity in parallelism. + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / index_dim_size); + + AT_DISPATCH_V2( + self.scalar_type(), + "scatter_gather_scalar_cpu", + AT_WRAP([&] { + constexpr auto SELF_ITER_STRIDE_IDX = 0; + constexpr auto INDEX_ITER_STRIDE_IDX = 1; + using opmath_t = at::opmath_type; + _cpu_scatter_gather_dim_loop loop_func; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[SELF_ITER_STRIDE_IDX]; + auto* index_data_bytes = data[INDEX_ITER_STRIDE_IDX]; + // we change the order of TensorIterator-dim loop + // vs dim-TensorIterator loop order depending on + // whether dim is the last dimension + if (dim== buffer.dim() - 1) { + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + // dim loop is a separate code block + // for better performance + loop_func.template operator()( + (opmath_t*)self_data_bytes, self_dim_stride, + (int64_t*)index_data_bytes, index_dim_stride, + value, dim, index_dim_size, index_upper_bound, + kernel_func); + + self_data_bytes += strides[SELF_ITER_STRIDE_IDX]; + index_data_bytes += strides[INDEX_ITER_STRIDE_IDX]; + } + } + else { + for (const auto i : c10::irange(index_dim_size)) { + auto* self_data = self_data_bytes; + auto* index_data = (char*)((int64_t*)index_data_bytes + i * index_dim_stride); + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + int64_t idx_dim = *(int64_t*)index_data; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", *(int64_t*)index_data, + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound); + + auto temp = value.to(); + kernel_func((opmath_t*)self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, &temp); + + self_data += strides[SELF_ITER_STRIDE_IDX]; + index_data += strides[INDEX_ITER_STRIDE_IDX]; + } + } + } + }; + iter.for_each(loop, grain_size); + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), + kBool, kHalf, kBFloat16); + if (need_acc) { + self.copy_(buffer); + } + } + + template + void operator()(const Tensor& self, int64_t dim, + const Tensor& _index, const Tensor& src, + const std::string& method_name, func_t& kernel_func) { + + Tensor buffer; + Tensor index = _index.to(ScalarType::Long); + bool need_acc = isReducedFloatingType(self.scalar_type()); + create_acc_buffer(buffer, self, need_acc); + + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(index.sizes(), /*squash_dims=*/dim) + .add_output(buffer) + .add_const_input(src) + .add_const_input(index) + .build(); + + auto self_dim_stride = ensure_nonempty_stride(buffer, dim); + auto self_dim_size = ensure_nonempty_size(buffer, dim); + + auto index_dim_stride = ensure_nonempty_stride(index, dim); + auto index_dim_size = ensure_nonempty_size(index, dim); + + auto src_dim_stride = ensure_nonempty_stride(src, dim); + auto src_dim_size = ensure_nonempty_size(src, dim); + + auto index_upper_bound = is_scatter_like ? self_dim_size : src_dim_size; + + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / index_dim_size); + + AT_DISPATCH_V2( + iter.dtype(1), + "scatter_gather_tensor_cpu", + AT_WRAP([&] { + constexpr auto SELF_ITER_STRIDE_IDX = 0; + constexpr auto INDEX_ITER_STRIDE_IDX = 2; + constexpr auto SRC_ITER_STRIDE_IDX = 1; + using opmath_t = at::opmath_type; + _cpu_scatter_gather_dim_loop loop_func; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[SELF_ITER_STRIDE_IDX]; + auto* index_data_bytes = data[INDEX_ITER_STRIDE_IDX]; + auto* src_data_bytes = data[SRC_ITER_STRIDE_IDX]; + // we change the order of TensorIterator-dim loop + // vs dim-TensorIterator loop order depending on + // whether dim is the last dimension + if (dim== buffer.dim() - 1) { + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + // dim loop is a separate code block + // for better performance + loop_func.template operator()( + (opmath_t*)self_data_bytes, self_dim_stride, + (int64_t*)index_data_bytes, index_dim_stride, + (scalar_t*)src_data_bytes, src_dim_stride, + dim, index_dim_size, index_upper_bound, + kernel_func + ); + + self_data_bytes += strides[SELF_ITER_STRIDE_IDX]; + index_data_bytes += strides[INDEX_ITER_STRIDE_IDX]; + src_data_bytes += strides[SRC_ITER_STRIDE_IDX]; + } + } + else { + for (const auto i : c10::irange(index_dim_size)) { + auto* self_data = self_data_bytes; + auto* index_data = (char*)((int64_t*)index_data_bytes + i * index_dim_stride); + auto* src_data = src_data_bytes; + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + int64_t idx_dim = *(int64_t*)index_data; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", *(int64_t*)index_data, + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound); + + kernel_func( + (opmath_t*)self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, + (scalar_t*)src_data + (is_scatter_like ? i : idx_dim) * src_dim_stride); + + self_data += strides[SELF_ITER_STRIDE_IDX]; + index_data += strides[INDEX_ITER_STRIDE_IDX]; + src_data += strides[SRC_ITER_STRIDE_IDX]; + } + } + } + }; + iter.for_each(loop, grain_size); + }), + AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), + AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), + kBool, kHalf, kBFloat16); + if (need_acc) { + self.copy_(buffer); + } + } + + void operator()(const Tensor& self, int64_t dim, + const Tensor& _index, const Tensor& src, + const std::string& method_name, ReduceMean& kernel_func) { + + Tensor buffer; + Tensor index = _index.to(ScalarType::Long); + bool need_acc = isReducedFloatingType(self.scalar_type()); + create_acc_buffer(buffer, self, need_acc); + + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(index.sizes(), /*squash_dims=*/dim) + .add_output(buffer) + .add_const_input(src) + .add_const_input(index) + .build(); + + auto self_dim_stride = ensure_nonempty_stride(buffer, dim); + auto self_dim_size = ensure_nonempty_size(buffer, dim); + + auto index_dim_stride = ensure_nonempty_stride(index, dim); + auto index_dim_size = ensure_nonempty_size(index, dim); + + auto src_dim_stride = ensure_nonempty_stride(src, dim); + auto src_dim_size = ensure_nonempty_size(src, dim); + + auto index_upper_bound = is_scatter_like ? self_dim_size : src_dim_size; + + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / index_dim_size); + + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( + ScalarType::Half, ScalarType::BFloat16, iter.dtype(1), + "scatter_gather_tensor_cpu_reduce_mean", [&] { + constexpr auto SELF_ITER_STRIDE_IDX = 0; + constexpr auto INDEX_ITER_STRIDE_IDX = 2; + constexpr auto SRC_ITER_STRIDE_IDX = 1; + using opmath_t = at::opmath_type; + _cpu_scatter_gather_dim_loop loop_func; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[SELF_ITER_STRIDE_IDX]; + auto* index_data_bytes = data[INDEX_ITER_STRIDE_IDX]; + auto* src_data_bytes = data[SRC_ITER_STRIDE_IDX]; + // we change the order of TensorIterator-dim loop + // vs dim-TensorIterator loop order depending on + // whether dim is the last dimension + if (dim== buffer.dim() - 1) { + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + // dim loop is a separate code block + // for better performance + loop_func.template operator()( + (opmath_t*)self_data_bytes, self_dim_stride, + (int64_t*)index_data_bytes, index_dim_stride, + (scalar_t*)src_data_bytes, src_dim_stride, + dim, index_dim_size, index_upper_bound, + kernel_func + ); + + self_data_bytes += strides[SELF_ITER_STRIDE_IDX]; + index_data_bytes += strides[INDEX_ITER_STRIDE_IDX]; + src_data_bytes += strides[SRC_ITER_STRIDE_IDX]; + } + } + else { + for (const auto i : c10::irange(index_dim_size)) { + auto* self_data = self_data_bytes; + auto* index_data = (char*)((int64_t*)index_data_bytes + i * index_dim_stride); + auto* src_data = src_data_bytes; + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + int64_t idx_dim = *(int64_t*)index_data; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", *(int64_t*)index_data, + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound); + + kernel_func( + (opmath_t*)self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, + (scalar_t*)src_data + (is_scatter_like ? i : idx_dim) * src_dim_stride); + + self_data += strides[SELF_ITER_STRIDE_IDX]; + index_data += strides[INDEX_ITER_STRIDE_IDX]; + src_data += strides[SRC_ITER_STRIDE_IDX]; + } + } + } + }; + iter.for_each(loop, grain_size); + } + ); + if (need_acc) { + self.copy_(buffer); + } + } + + void operator()(const Tensor& self, int64_t dim, + const Tensor& _index, const Tensor& src, + const std::string& method_name, ReduceMaximum& kernel_func) { + Tensor buffer; + Tensor index = _index.to(ScalarType::Long); + bool need_acc = isReducedFloatingType(self.scalar_type()); + create_acc_buffer(buffer, self, need_acc); + + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(index.sizes(), /*squash_dims=*/dim) + .add_output(buffer) + .add_const_input(src) + .add_const_input(index) + .build(); + + auto self_dim_stride = ensure_nonempty_stride(buffer, dim); + auto self_dim_size = ensure_nonempty_size(buffer, dim); + + auto index_dim_stride = ensure_nonempty_stride(index, dim); + auto index_dim_size = ensure_nonempty_size(index, dim); + + auto src_dim_stride = ensure_nonempty_stride(src, dim); + auto src_dim_size = ensure_nonempty_size(src, dim); + + auto index_upper_bound = is_scatter_like ? self_dim_size : src_dim_size; + + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / index_dim_size); + + AT_DISPATCH_ALL_TYPES_AND3( + ScalarType::Bool, ScalarType::Half, ScalarType::BFloat16, iter.dtype(1), + "scatter_gather_tensor_cpu_reduce_amax", [&] { + constexpr auto SELF_ITER_STRIDE_IDX = 0; + constexpr auto INDEX_ITER_STRIDE_IDX = 2; + constexpr auto SRC_ITER_STRIDE_IDX = 1; + using opmath_t = at::opmath_type; + _cpu_scatter_gather_dim_loop loop_func; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[SELF_ITER_STRIDE_IDX]; + auto* index_data_bytes = data[INDEX_ITER_STRIDE_IDX]; + auto* src_data_bytes = data[SRC_ITER_STRIDE_IDX]; + // we change the order of TensorIterator-dim loop + // vs dim-TensorIterator loop order depending on + // whether dim is the last dimension + if (dim== buffer.dim() - 1) { + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + // dim loop is a separate code block + // for better performance + loop_func.template operator()( + (opmath_t*)self_data_bytes, self_dim_stride, + (int64_t*)index_data_bytes, index_dim_stride, + (scalar_t*)src_data_bytes, src_dim_stride, + dim, index_dim_size, index_upper_bound, + kernel_func + ); + + self_data_bytes += strides[SELF_ITER_STRIDE_IDX]; + index_data_bytes += strides[INDEX_ITER_STRIDE_IDX]; + src_data_bytes += strides[SRC_ITER_STRIDE_IDX]; + } + } + else { + for (const auto i : c10::irange(index_dim_size)) { + auto* self_data = self_data_bytes; + auto* index_data = (char*)((int64_t*)index_data_bytes + i * index_dim_stride); + auto* src_data = src_data_bytes; + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + int64_t idx_dim = *(int64_t*)index_data; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", *(int64_t*)index_data, + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound); + + kernel_func( + (opmath_t*)self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, + (scalar_t*)src_data + (is_scatter_like ? i : idx_dim) * src_dim_stride); + + self_data += strides[SELF_ITER_STRIDE_IDX]; + index_data += strides[INDEX_ITER_STRIDE_IDX]; + src_data += strides[SRC_ITER_STRIDE_IDX]; + } + } + } + }; + iter.for_each(loop, grain_size); + } + ); + if (need_acc) { + self.copy_(buffer); + } + } + + void operator()(const Tensor& self, int64_t dim, + const Tensor& _index, const Tensor& src, + const std::string& method_name, ReduceMinimum& kernel_func) { + + Tensor buffer; + Tensor index = _index.to(ScalarType::Long); + bool need_acc = isReducedFloatingType(self.scalar_type()); + create_acc_buffer(buffer, self, need_acc); + + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(index.sizes(), /*squash_dims=*/dim) + .add_output(buffer) + .add_const_input(src) + .add_const_input(index) + .build(); + + auto self_dim_stride = ensure_nonempty_stride(buffer, dim); + auto self_dim_size = ensure_nonempty_size(buffer, dim); + + auto index_dim_stride = ensure_nonempty_stride(index, dim); + auto index_dim_size = ensure_nonempty_size(index, dim); + + auto src_dim_stride = ensure_nonempty_stride(src, dim); + auto src_dim_size = ensure_nonempty_size(src, dim); + + auto index_upper_bound = is_scatter_like ? self_dim_size : src_dim_size; + + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / index_dim_size); + + AT_DISPATCH_ALL_TYPES_AND3( + ScalarType::Bool, ScalarType::Half, ScalarType::BFloat16, iter.dtype(1), + "scatter_gather_tensor_cpu_reduce_amin", [&] { + constexpr auto SELF_ITER_STRIDE_IDX = 0; + constexpr auto INDEX_ITER_STRIDE_IDX = 2; + constexpr auto SRC_ITER_STRIDE_IDX = 1; + using opmath_t = at::opmath_type; + _cpu_scatter_gather_dim_loop loop_func; + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* self_data_bytes = data[SELF_ITER_STRIDE_IDX]; + auto* index_data_bytes = data[INDEX_ITER_STRIDE_IDX]; + auto* src_data_bytes = data[SRC_ITER_STRIDE_IDX]; + // we change the order of TensorIterator-dim loop + // vs dim-TensorIterator loop order depending on + // whether dim is the last dimension + if (dim== buffer.dim() - 1) { + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + // dim loop is a separate code block + // for better performance + loop_func.template operator()( + (opmath_t*)self_data_bytes, self_dim_stride, + (int64_t*)index_data_bytes, index_dim_stride, + (scalar_t*)src_data_bytes, src_dim_stride, + dim, index_dim_size, index_upper_bound, + kernel_func + ); + + self_data_bytes += strides[SELF_ITER_STRIDE_IDX]; + index_data_bytes += strides[INDEX_ITER_STRIDE_IDX]; + src_data_bytes += strides[SRC_ITER_STRIDE_IDX]; + } + } + else { + for (const auto i : c10::irange(index_dim_size)) { + auto* self_data = self_data_bytes; + auto* index_data = (char*)((int64_t*)index_data_bytes + i * index_dim_stride); + auto* src_data = src_data_bytes; + for ([[maybe_unused]] const auto nelem : c10::irange(n)) { + int64_t idx_dim = *(int64_t*)index_data; + // we are not putting idx_dim in the error message because it disables + // loop optimization in clang-7 + TORCH_CHECK(idx_dim >= 0 && idx_dim < index_upper_bound, + "index ", *(int64_t*)index_data, + " is out of bounds for dimension ", dim, + " with size ", index_upper_bound); + + kernel_func( + (opmath_t*)self_data + (is_scatter_like ? idx_dim : i) * self_dim_stride, + (scalar_t*)src_data + (is_scatter_like ? i : idx_dim) * src_dim_stride); + + self_data += strides[SELF_ITER_STRIDE_IDX]; + index_data += strides[INDEX_ITER_STRIDE_IDX]; + src_data += strides[SRC_ITER_STRIDE_IDX]; + } + } + } + }; + iter.for_each(loop, grain_size); + } + ); + if (need_acc) { + self.copy_(buffer); + } + } +}; + +#ifndef USE_FBGEMM +namespace fbgemm { + +template +std::pair radix_sort_parallel( + K* const inp_key_buf, + V* const inp_value_buf, + K* const tmp_key_buf, + V* const tmp_value_buf, + const int64_t elements_count, + const int64_t max_value) { + TORCH_INTERNAL_ASSERT(false, "radix_sort_parallel: ATen not compiled with FBGEMM support"); + return std::make_pair(nullptr, nullptr); +} + +} +#endif + +// implementation taken from FBGEMM/src/Utils.cc +namespace { +// In radix sort, we extract one byte (8 bits) per pass from each key, +// which yields 256 (2^8) distinct values. Therefore, we use 256 histogram bins +// to count the frequency of each byte value during a pass. +constexpr int RDX_HIST_SIZE = 256; // histogram size per thread + +void update_prefsum_and_offset_in_range( + int64_t& offset, + const int bins_beg, + const int bins_end, + const int nthreads, + const int64_t* const histogram, + int64_t* const histogram_ps) { + for (int bins = bins_beg; bins < bins_end; ++bins) { + for (int t = 0; t < nthreads; ++t) { + histogram_ps[t * RDX_HIST_SIZE + bins] = offset; + offset += histogram[t * RDX_HIST_SIZE + bins]; + } + } +} + +static inline void combine_prefix_sum( + const int nthreads, + [[maybe_unused]] const int64_t elements_count, + const int64_t* const histogram, + int64_t* const histogram_ps) { + int64_t offset = 0; + update_prefsum_and_offset_in_range( + offset, 0, RDX_HIST_SIZE, nthreads, histogram, histogram_ps); + // TODO(DamianSzwichtenberg): Is assert sufficient? In most cases, it will + // work only in debug build. + assert(offset == elements_count); +} + +static inline void combine_prefix_sum_for_msb( + const int nthreads, + [[maybe_unused]] const int64_t elements_count, + const int64_t* const histogram, + int64_t* const histogram_ps) { + int64_t offset = 0; + update_prefsum_and_offset_in_range( + offset, 128, RDX_HIST_SIZE, nthreads, histogram, histogram_ps); + update_prefsum_and_offset_in_range( + offset, 0, 128, nthreads, histogram, histogram_ps); + // TODO(DamianSzwichtenberg): Is assert sufficient? In most cases, it will + // work only in debug build. + assert(offset == elements_count); +} + +template +void radix_sort_kernel( + const K* const input_keys, + const V* const input_values, + K* const output_keys, + V* const output_values, + const int64_t elements_count, + int64_t* const histogram, + int64_t* const histogram_ps, + const int pass, + const bool pass_with_sign_bit = false) { + const auto tid = omp_get_thread_num(); + const auto nthreads = omp_get_num_threads(); + const auto elements_count_4 = elements_count / 4 * 4; + + auto* const local_histogram = &histogram[RDX_HIST_SIZE * tid]; + auto* const local_histogram_ps = &histogram_ps[RDX_HIST_SIZE * tid]; + // Step 1: compute histogram + for (int i = 0; i < RDX_HIST_SIZE; i++) { + local_histogram[i] = 0; + } + +#pragma omp for schedule(static) + for (int64_t i = 0; i < elements_count_4; i += 4) { + const auto key_1 = input_keys[i]; + const auto key_2 = input_keys[i + 1]; + const auto key_3 = input_keys[i + 2]; + const auto key_4 = input_keys[i + 3]; + + local_histogram[(key_1 >> (pass * 8)) & 0xFF]++; + local_histogram[(key_2 >> (pass * 8)) & 0xFF]++; + local_histogram[(key_3 >> (pass * 8)) & 0xFF]++; + local_histogram[(key_4 >> (pass * 8)) & 0xFF]++; + } + if (tid == (nthreads - 1)) { + for (int64_t i = elements_count_4; i < elements_count; ++i) { + const auto key = input_keys[i]; + local_histogram[(key >> (pass * 8)) & 0xFF]++; + } + } +#pragma omp barrier + // Step 2: prefix sum + if (tid == 0) { + if (pass_with_sign_bit) { + combine_prefix_sum_for_msb( + nthreads, elements_count, histogram, histogram_ps); + + } else { + combine_prefix_sum(nthreads, elements_count, histogram, histogram_ps); + } + } +#pragma omp barrier + + // Step 3: scatter +#pragma omp for schedule(static) + for (int64_t i = 0; i < elements_count_4; i += 4) { + const auto key_1 = input_keys[i]; + const auto key_2 = input_keys[i + 1]; + const auto key_3 = input_keys[i + 2]; + const auto key_4 = input_keys[i + 3]; + + const int bin_1 = (key_1 >> (pass * 8)) & 0xFF; + const int bin_2 = (key_2 >> (pass * 8)) & 0xFF; + const int bin_3 = (key_3 >> (pass * 8)) & 0xFF; + const int bin_4 = (key_4 >> (pass * 8)) & 0xFF; + + const auto pos_1 = local_histogram_ps[bin_1]++; + const auto pos_2 = local_histogram_ps[bin_2]++; + const auto pos_3 = local_histogram_ps[bin_3]++; + const auto pos_4 = local_histogram_ps[bin_4]++; + + output_keys[pos_1] = key_1; + output_values[pos_1] = input_values[i]; + output_keys[pos_2] = key_2; + output_values[pos_2] = input_values[i + 1]; + output_keys[pos_3] = key_3; + output_values[pos_3] = input_values[i + 2]; + output_keys[pos_4] = key_4; + output_values[pos_4] = input_values[i + 3]; + } + if (tid == (nthreads - 1)) { + for (int64_t i = elements_count_4; i < elements_count; ++i) { + const auto key = input_keys[i]; + const auto pos = local_histogram_ps[(key >> (pass * 8)) & 0xFF]++; + output_keys[pos] = key; + output_values[pos] = input_values[i]; + } + } +} + +template +std::pair radix_sort_parallel( + K* const inp_key_buf, + V* const inp_value_buf, + K* const tmp_key_buf, + V* const tmp_value_buf, + const int64_t elements_count, + const int64_t max_value, + const bool maybe_with_neg_vals = false) { + if (max_value == 0) { + return {inp_key_buf, inp_value_buf}; + } + + const auto maxthreads = omp_get_max_threads(); + + std::vector histogram(RDX_HIST_SIZE * maxthreads, 0); + std::vector histogram_ps(RDX_HIST_SIZE * maxthreads, 0); + + // If negative values are present, we want to perform all passes + // up to a sign bit + int num_bits = sizeof(K) * 8; + if (!maybe_with_neg_vals) + num_bits -= c10::llvm::countLeadingZeros( + static_cast::type>(max_value)); + + const unsigned int num_passes = (num_bits + 7) / 8; + +#pragma omp parallel + { + K* input_keys = inp_key_buf; + V* input_values = inp_value_buf; + K* output_keys = tmp_key_buf; + V* output_values = tmp_value_buf; + + for (unsigned int pass = 0; pass < num_passes; pass++) { + radix_sort_kernel( + input_keys, + input_values, + output_keys, + output_values, + elements_count, + histogram.data(), + histogram_ps.data(), + pass, + maybe_with_neg_vals && pass == num_passes - 1); + + std::swap(input_keys, output_keys); + std::swap(input_values, output_values); +#pragma omp barrier + {} + } + } + + return ( + num_passes % 2 == 0 ? std::make_pair(inp_key_buf, inp_value_buf) + : std::make_pair(tmp_key_buf, tmp_value_buf)); +} + +} // namespace + +// Note [scatter reduce optimization] +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// 1. initiative: optimize `scatter_reduce` on classic PyG use-case: +// `scatter_reduce` is extensively used on 'message passing' when +// aggregating info. +// +// Typically, `self` will 2D tensor and `index` is a 1D extended/broadcasted +// tensor, which means that the aggregation is on rowwise and we can vectorize +// on the inner dimensions. +// +// 2. implementation: map `scatter_reduce` to `spmm` reduce +// in the shape of `[M, N]` * `[N, K]`, where: +// +// M: self_dim_size +// nnz: index_dim_size +// K: index.numel() / index_dim_size; +// +// step 1: convert input index to CSR format (use radix_sort to +// solve write addr conflicts on `self` tensor) +// +// step 2: spmm reduce, parallel on M and vectorize on K +// + +template +void cpu_scatter_reduce_expanded_index(const Tensor& self, const Tensor& index, const Tensor& src, bool include_self) { + const int64_t* index_data = index.const_data_ptr(); + scalar_t* self_data = self.data_ptr(); + const scalar_t* src_data = src.const_data_ptr(); + + const int64_t M = ensure_nonempty_size(self, 0); + const int64_t nnz = ensure_nonempty_size(index, 0); + const int64_t K = index.numel() / nnz; + + const int64_t index_upper_bound = M; + + auto keys = std::make_unique(nnz); + auto values = std::make_unique(nnz); + auto keys_tmp = std::make_unique(nnz); + auto values_tmp = std::make_unique(nnz); + at::parallel_for(0, nnz, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + int64_t index = index_data[i]; + TORCH_CHECK(index >= 0 && index < index_upper_bound, + "index ", index, + " is out of bounds for dimension ", 0, + " with size ", index_upper_bound); + keys[i] = index; + values[i] = i; + } + }); + + int64_t* sorted_col_index_keys = nullptr; + int64_t* sorted_col_index_values = nullptr; + +// We maintain the FBGEMM path for x86 platforms to leverage potential +// architecture-specific assembly/intrinsic optimizations in that library. +// For ARM and other non-x86 platforms, we use the in-tree radix_sort_parallel +// implementation to ensure parity in performance. +#if defined(USE_FBGEMM) + std::tie(sorted_col_index_keys, sorted_col_index_values) = fbgemm::radix_sort_parallel( + keys.get(), + values.get(), + keys_tmp.get(), + values_tmp.get(), + nnz, + M); +#else + std::tie(sorted_col_index_keys, sorted_col_index_values) = radix_sort_parallel( + keys.get(), + values.get(), + keys_tmp.get(), + values_tmp.get(), + nnz, + M); +#endif + + int num_threads = at::get_num_threads(); + std::vector num_uniq(num_threads, 0); + at::parallel_for(1, nnz, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + for(const auto i : c10::irange(begin, end)) { + if (sorted_col_index_keys[i] != sorted_col_index_keys[i - 1]) { + num_uniq[tid]++; + } + } + }); + num_uniq[0]++; + for (const auto n : c10::irange(1, num_threads)) { + num_uniq[n] += num_uniq[n - 1]; + } + + // in case some rows are not written into, num_nonzero_rows will be smaller than M + int64_t num_nonzero_rows = num_uniq[num_threads - 1]; + auto row_index_tmp = std::make_unique(num_nonzero_rows); + auto row_index_offset_tmp = std::make_unique(num_nonzero_rows + 1); + int64_t* row_index = row_index_tmp.get(); + int64_t* row_index_offset = row_index_offset_tmp.get(); + row_index[0] = sorted_col_index_keys[0]; + row_index_offset[0] = 0; + row_index_offset[num_nonzero_rows] = nnz; + + at::parallel_for(1, nnz, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + int64_t* t_index = row_index + ((tid == 0) ? 1 : num_uniq[tid - 1]); + int64_t* t_index_offset = row_index_offset + ((tid == 0) ? 1 : num_uniq[tid - 1]); + for (const auto i : c10::irange(begin, end)) { + if (sorted_col_index_keys[i] != sorted_col_index_keys[i - 1]) { + *t_index = sorted_col_index_keys[i]; + *t_index_offset = i; + t_index++; + t_index_offset++; + } + } + }); + + using opmath_t = at::opmath_type; + Tensor buffer; + opmath_t* buffer_data = nullptr; + static constexpr bool need_acc = is_reduced_floating_point_v; + if constexpr (need_acc) { + auto acc_type = at::toAccumulateType(self.scalar_type(), /*is_cuda=*/true); + buffer = at::zeros({num_threads, K}, self.options().dtype(acc_type)); + buffer_data = buffer.data_ptr(); + } + + // TODO: do blocking on col dimension to reduce WR bandwidth + at::parallel_for(0, num_nonzero_rows, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, + "expect thread id smaller than ", num_threads, ", got thread id ", tid); + opmath_t* buffer_ptr = nullptr; + + for (const auto m : c10::irange(begin, end)) { + int64_t row = row_index[m]; + int64_t off_start = row_index_offset[m]; + int64_t off_end = row_index_offset[m + 1]; + scalar_t* self_ptr = self_data + row * K; + if constexpr (need_acc) { + buffer_ptr = buffer_data + tid * K; + } else { + buffer_ptr = reinterpret_cast(self_ptr); + } + + // step 1: reinit rows in `self` if needed + _init(self_ptr, buffer_ptr, K, include_self); + + // step 2: reduce + for (const auto n : c10::irange(off_start, off_end)) { + int64_t col = sorted_col_index_values[n]; + update(buffer_ptr, src_data + col * K, K); + } + if constexpr (need_acc) { + vec::convert(buffer_ptr, self_ptr, K); + } + + // step 3: finalize + int64_t count = include_self ? 1 : 0; + count += off_end - off_start; + write(self_ptr, count, K); + } + }); +} + +template +void cpu_gather_expanded_index_kernel(const Tensor& result, const Tensor& _index, const Tensor& self) { + Tensor index = _index.to(ScalarType::Long); + const int64_t* index_data = index.const_data_ptr(); + scalar_t* result_data = result.data_ptr(); + const scalar_t* self_data = self.const_data_ptr(); + + const int64_t M = ensure_nonempty_size(result, 0); + const int64_t N = ensure_nonempty_size(self, 0); + const int64_t K = index.numel() / M; + + const int64_t index_upper_bound = N; + + using Vec = vec::Vectorized; + int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / K); + at::parallel_for(0, M, grain_size, [&](int64_t begin, int64_t end) { + for (const auto m : c10::irange(begin, end)) { + scalar_t* result_ptr = result_data + m * K; + int64_t index = index_data[m]; + TORCH_CHECK(index >= 0 && index < index_upper_bound, + "index ", index, + " is out of bounds for dimension ", 0, + " with size ", index_upper_bound); + const scalar_t* self_ptr = self_data + index * K; + int64_t d = 0; + for (; d < K - (K % Vec::size()); d += Vec::size()) { + Vec out_vec = Vec::loadu(self_ptr + d); + out_vec.store(result_ptr + d); + } + #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (; d < K; d++) { + result_ptr[d] = self_ptr[d]; + } + } + }); +} + +void scatter_add_expanded_index_kernel(const Tensor& self, const Tensor& index, const Tensor& src) { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, self.scalar_type(), "scatter_add_expanded_index", [&] { + cpu_scatter_reduce_expanded_index(self, index, src, /*include_self*/true); + }); +} + +void scatter_reduce_expanded_index_kernel( + const Tensor& self, const Tensor& index, const Tensor& src, + const ReductionType& reduction, bool include_self) { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, self.scalar_type(), "scatter_reduce_expanded_index", [&] { + AT_DISPATCH_REDUCTION_TYPES(reduction, [&]() { + cpu_scatter_reduce_expanded_index(self, index, src, include_self); + }); + }); +} + +void gather_expanded_index_kernel(const Tensor& result, const Tensor& self, const Tensor& index) { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, self.scalar_type(), "gather_expanded_index", [&] { + cpu_gather_expanded_index_kernel(result, index, self); + }); +} + +void gather_cpu_kernel(const Tensor& result, const Tensor& self, int64_t dim, const Tensor& index) { + cpu_scatter_gather_base_kernel()( + result, dim, index, self, + "gather_out_cpu", tensor_assign); +} + +void scatter_cpu_kernel(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src) { + cpu_scatter_gather_base_kernel<>()( + self, dim, index, src, "scatter_cpu_", tensor_assign); +} + +void scatter_fill_cpu_kernel(const Tensor& self, int64_t dim, const Tensor& index, const Scalar& value) { + cpu_scatter_gather_base_kernel<>()( + self, dim, index, value, "scatter_fill_cpu_", tensor_assign); +} + +void scatter_add_cpu_kernel(const Tensor& self, int64_t dim, const Tensor& index, const Tensor& src) { + cpu_scatter_gather_base_kernel<>()( + self, dim, index, src, + "scatter_add_", reduce_add); +} + +void scatter_reduce_cpu_kernel(const Tensor& self, const int64_t dim, const Tensor& index, + const Tensor& src, const ReductionType& reduce) { + switch (reduce) { + case ReductionType::SUM : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_add_", reduce_add); + break; + case ReductionType::PROD : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_multiply_", reduce_multiply); + break; + default : + break; + } +} + +void scatter_reduce_two_cpu_kernel(const Tensor& self, const int64_t dim, const Tensor& index, + const Tensor& src, const ReductionType& reduce) { + switch (reduce) { + case ReductionType::SUM : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_sum_", reduce_add); + break; + case ReductionType::PROD : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_prod_", reduce_multiply); + break; + case ReductionType::MAX : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_amax_", reduce_maximum); + break; + case ReductionType::MIN : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_amin_", reduce_minimum); + break; + case ReductionType::MEAN : + cpu_scatter_gather_base_kernel<>()(self, dim, index, src, + "scatter_reduce_mean_", reduce_mean); + break; + } +} + +void scatter_scalar_reduce_cpu_kernel(const Tensor& self, const int64_t dim, const Tensor& index, + const Scalar& value, const ReductionType& reduce) { + switch (reduce) { + case ReductionType::SUM : + cpu_scatter_gather_base_kernel<>()(self, dim, index, value, + "scatter_scalar_reduce_add_", reduce_add); + break; + case ReductionType::PROD : + cpu_scatter_gather_base_kernel<>()(self, dim, index, value, + "scatter_scalar_reduce_multiply_", reduce_multiply); + break; + default: + break; + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(gather_stub, &gather_cpu_kernel) +REGISTER_DISPATCH(scatter_stub, &scatter_cpu_kernel) +REGISTER_DISPATCH(scatter_fill_stub, &scatter_fill_cpu_kernel) +REGISTER_DISPATCH(scatter_add_stub, &scatter_add_cpu_kernel) +REGISTER_DISPATCH(scatter_reduce_stub, &scatter_reduce_cpu_kernel) +REGISTER_DISPATCH(scatter_scalar_reduce_stub, &scatter_scalar_reduce_cpu_kernel) +REGISTER_DISPATCH(scatter_reduce_two_stub, &scatter_reduce_two_cpu_kernel) + +// fast paths for GNN usage +REGISTER_DISPATCH(scatter_add_expanded_index_stub, &scatter_add_expanded_index_kernel) +REGISTER_DISPATCH(scatter_reduce_expanded_index_stub, &scatter_reduce_expanded_index_kernel) +REGISTER_DISPATCH(gather_expanded_index_stub, &gather_expanded_index_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SerialStackImpl.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SerialStackImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..203d0b8cf525639984ab4f09d742efa6f52866c5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SerialStackImpl.h @@ -0,0 +1,146 @@ +// Copyright 2004-present Facebook. All Rights Reserved. +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native::detail { + +struct InputMeta { + void* data_ptr; + int64_t inner_size; + + InputMeta(const Tensor& t, int64_t dim, int64_t inner) + : data_ptr(t.data_ptr()), inner_size(t.sizes()[dim] * inner) {} +}; + +// This kernel is used by two TensorList types: +// 1. stack_serial_kernel uses at::ArrayRef +// 2. Static runtime calls this kernel directly (csrc/jit/runtime/static/ops.cpp) with +// ProcessedNodeInputWrapper. +// When making changes, make sure that they are compatible with both types! +template +void stack_serial_kernel_impl(Tensor& result, TensorListType tensors, int64_t dim) { + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + dim >= 0 && dim <= result.dim(), + "dim out of range in stack_serial_kernel_impl"); + int64_t outer = + result.numel() / (result.sizes()[dim] * result.strides()[dim]); + scalar_t* result_data = result.data_ptr(); + int64_t ninputs = tensors.size(); + std::vector inputs; + inputs.reserve(ninputs); + for (const auto& tensor : tensors) { + inputs.emplace_back(tensor, dim, tensor.strides()[dim]); + } + + using Vec = vec::Vectorized; + scalar_t* result_ptr = result_data; + for (const auto i : c10::irange(outer)) { + for (const auto j : c10::irange(ninputs)) { + int64_t local_inner = inputs[j].inner_size; + scalar_t* input_ptr = (scalar_t*)(inputs[j].data_ptr) + i * local_inner; + + if (local_inner < Vec::size()) { + for (const auto k : c10::irange(local_inner)) { + result_ptr[k] = input_ptr[k]; + } + } else { + vec::map( + [](Vec x) { return x; }, result_ptr, input_ptr, local_inner); + } + result_ptr += local_inner; + } + } +} + +// Checks to see whether native stack can be invoked under these conditions: +// - result and input tensors are contiguous +// - only one thread is used +// - no type promotion has to occur +// - tensors dtype is Double or Float +template +bool can_use_native_serial_stack_impl(Tensor& result, TensorListType tensors, int64_t dim) { + TORCH_CHECK(!tensors.empty(), "expected a non-empty list of Tensors"); + const Tensor& first_tensor = tensors[0]; + // stack dimension should be in range [0,firstTensor.dim()) + // dim == firstTensor.dim() is a valid input, but it is handled by default code path + // that uses unsqueeze + if (dim >= first_tensor.dim()) return false; + // Native stack doesn't apply any tensor is skipped. + if (first_tensor.numel() == 0 && first_tensor.dim() == 1) return false; + // there should be no type promotion + if (result.dtype() != first_tensor.dtype()) return false; + + auto first_tensor_mem_format = first_tensor.suggest_memory_format(); + ScalarType dtype = first_tensor.scalar_type(); + + if (!result.is_contiguous(first_tensor_mem_format)) { + return false; + } + + // fast path only works for Double and Float + if (dtype != ScalarType::Double && dtype != ScalarType::Float) { + return false; + } + + // check remainder of inputs +#ifndef STRIP_ERROR_MESSAGES + auto const &first_tensor_shape = first_tensor.sizes(); +#endif + for (const auto i : c10::irange(1, tensors.size())) { + auto const &tensor = tensors[i]; + TORCH_CHECK(tensors[i].sizes() == first_tensor.sizes(), + "stack expects each tensor to be equal size, but got ", first_tensor_shape, + " at entry 0 and ", tensor.sizes(), " at entry ", i); + + // every tensor must be contiguous + // tensor sizes and strides must be the same + // there should be no type promotion + if (!tensor.is_contiguous(first_tensor_mem_format) || + tensor.strides() != first_tensor.strides() || + tensor.dtype() != dtype) { + return false; + } + } + + // fast native stack should only be used when it is not worth using multiple threads + // or there is only one thread. Note that we aren't checking result.numel() here because + // it may not have been resized and we want to defer that cost till later. + int64_t numel_in_stack = first_tensor.numel() * tensors.size(); + return numel_in_stack < at::internal::GRAIN_SIZE || at::get_num_threads() == 1; +} + +template +struct CanUseNativeSerialStack; + +template +struct CanUseNativeSerialStack { + static bool call(Tensor& result, TensorListType tensors, int64_t dim) { + // Inputs cannot alias the output tensor + for (const auto i : c10::irange(tensors.size())) { + auto lap = at::get_overlap_status(result, tensors[i]); + TORCH_CHECK(lap != at::MemOverlapStatus::Partial && + lap != at::MemOverlapStatus::Full, 0, + "unsupported operation: the input tensors cannot refer to any of the " + "output memory locations. Found overlap in input tensor ", i); + } + + return can_use_native_serial_stack_impl(result, tensors, dim); + } +}; + +template +struct CanUseNativeSerialStack { + static bool call(Tensor& result, TensorListType tensors, int64_t dim) { + return can_use_native_serial_stack_impl(result, tensors, dim); + } +}; + +} // namespace at::native::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SoftMaxKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SoftMaxKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a6b39949dc6d2ccbda5952bda51dfa1bce8a95b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SoftMaxKernel.cpp @@ -0,0 +1,1074 @@ +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +// [Note AVX-SSE transitions] In general we avoid calls into cmath for code +// compiled with AVX/AVX2 This is because of SSE-AVX transitions and a bug in +// Glibc2.23 See https://bugs.launchpad.net/ubuntu/+source/glibc/+bug/1663280 +// +// On grainsize: The grainsize is chosen to roughly get GRAIN_SIZE number of +// computations per task. Each task works across dim_size elements. 16 should be +// a very rough approximation of the number of computations per dim_size element +// by counting simple computations (*, +, -) as 1 and exp or log as 4. +// +// We use a chunk size such that it'd fit in L1D. + +namespace at::native { +namespace { +template +inline void _vec_log_softmax_lastdim( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t dim_size) { + const auto chunk_size = vec_log_softmax_lastdim_chunk_size( + at::internal::GRAIN_SIZE, + outer_size, + dim_size); + // Note: grain_size value of 0 + // We don't change the number of OpenMP threads in the OpenMP thread-pool, + // so some threads do useful work, while others don't. + // We can simply use grain_size of 0 & rely upon invoke_parallel to distribute + // work among threads in an equitable manner. We compute CHUNK_SIZE to ensure + // each thread's computations would be efficient. + parallel_for(0, outer_size, 0, [&](int64_t begin, int64_t end) { + serial_vec_log_softmax_lastdim_range( + input_data_base, + output_data_base, + dim_size, + chunk_size, + begin, + end); + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_softmax_lastdim( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + // See Note: grain_size value of 0 + parallel_for(0, outer_size, 0, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_data = input_data_base + i * dim_size; + scalar_t* output_data = output_data_base + i * dim_size; + scalar_t max_input = vec::reduce_all( + [](Vec& x, Vec& y) { return vec::maximum(x, y); }, + input_data, + dim_size); + vec::map( + [max_input](Vec x) { return (x - Vec(max_input)).exp(); }, + output_data, + input_data, + dim_size); + scalar_t tmp_sum = vec::reduce_all( + [](Vec x, Vec y) { return x + y; }, output_data, dim_size); + tmp_sum = 1 / tmp_sum; + vec::map( + [tmp_sum](Vec x) { return x * Vec(tmp_sum); }, + output_data, + output_data, + dim_size); + } + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_softmax_lastdim( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + // See Note: grain_size value of 0 + parallel_for(0, outer_size, 0, [&](int64_t begin, int64_t end) { + // thread local temp buffer. + auto buffer = std::make_unique(dim_size); + float* buffer_data = buffer.get(); + + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_data = input_data_base + i * dim_size; + scalar_t* output_data = output_data_base + i * dim_size; + // reduce to max and cache float input data + fVec max_fvec = fVec(-std::numeric_limits::infinity()); + int64_t d0 = 0; + for (; d0 < dim_size - (dim_size % Vec::size()); d0 += Vec::size()) { + Vec data_vec = Vec::loadu(input_data + d0); + auto [data_fvec0, data_fvec1] = vec::convert_to_float(data_vec); + max_fvec = vec::maximum(max_fvec, data_fvec0); + max_fvec = vec::maximum(max_fvec, data_fvec1); + data_fvec0.store(buffer_data + d0); + data_fvec1.store(buffer_data + d0 + fVec::size()); + } + float max_val = vec::vec_reduce_all([](fVec& x, fVec& y) { return vec::maximum(x, y); }, max_fvec); + for (; d0 < dim_size; d0++) { + float data_val = input_data[d0]; + max_val = std::max(max_val, data_val); + buffer_data[d0] = data_val; + } + + // map (x - max).exp() and reduce to sum + fVec sum_fvec = fVec(float(0)); + int64_t d1 = 0; + for (; d1 < dim_size - (dim_size % fVec::size()); d1 += fVec::size()) { + fVec data_fvec = (fVec::loadu(buffer_data + d1) - fVec(max_val)).exp(); + sum_fvec += data_fvec; + data_fvec.store(buffer_data + d1); + } + float sum_val = vec::vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, sum_fvec); + for (; d1 < dim_size; d1++) { + float data_val = std::exp(buffer_data[d1] - max_val); + sum_val += data_val; + buffer_data[d1] = data_val; + } + + sum_val = 1 / sum_val; + int64_t d2 = 0; + for (; d2 < dim_size - (dim_size % Vec::size()); d2 += Vec::size()) { + fVec out_fvec0 = fVec::loadu(buffer_data + d2) * fVec(sum_val); + fVec out_fvec1 = fVec::loadu(buffer_data + d2 + fVec::size()) * fVec(sum_val); + Vec out_vec = vec::convert_from_float(out_fvec0, out_fvec1); + out_vec.store(output_data + d2); + } + for (; d2 < dim_size; d2++) { + output_data[d2] = scalar_t(buffer_data[d2] * sum_val); + } + } + }); +} + +template +inline void _vec_host_softmax_backward_lastdim( + scalar_t* grad_input_data_base, + const scalar_t* grad_data_base, + const scalar_t* output_data_base, + int64_t outer_size, + int64_t dim_size) { + using Vec = vec::Vectorized>; + // See Note: grain_size value of 0 + parallel_for( + 0, + outer_size, + 0, + [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + scalar_t* grad_input_data = grad_input_data_base + i * dim_size; + const scalar_t* grad_data = grad_data_base + i * dim_size; + const scalar_t* output_data = output_data_base + i * dim_size; + if constexpr (log_softmax) { + auto sum = vec::reduce_all( + [](Vec& x, Vec& y) { return x + y; }, grad_data, dim_size); + vec::map2( + [sum](Vec x, Vec y) { return x - ((y.exp()) * Vec(sum)); }, + grad_input_data, + grad_data, + output_data, + dim_size); + } else { + auto sum = vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + grad_data, + output_data, + dim_size); + vec::map2( + [sum](Vec x, Vec y) { return (x - Vec(sum)) * y; }, + grad_input_data, + grad_data, + output_data, + dim_size); + } + } + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_softmax_backward( + scalar_t* grad_input_data_base, + const scalar_t* grad_output_data_base, + const scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + int64_t outer_stride = dim_size * inner_size; + int64_t BLOCK_SIZE = 128 * 1024; + int64_t MAX_CHUNK_SIZE = std::max( + BLOCK_SIZE / dim_size / sizeof(scalar_t), Vec::size()); + MAX_CHUNK_SIZE = MAX_CHUNK_SIZE / Vec::size() * Vec::size(); + int64_t CHUNK_SIZE = std::min(MAX_CHUNK_SIZE, inner_size); + int64_t num_chunks = divup(inner_size, CHUNK_SIZE); + // See Note: grain_size value of 0 + parallel_for( + 0, outer_size * num_chunks, 0, [&](int64_t begin, int64_t end) { + // thread local temp buffer that holds vertical sum result + auto buffer = std::make_unique(CHUNK_SIZE); + scalar_t* tmp_sum_data = buffer.get(); + + for (int64_t i = begin; i < end; i++) { + int64_t outer_idx = i / num_chunks; + int64_t k = i % num_chunks; + int64_t inner_idx_begin = k * CHUNK_SIZE; + int64_t size = std::min(CHUNK_SIZE, inner_size - inner_idx_begin); + + // init + Vec zero_vec = Vec(scalar_t(0)); + int64_t d0 = 0; + for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) { + zero_vec.store(tmp_sum_data + d0); + } + for (; d0 < size; d0++) { + tmp_sum_data[d0] = scalar_t(0); + } + + // compute sum of grad_output * output + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + int64_t offset = outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + const scalar_t* grad_output_ptr = grad_output_data_base + offset; + const scalar_t* output_ptr = output_data_base + offset; + + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec grad_output_vec = Vec::loadu(grad_output_ptr + d1); + Vec output_vec = Vec::loadu(output_ptr + d1); + Vec sum_vec = Vec::loadu(tmp_sum_data + d1); + sum_vec += grad_output_vec * output_vec; + sum_vec.store(tmp_sum_data + d1); + } + for (; d1 < size; d1++) { + tmp_sum_data[d1] += grad_output_ptr[d1] * output_ptr[d1]; + } + } + + // compute output * (grad_output - sum) + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + int64_t offset = outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + const scalar_t* grad_output_ptr = grad_output_data_base + offset; + const scalar_t* output_ptr = output_data_base + offset; + scalar_t* grad_input_ptr = grad_input_data_base + offset; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + Vec grad_output_vec = Vec::loadu(grad_output_ptr + d2); + Vec output_vec = Vec::loadu(output_ptr + d2); + Vec sum_vec = Vec::loadu(tmp_sum_data + d2); + Vec grad_input_vec = output_vec * (grad_output_vec - sum_vec); + grad_input_vec.store(grad_input_ptr + d2); + } + for (; d2 < size; d2++) { + grad_input_ptr[d2] = output_ptr[d2] * (grad_output_ptr[d2] - tmp_sum_data[d2]); + } + } + } + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_softmax_backward( + scalar_t* grad_input_data_base, + const scalar_t* grad_output_data_base, + const scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + int64_t outer_stride = dim_size * inner_size; + int64_t BLOCK_SIZE = 128 * 1024; + int64_t MAX_CHUNK_SIZE = std::max( + BLOCK_SIZE / dim_size / sizeof(scalar_t), Vec::size()); + MAX_CHUNK_SIZE = MAX_CHUNK_SIZE / Vec::size() * Vec::size(); + int64_t CHUNK_SIZE = std::min(MAX_CHUNK_SIZE, inner_size); + int64_t num_chunks = divup(inner_size, CHUNK_SIZE); + // See Note: grain_size value of 0 + parallel_for( + 0, outer_size * num_chunks, 0, [&](int64_t begin, int64_t end) { + // thread local temp buffer that holds vertical sum result + auto buffer = std::make_unique(CHUNK_SIZE); + float* tmp_sum_data = buffer.get(); + + // thread local buffer that holds grad_output and output data in float32 + auto grad_output_buffer = std::make_unique(dim_size * CHUNK_SIZE); + float* grad_output_buffer_data = grad_output_buffer.get(); + + auto output_buffer = std::make_unique(dim_size * CHUNK_SIZE); + float* output_buffer_data = output_buffer.get(); + + for (int64_t i = begin; i < end; i++) { + int64_t outer_idx = i / num_chunks; + int64_t k = i % num_chunks; + int64_t inner_idx_begin = k * CHUNK_SIZE; + int64_t size = std::min(CHUNK_SIZE, inner_size - inner_idx_begin); + + // init + fVec zero_fvec = fVec(float(0)); + int64_t d0 = 0; + for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) { + zero_fvec.store(tmp_sum_data + d0); + zero_fvec.store(tmp_sum_data + d0 + fVec::size()); + } + for (; d0 < size; d0++) { + tmp_sum_data[d0] = float(0); + } + + // compute sum of grad_output * output + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + int64_t offset = outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + const scalar_t* grad_output_ptr = grad_output_data_base + offset; + const scalar_t* output_ptr = output_data_base + offset; + float* grad_output_buffer_ptr = + grad_output_buffer_data + dim_idx * CHUNK_SIZE; + float* output_buffer_ptr = + output_buffer_data + dim_idx * CHUNK_SIZE; + + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec grad_output_vec = Vec::loadu(grad_output_ptr + d1); + auto [grad_output_fvec0, grad_output_fvec1] = + vec::convert_to_float(grad_output_vec); + Vec output_vec = Vec::loadu(output_ptr + d1); + auto [output_fvec0, output_fvec1] = + vec::convert_to_float(output_vec); + fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d1); + fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d1 + fVec::size()); + sum_fvec0 += grad_output_fvec0 * output_fvec0; + sum_fvec1 += grad_output_fvec1 * output_fvec1; + sum_fvec0.store(tmp_sum_data + d1); + sum_fvec1.store(tmp_sum_data + d1 + fVec::size()); + + // cache the 'converted' float grad_output and output + grad_output_fvec0.store(grad_output_buffer_ptr + d1); + grad_output_fvec1.store( + grad_output_buffer_ptr + d1 + fVec::size()); + output_fvec0.store(output_buffer_ptr + d1); + output_fvec1.store(output_buffer_ptr + d1 + fVec::size()); + } + for (; d1 < size; d1++) { + float grad_output_val = float(grad_output_ptr[d1]); + float output_val = float(output_ptr[d1]); + tmp_sum_data[d1] += grad_output_val * output_val; + grad_output_buffer_ptr[d1] = grad_output_val; + output_buffer_ptr[d1] = output_val; + } + } + + // compute output * (grad_output - sum) + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + scalar_t* grad_input_ptr = grad_input_data_base + + outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + float* grad_output_buffer_ptr = + grad_output_buffer_data + dim_idx * CHUNK_SIZE; + float* output_buffer_ptr = + output_buffer_data + dim_idx * CHUNK_SIZE; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d2); + fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d2 + fVec::size()); + fVec grad_output_fvec0 = fVec::loadu(grad_output_buffer_ptr + d2); + fVec grad_output_fvec1 = + fVec::loadu(grad_output_buffer_ptr + d2 + fVec::size()); + fVec output_fvec0 = fVec::loadu(output_buffer_ptr + d2); + fVec output_fvec1 = + fVec::loadu(output_buffer_ptr + d2 + fVec::size()); + fVec grad_input_fvec0 = + output_fvec0 * (grad_output_fvec0 - sum_fvec0); + fVec grad_input_fvec1 = + output_fvec1 * (grad_output_fvec1 - sum_fvec1); + Vec grad_input_vec = + vec::convert_from_float(grad_input_fvec0, grad_input_fvec1); + grad_input_vec.store(grad_input_ptr + d2); + } + for (; d2 < size; d2++) { + grad_input_ptr[d2] = output_buffer_ptr[d2] * (grad_output_buffer_ptr[d2] - tmp_sum_data[d2]); + } + } + } + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_log_softmax_backward( + scalar_t* grad_input_data_base, + const scalar_t* grad_output_data_base, + const scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + int64_t outer_stride = dim_size * inner_size; + int64_t BLOCK_SIZE = 128 * 1024; + int64_t MAX_CHUNK_SIZE = std::max( + BLOCK_SIZE / dim_size / sizeof(scalar_t), Vec::size()); + MAX_CHUNK_SIZE = MAX_CHUNK_SIZE / Vec::size() * Vec::size(); + int64_t CHUNK_SIZE = std::min(MAX_CHUNK_SIZE, inner_size); + int64_t num_chunks = divup(inner_size, CHUNK_SIZE); + // See Note: grain_size value of 0 + parallel_for( + 0, outer_size * num_chunks, 0, [&](int64_t begin, int64_t end) { + // thread local temp buffer that holds vertical sum result + auto buffer = std::make_unique(CHUNK_SIZE); + scalar_t* tmp_sum_data = buffer.get(); + + for (int64_t i = begin; i < end; i++) { + int64_t outer_idx = i / num_chunks; + int64_t k = i % num_chunks; + int64_t inner_idx_begin = k * CHUNK_SIZE; + int64_t size = std::min(CHUNK_SIZE, inner_size - inner_idx_begin); + + // init + Vec zero_vec = Vec(scalar_t(0)); + int64_t d0 = 0; + for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) { + zero_vec.store(tmp_sum_data + d0); + } + for (; d0 < size; d0++) { + tmp_sum_data[d0] = scalar_t(0); + } + + // compute sum of grad_output + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + const scalar_t* grad_output_ptr = grad_output_data_base + + outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec grad_output_vec = Vec::loadu(grad_output_ptr + d1); + Vec sum_vec = Vec::loadu(tmp_sum_data + d1); + sum_vec += grad_output_vec; + sum_vec.store(tmp_sum_data + d1); + } + for (; d1 < size; d1++) { + tmp_sum_data[d1] += grad_output_ptr[d1]; + } + } + + // compute grad_output - output.exp() * sum + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + int64_t offset = outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + const scalar_t* grad_output_ptr = grad_output_data_base + offset; + const scalar_t* output_ptr = output_data_base + offset; + scalar_t* grad_input_ptr = grad_input_data_base + offset; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + Vec grad_output_vec = Vec::loadu(grad_output_ptr + d2); + Vec output_vec = Vec::loadu(output_ptr + d2); + Vec sum_vec = Vec::loadu(tmp_sum_data + d2); + Vec grad_input_vec = grad_output_vec - output_vec.exp() * sum_vec; + grad_input_vec.store(grad_input_ptr + d2); + } + for (; d2 < size; d2++) { + grad_input_ptr[d2] = grad_output_ptr[d2] - + std::exp(output_ptr[d2]) * tmp_sum_data[d2]; + } + } + } + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_log_softmax_backward( + scalar_t* grad_input_data_base, + const scalar_t* grad_output_data_base, + const scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + int64_t outer_stride = dim_size * inner_size; + int64_t BLOCK_SIZE = 128 * 1024; + int64_t MAX_CHUNK_SIZE = std::max( + BLOCK_SIZE / dim_size / sizeof(scalar_t), Vec::size()); + MAX_CHUNK_SIZE = MAX_CHUNK_SIZE / Vec::size() * Vec::size(); + int64_t CHUNK_SIZE = std::min(MAX_CHUNK_SIZE, inner_size); + int64_t num_chunks = divup(inner_size, CHUNK_SIZE); + // See Note: grain_size value of 0 + parallel_for( + 0, outer_size * num_chunks, 0, [&](int64_t begin, int64_t end) { + // thread local temp buffer that holds vertical sum result + auto buffer = std::make_unique(CHUNK_SIZE); + float* tmp_sum_data = buffer.get(); + + // thread local buffer that holds grad_output data in float32 + auto grad_output_buffer = std::make_unique(dim_size * CHUNK_SIZE); + float* grad_output_buffer_data = grad_output_buffer.get(); + + for (int64_t i = begin; i < end; i++) { + int64_t outer_idx = i / num_chunks; + int64_t k = i % num_chunks; + int64_t inner_idx_begin = k * CHUNK_SIZE; + int64_t size = std::min(CHUNK_SIZE, inner_size - inner_idx_begin); + + // init + fVec zero_fvec = fVec(float(0)); + int64_t d0 = 0; + for (; d0 < size - (size % Vec::size()); d0 += Vec::size()) { + zero_fvec.store(tmp_sum_data + d0); + zero_fvec.store(tmp_sum_data + d0 + fVec::size()); + } + for (; d0 < size; d0++) { + tmp_sum_data[d0] = float(0); + } + + // compute sum of grad_output + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + const scalar_t* grad_output_ptr = grad_output_data_base + + outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + float* grad_output_buffer_ptr = + grad_output_buffer_data + dim_idx * CHUNK_SIZE; + + int64_t d1 = 0; + for (; d1 < size - (size % Vec::size()); d1 += Vec::size()) { + Vec grad_output_vec = Vec::loadu(grad_output_ptr + d1); + auto [grad_output_fvec0, grad_output_fvec1] = + vec::convert_to_float(grad_output_vec); + fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d1); + fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d1 + fVec::size()); + sum_fvec0 += grad_output_fvec0; + sum_fvec1 += grad_output_fvec1; + sum_fvec0.store(tmp_sum_data + d1); + sum_fvec1.store(tmp_sum_data + d1 + fVec::size()); + + // cache the 'converted' float grad_output + grad_output_fvec0.store(grad_output_buffer_ptr + d1); + grad_output_fvec1.store( + grad_output_buffer_ptr + d1 + fVec::size()); + } + for (; d1 < size; d1++) { + float grad_output_val = float(grad_output_ptr[d1]); + tmp_sum_data[d1] += grad_output_val; + grad_output_buffer_ptr[d1] = grad_output_val; + } + } + + // compute grad_output - output.exp() * sum + for (int64_t dim_idx = 0; dim_idx < dim_size; dim_idx++) { + int64_t offset = outer_idx * outer_stride + dim_idx * inner_size + + inner_idx_begin; + const scalar_t* output_ptr = output_data_base + offset; + scalar_t* grad_input_ptr = grad_input_data_base + offset; + float* grad_output_buffer_ptr = + grad_output_buffer_data + dim_idx * CHUNK_SIZE; + + int64_t d2 = 0; + for (; d2 < size - (size % Vec::size()); d2 += Vec::size()) { + Vec output_vec = Vec::loadu(output_ptr + d2); + auto [output_fvec0, output_fvec1] = + vec::convert_to_float(output_vec); + fVec sum_fvec0 = fVec::loadu(tmp_sum_data + d2); + fVec sum_fvec1 = fVec::loadu(tmp_sum_data + d2 + fVec::size()); + fVec grad_output_fvec0 = fVec::loadu(grad_output_buffer_ptr + d2); + fVec grad_output_fvec1 = + fVec::loadu(grad_output_buffer_ptr + d2 + fVec::size()); + fVec grad_input_fvec0 = + grad_output_fvec0 - output_fvec0.exp() * sum_fvec0; + fVec grad_input_fvec1 = + grad_output_fvec1 - output_fvec1.exp() * sum_fvec1; + Vec grad_input_vec = + vec::convert_from_float(grad_input_fvec0, grad_input_fvec1); + grad_input_vec.store(grad_input_ptr + d2); + } + for (; d2 < size; d2++) { + grad_input_ptr[d2] = grad_output_buffer_ptr[d2] - + std::exp(float(output_ptr[d2])) * tmp_sum_data[d2]; + } + } + } + }); +} + +template +struct vec_host_softmax_lastdim { + static void apply(const Tensor& output, const Tensor& input) { + int64_t outer_size = 1; + int64_t dim_size = input.size(input.ndimension() - 1); + for (int64_t i = 0; i < input.ndimension() - 1; ++i) + outer_size *= input.size(i); + const scalar_t* input_data_base = input.const_data_ptr(); + scalar_t* output_data_base = output.data_ptr(); + if (LogSoftMax) { + _vec_log_softmax_lastdim( + input_data_base, output_data_base, outer_size, dim_size); + } else { + _vec_softmax_lastdim( + input_data_base, output_data_base, outer_size, dim_size); + } + } +}; + +template +inline typename std::enable_if_t>, void> +_vec_softmax( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + using Vec16 = vec::Vectorized; + int64_t dim_stride = inner_size; + int64_t outer_stride = dim_size * dim_stride; + int vectorized_step = Vec16().size(); // Currently, we only support BFloat16/Half in this special implementation + // See Note: grain_size value of 0 + parallel_for( + 0, outer_size * inner_size, 0, [&](int64_t begin, int64_t end) { + int64_t idx = begin; + std::vector temp_vec_input(dim_size * vectorized_step); + std::vector temp_vec_output(dim_size * vectorized_step); + float* temp_vec_input_data = temp_vec_input.data(); + float* temp_vec_output_data = temp_vec_output.data(); + while (idx < end) { + int64_t outer_idx = idx / inner_size; + int64_t inner_idx = idx % inner_size; + if (((inner_idx + vectorized_step) <= inner_size) && ((idx + vectorized_step) <= end)) { + // Vectorization + const scalar_t* input_data = + input_data_base + outer_idx * outer_stride + inner_idx; + scalar_t* output_data = + output_data_base + outer_idx * outer_stride + inner_idx; + // Step 1: Get max Score + Vec16 max_vec_bf16 = Vec16::loadu(input_data); + std::tuple convert_result = vec::convert_to_float(max_vec_bf16); + Vec max_vec_o1 = std::get<0>(convert_result); + Vec max_vec_o2 = std::get<1>(convert_result); + std::get<0>(convert_result).store(temp_vec_input_data); + std::get<1>(convert_result).store(temp_vec_input_data + Vec().size()); + for (const auto d : c10::irange(1, dim_size)) { + Vec16 input_vec_bf16 = Vec16::loadu(input_data + d * dim_stride); + convert_result = vec::convert_to_float(input_vec_bf16); + max_vec_o1 = vec::maximum(max_vec_o1, std::get<0>(convert_result)); + max_vec_o2 = vec::maximum(max_vec_o2, std::get<1>(convert_result)); + std::get<0>(convert_result).store(temp_vec_input_data + d*vectorized_step); + std::get<1>(convert_result).store(temp_vec_input_data + d*vectorized_step + Vec().size()); + } + // Step2: Calculate sum + Vec sum_vec_o1 = Vec(0.0); + Vec sum_vec_o2 = Vec(0.0); + for (const auto d : c10::irange(dim_size)) { + Vec output_vec_o1 = Vec::loadu(temp_vec_input_data + d*vectorized_step); + Vec output_vec_o2 = Vec::loadu(temp_vec_input_data + d*vectorized_step + Vec().size()); + output_vec_o1 = (output_vec_o1 - max_vec_o1).exp(); + output_vec_o2 = (output_vec_o2 - max_vec_o2).exp(); + output_vec_o1.store(temp_vec_output_data + d*vectorized_step); + output_vec_o2.store(temp_vec_output_data + d*vectorized_step + Vec().size()); + + sum_vec_o1 = sum_vec_o1 + output_vec_o1; + sum_vec_o2 = sum_vec_o2 + output_vec_o2; + } + // Step3: Unify + for (const auto d : c10::irange(dim_size)) { + Vec output_vec_o1 = Vec::loadu(temp_vec_output_data + d*vectorized_step); + Vec output_vec_o2 = Vec::loadu(temp_vec_output_data + d*vectorized_step + Vec().size()); + output_vec_o1 = output_vec_o1/sum_vec_o1; + output_vec_o2 = output_vec_o2/sum_vec_o2; + Vec16 output_vec_bf16 = vec::convert_from_float(output_vec_o1, output_vec_o2); + output_vec_bf16.store(output_data + d * dim_stride); + } + idx += vectorized_step; + } else { + // Tail case(Scalar): it is exactly same logic as host_softmax + // inside aten/src/ATen/native/SoftMax.cpp. There are 2 kind of + // cases which will fall through this part: + // Case 1: For the idx at the end of total chunk for each thread, there are not enough numbers for parallelization. + // Case 2: For the idx at the end of each inner_size inside thread, there are not enough numbers for parallelization. + int64_t tail_number = ((idx+vectorized_step) > end) ? /*Case1*/ (end - idx) : /*Case2*/ (inner_size - inner_idx); + for (const auto i : c10::irange(tail_number)) { + outer_idx = (idx + i) / inner_size; + inner_idx = (idx + i) % inner_size; + const scalar_t* input_data = + input_data_base + outer_idx * outer_stride + inner_idx; + scalar_t* output_data = + output_data_base + outer_idx * outer_stride + inner_idx; + // Step1: Get max score + float max_input = float(input_data[0]); + for (const auto d : c10::irange(1, dim_size)) { + max_input = std::max(max_input, float(input_data[d * dim_stride])); + } + // Step2: Calculate the Sum + float sum_data = 0.0; + float temp_output_data = 0.0; + for (const auto d : c10::irange(dim_size)) { + temp_output_data = std::exp(input_data[d * dim_stride] - max_input); + sum_data += temp_output_data; + output_data[d * dim_stride] = scalar_t(temp_output_data); + } + // Step3: Unify + for (const auto d : c10::irange(dim_size)) { + output_data[d * dim_stride] = + scalar_t(float(output_data[d * dim_stride])/sum_data); + } + } + idx += tail_number; + } + } + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_softmax( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + using Vec = vec::Vectorized; + int64_t dim_stride = inner_size; + int64_t outer_stride = dim_size * dim_stride; + int vectorized_step = Vec().size(); + // See Note: grain_size value of 0 + parallel_for( + 0, outer_size * inner_size, 0, [&](int64_t begin, int64_t end) { + int64_t idx = begin; + while (idx < end) { + int64_t outer_idx = idx / inner_size; + int64_t inner_idx = idx % inner_size; + if (((inner_idx + vectorized_step) <= inner_size) && ((idx + vectorized_step) <= end)) { + // Vectorization + const scalar_t* input_data = + input_data_base + outer_idx * outer_stride + inner_idx; + scalar_t* output_data = + output_data_base + outer_idx * outer_stride + inner_idx; + // Step 1: Get max Score + Vec max_vec = Vec::loadu(input_data); + for (const auto d : c10::irange(1, dim_size)) { + Vec input_vec = Vec::loadu(input_data + d * dim_stride); + max_vec = vec::maximum(max_vec, input_vec); + } + // Step2: Calculate sum + Vec sum_vec = Vec(0.0); + for (const auto d : c10::irange(dim_size)) { + Vec output_vec = + (Vec::loadu(input_data + d * dim_stride) - max_vec).exp(); + output_vec.store(output_data + d * dim_stride); + sum_vec = sum_vec + output_vec; + } + // Step3: Unify + for (const auto d : c10::irange(dim_size)) { + Vec output_vec = + Vec::loadu(output_data + d * dim_stride) / sum_vec; + output_vec.store(output_data + d * dim_stride); + } + idx += vectorized_step; + } else { + // Tail case(Scalar): it is exactly same logic as host_softmax + // inside aten/src/ATen/native/SoftMax.cpp. There are 2 kind of + // cases which will fall through this part: + // Case 1: For the idx at the end of total chunk for each thread, there are not enough numbers for parallelization. + // Case 2: For the idx at the end of each inner_size inside thread, there are not enough numbers for parallelization. + int64_t tail_number = ((idx+vectorized_step) > end) ? /*Case1*/ (end - idx) : /*Case2*/ (inner_size - inner_idx); + for (const auto i : c10::irange(tail_number)) { + outer_idx = (idx + i) / inner_size; + inner_idx = (idx + i) % inner_size; + const scalar_t* input_data = + input_data_base + outer_idx * outer_stride + inner_idx; + scalar_t* output_data = + output_data_base + outer_idx * outer_stride + inner_idx; + // Step1: Get max score + scalar_t max_input = input_data[0]; + for (const auto d : c10::irange(1, dim_size)) { + max_input = std::max(max_input, input_data[d * dim_stride]); + } + // Step2: Calculate the Sum + scalar_t sum_data = 0; + for (const auto d : c10::irange(dim_size)) { + output_data[d * dim_stride] = + std::exp(input_data[d * dim_stride] - max_input); + sum_data += output_data[d * dim_stride]; + } + // Step3: Unify + for (const auto d : c10::irange(dim_size)) { + output_data[d * dim_stride] = + output_data[d * dim_stride]/sum_data; + } + } + idx += tail_number; + } + } + }); +} + +// NB: fast kernel for log_softmax when dim != -1 +// input shape is normalized to {outer_size, dim_size, inner_size} +// +// The algorithm requires to load input tensor 3 times, to increase parallelism +// and cache hit rate, inner_size is blocked as: +// inner_size: {CHUNK_SIZE, CHUNK_SIZE, ..., Remainder} +// +// Parallel on {outer_size, num_chunks} and do vertical reduction on each block of +// {dim_size, CHUNK_SIZE}, block size (128KB) selected to be L2 hit. +// +template +inline typename std::enable_if_t>, void> +_vec_logsoftmax( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + const auto [CHUNK_SIZE_binding, num_chunks_binding] = vec_logsoftmax_chunk_size_and_num_chunks( + inner_size, dim_size); + // Work around "capturing a structured binding is not yet supported in OpenMP". + const auto CHUNK_SIZE = CHUNK_SIZE_binding; + const auto num_chunks = num_chunks_binding; + + // See Note: grain_size value of 0 + at::parallel_for(0, outer_size * num_chunks, 0, [&](int64_t begin, int64_t end) { + serial_vec_logsoftmax_range( + input_data_base, + output_data_base, + inner_size, + CHUNK_SIZE, + num_chunks, + dim_size, + begin, + end); + }); +} + +template +inline typename std::enable_if_t>, void> +_vec_logsoftmax( + const scalar_t* input_data_base, + scalar_t* output_data_base, + int64_t outer_size, + int64_t inner_size, + int64_t dim_size) { + const auto [CHUNK_SIZE_binding, num_chunks_binding] = vec_logsoftmax_chunk_size_and_num_chunks( + inner_size, dim_size); + // Work around "capturing a structured binding is not yet supported in OpenMP". + const auto CHUNK_SIZE = CHUNK_SIZE_binding; + const auto num_chunks = num_chunks_binding; + + // See Note: grain_size value of 0 + at::parallel_for(0, outer_size * num_chunks, 0, [&](int64_t begin, int64_t end) { + serial_vec_logsoftmax_range( + input_data_base, + output_data_base, + inner_size, + CHUNK_SIZE, + num_chunks, + dim_size, + begin, + end); + }); +} + +template +struct vec_softmax { + static void apply(const Tensor& output, const Tensor& input, int64_t dim) { + int64_t outer_size = 1; + int64_t dim_size = input.size(dim); + int64_t inner_size = 1; + for (const auto i : c10::irange(dim))outer_size *= input.size(i); + for (int64_t i = dim + 1; i < input.dim(); ++i) + inner_size *= input.size(i); + const scalar_t* input_data_base = input.const_data_ptr(); + scalar_t* output_data_base = output.data_ptr(); + if (LogSoftMax) { + _vec_logsoftmax( + input_data_base, output_data_base, outer_size, inner_size, dim_size); + } else { + _vec_softmax( + input_data_base, output_data_base, outer_size, inner_size, dim_size); + } + } +}; + +template +struct vec_host_softmax_backward_lastdim { + static void + apply(const Tensor& grad_input, const Tensor& grad, const Tensor& output) { + int64_t outer_size = 1; + int64_t dim_size = grad.size(grad.ndimension() - 1); + for (int64_t i = 0; i < grad.ndimension() - 1; ++i) + outer_size *= grad.size(i); + scalar_t* grad_input_data_base = grad_input.mutable_data_ptr(); + const scalar_t* grad_data_base = grad.const_data_ptr(); + const scalar_t* output_data_base = output.const_data_ptr(); + _vec_host_softmax_backward_lastdim( + grad_input_data_base, + grad_data_base, + output_data_base, + outer_size, + dim_size); + } +}; + +template +struct vec_host_softmax_backward { + static void apply( + const Tensor& grad_input, + const Tensor& grad, + const Tensor& output, + int64_t dim) { + int64_t outer_size = 1; + int64_t dim_size = grad.size(dim); + int64_t inner_size = 1; + for (const auto i : c10::irange(dim)) { + outer_size *= grad.size(i); + } + for (int64_t i = dim + 1; i < grad.dim(); ++i) { + inner_size *= grad.size(i); + } + scalar_t* grad_input_data_base = grad_input.mutable_data_ptr(); + const scalar_t* grad_output_data_base = grad.const_data_ptr(); + const scalar_t* output_data_base = output.const_data_ptr(); + if (LogSoftMax) { + _vec_log_softmax_backward( + grad_input_data_base, + grad_output_data_base, + output_data_base, + outer_size, + inner_size, + dim_size); + } else { + _vec_softmax_backward( + grad_input_data_base, + grad_output_data_base, + output_data_base, + outer_size, + inner_size, + dim_size); + } + } +}; + +void softmax_lastdim_kernel_impl( + const Tensor& result, + const Tensor& self) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::BFloat16, at::ScalarType::Half, self.scalar_type(), + "softmax_lastdim_kernel_impl", + [&] { vec_host_softmax_lastdim::apply(result, self); }); +} + +void softmax_kernel_impl(const Tensor& result, const Tensor& self, int64_t dim) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, self.scalar_type(), + "softmax_kernel_impl", + [&] { vec_softmax::apply(result, self, dim); }); +} + +void log_softmax_lastdim_kernel_impl( + const Tensor& result, + const Tensor& self) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::BFloat16, at::ScalarType::Half, self.scalar_type(), + "log_softmax_lastdim_kernel_impl", + [&] { vec_host_softmax_lastdim::apply(result, self); }); +} + +void log_softmax_kernel_impl(const Tensor& result, const Tensor& self, int64_t dim) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, self.scalar_type(), + "log_softmax_kernel_impl", + [&] { vec_softmax::apply(result, self, dim); }); +} + +void softmax_backward_lastdim_kernel_impl( + const Tensor& grad_input, + const Tensor& grad, + const Tensor& output) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::BFloat16, at::ScalarType::Half, grad.scalar_type(), + "softmax_backward_lastdim_kernel_impl", [&] { + vec_host_softmax_backward_lastdim::apply( + grad_input, grad, output); + }); +} + +void log_softmax_backward_lastdim_kernel_impl( + const Tensor& grad_input, + const Tensor& grad, + const Tensor& output) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::BFloat16, at::ScalarType::Half, grad.scalar_type(), + "log_softmax_backward_lastdim_kernel_impl", [&] { + vec_host_softmax_backward_lastdim::apply( + grad_input, grad, output); + }); +} + +void softmax_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad, + const Tensor& output, + int64_t dim) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::BFloat16, + at::ScalarType::Half, + grad.scalar_type(), + "softmax_backward_kernel_impl", + [&] { + vec_host_softmax_backward::apply( + grad_input, grad, output, dim); + }); +} + +void log_softmax_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad, + const Tensor& output, + int64_t dim) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::BFloat16, + at::ScalarType::Half, + grad.scalar_type(), + "log_softmax_backward_kernel_impl", + [&] { + vec_host_softmax_backward::apply( + grad_input, grad, output, dim); + }); +} + +} // anonymous namespace + +ALSO_REGISTER_AVX512_DISPATCH(softmax_lastdim_kernel, &softmax_lastdim_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH(log_softmax_lastdim_kernel, &log_softmax_lastdim_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH( + softmax_backward_lastdim_kernel, + &softmax_backward_lastdim_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH( + log_softmax_backward_lastdim_kernel, + &log_softmax_backward_lastdim_kernel_impl) + +ALSO_REGISTER_AVX512_DISPATCH(softmax_kernel, &softmax_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH(log_softmax_kernel, &log_softmax_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH(softmax_backward_kernel, &softmax_backward_kernel_impl) +ALSO_REGISTER_AVX512_DISPATCH( + log_softmax_backward_kernel, + &log_softmax_backward_kernel_impl) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SoftmaxKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SoftmaxKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..fac10bad489fe3358eb2cdb79d5e6edbc20f14d7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SoftmaxKernel.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +namespace at { +class Tensor; + +namespace native { + +using forward_fn = void (*)(const Tensor&, const Tensor&); +using backward_fn = void(*)(const Tensor &, const Tensor &, const Tensor&); + +DECLARE_DISPATCH(forward_fn, softmax_lastdim_kernel) +DECLARE_DISPATCH(forward_fn, log_softmax_lastdim_kernel) +DECLARE_DISPATCH(backward_fn, softmax_backward_lastdim_kernel) +DECLARE_DISPATCH(backward_fn, log_softmax_backward_lastdim_kernel) + +using forward_fn_with_dim = void(*)(const Tensor &, const Tensor &, const int64_t); +using backward_fn_with_dim = + void (*)(const Tensor&, const Tensor&, const Tensor&, const int64_t); + +DECLARE_DISPATCH(forward_fn_with_dim, softmax_kernel) +DECLARE_DISPATCH(forward_fn_with_dim, log_softmax_kernel) +DECLARE_DISPATCH(backward_fn_with_dim, softmax_backward_kernel) +DECLARE_DISPATCH(backward_fn_with_dim, log_softmax_backward_kernel) +} +} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SortingKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SortingKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9471cd471e8acd5e05a9390e90f84ad077110323 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SortingKernel.cpp @@ -0,0 +1,270 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef USE_FBGEMM +#include +#endif + +namespace at::native { + +namespace { + +template +void _dim_apply( + const TensorBase &values, + const TensorBase &indices, + int64_t dim, + const std::string& method_name, + const func_t& f) { + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(values.sizes(), /*squash_dims=*/dim) + .add_output(values) + .add_output(indices) + .build(); + + auto values_dim_stride = values.stride(dim); + auto indices_dim_stride = indices.stride(dim); + auto dim_size = values.size(dim); + + AT_DISPATCH_V2( + iter.dtype(), "sorting_kernel_method_name", AT_WRAP([&] { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* values_data_bytes = data[0]; + auto* indices_data_bytes = data[1]; + + if(values_data_bytes==nullptr || indices_data_bytes==nullptr){ + return; + } + + for ([[maybe_unused]] const auto i : c10::irange(n)) { + f(reinterpret_cast(values_data_bytes), + values_dim_stride, + reinterpret_cast(indices_data_bytes), + indices_dim_stride, + dim_size); + + values_data_bytes += strides[0]; + indices_data_bytes += strides[1]; + } + }; + + int64_t grain_size = internal::GRAIN_SIZE / std::max(int64_t{1}, dim_size); + iter.for_each(loop, /*grain_size=*/grain_size); + }), kBool, kHalf, kBFloat16, AT_EXPAND(AT_ALL_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES) + ); +} + +template +struct KeyValueCompAsc { + template + constexpr bool operator()(LHS lhs, RHS rhs) const { + return (!_isnan(get<0>(lhs)) && _isnan(get<0>(rhs))) + || (get<0>(lhs) < get<0>(rhs)); + } +}; + +template +struct KeyValueCompDesc { + template + constexpr bool operator()(LHS lhs, RHS rhs) const { + return (_isnan(get<0>(lhs)) && !_isnan(get<0>(rhs))) + || (get<0>(lhs) > get<0>(rhs)); + } +}; + +#ifdef USE_FBGEMM +bool can_use_radix_sort(const TensorBase& values, const bool descending) { + // radix_sort can be used only for 1D data + if (values.dim() != 1) return false; + // radix_sort sorts in ascending order + if (descending) return false; + // radix_sort works for integer values + if (!at::isIntegralType(values.scalar_type(), /*includeBool=*/false)) return false; + // performance improvements are visible for bigger tensor sizes, when radix_sort + // is accelerated with OpenMP + if (values.numel() < at::internal::GRAIN_SIZE || !fbgemm::is_radix_sort_accelerated_with_openmp()) return false; + // TODO(DamianSzwichtenberg): radix_sort is a stable sorting algorithm, + // should we check here, whether stable is set to true? + + return true; +} + +void parallel_sort1d_kernel( + const TensorBase& values, + const TensorBase& indices) { + AT_DISPATCH_INTEGRAL_TYPES(values.scalar_type(), "parallel_sort1d_kernel", [&] { + const auto elements = values.numel(); + auto* const keys = values.data_ptr(); + auto* const vals = indices.data_ptr(); + std::vector tmp_keys(elements); + std::vector tmp_vals(elements); + const scalar_t* sorted_keys = nullptr; + const int64_t* sorted_vals = nullptr; + std::tie(sorted_keys, sorted_vals) = fbgemm::radix_sort_parallel( + keys, + vals, + tmp_keys.data(), + tmp_vals.data(), + elements, + std::numeric_limits::max(), + values.scalar_type() != ScalarType::Byte); + + const bool sorted_in_place = keys == sorted_keys; + if (!sorted_in_place) { + const auto num_threads = at::get_num_threads(); + at::parallel_for(0, elements, elements / num_threads, [&](int64_t begin, int64_t end) { + const auto job_size = end - begin; + vec::map([](vec::Vectorized x) -> vec::Vectorized { return x; }, keys + begin, sorted_keys + begin, job_size); + vec::map([](vec::Vectorized x) -> vec::Vectorized { return x; }, vals + begin, sorted_vals + begin, job_size); + }); + } + }); +} +#endif + +template +inline void sort_kernel_impl(const value_accessor_t& value_accessor, + const indices_accessor_t& indices_accessor, + int64_t dim_size, bool descending, bool stable) { + auto composite_accessor = CompositeRandomAccessorCPU< + value_accessor_t, indices_accessor_t + >(value_accessor, indices_accessor); + if (descending) { + if (stable) { + std::stable_sort(composite_accessor, composite_accessor + dim_size, + KeyValueCompDesc()); + } else { + std::sort(composite_accessor, composite_accessor + dim_size, + KeyValueCompDesc()); + } + } else { + if (stable) { + std::stable_sort(composite_accessor, composite_accessor + dim_size, + KeyValueCompAsc()); + } else { + std::sort(composite_accessor, composite_accessor + dim_size, + KeyValueCompAsc()); + } + } +} + +void sort_kernel( + const TensorBase& self, + const TensorBase& values, + const TensorBase& indices, + int64_t dim, + bool descending, + bool stable) { + dim = maybe_wrap_dim(dim, values.dim()); + _fill_indices(indices, dim); + if (self.stride(dim) == 0) { + // check if stride is zero + // https://github.com/pytorch/pytorch/issues/91420 + return; + } +#ifdef USE_FBGEMM + if (can_use_radix_sort(values, descending)) { + parallel_sort1d_kernel(values, indices); + return; + } +#endif + _dim_apply( + values, indices, dim, + "sort_cpu", [&]( + auto* values, int64_t values_dim_stride, + auto* indices, int64_t indices_dim_stride, + int64_t dim_size + ) { + using scalar_t = std::remove_pointer_t; + if (values_dim_stride == 1 && indices_dim_stride == 1) { + sort_kernel_impl< + scalar_t, decltype(values), decltype(indices) + >(values, indices, dim_size, descending, stable); + } else if (values_dim_stride == 1 && indices_dim_stride != 1) { + auto indices_accessor = StridedRandomAccessor( + indices, indices_dim_stride); + sort_kernel_impl< + scalar_t, decltype(values), decltype(indices_accessor) + >(values, indices_accessor, dim_size, descending, stable); + } else if (values_dim_stride != 1 && indices_dim_stride == 1) { + auto values_accessor = StridedRandomAccessor( + values, values_dim_stride); + sort_kernel_impl< + scalar_t, decltype(values_accessor), decltype(indices) + >(values_accessor, indices, dim_size, descending, stable); + } else { + auto values_accessor = StridedRandomAccessor( + values, values_dim_stride); + auto indices_accessor = StridedRandomAccessor( + indices, indices_dim_stride); + sort_kernel_impl< + scalar_t, decltype(values_accessor), decltype(indices_accessor) + >(values_accessor, indices_accessor, dim_size, descending, stable); + } + } + ); +} + +void topk_kernel( + const TensorBase &values, + const TensorBase &indices, + const TensorBase &self, + int64_t k, + int64_t dim, + bool largest, + bool sorted) { + auto sizes = self.sizes(); + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(sizes, /*squash_dims=*/dim) + .add_output(values) + .add_output(indices) + .add_const_input(self) + .build(); + + auto mode_values_stride = values.strides()[dim]; + auto mode_indices_stride = indices.strides()[dim]; + auto tmp_values_stride = self.strides()[dim]; + + AT_DISPATCH_ALL_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, self.scalar_type(), "topk_cpu", [&] { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + if (self.scalar_type() == ScalarType::BFloat16) { + return topk_impl_loop( + mode_values_stride, mode_indices_stride, tmp_values_stride, + k, sizes[dim], largest, sorted, data, strides, n); + } else { + return topk_impl_loop( + mode_values_stride, mode_indices_stride, tmp_values_stride, + k, sizes[dim], largest, sorted, data, strides, n); + } + }; + + int64_t grain_size = internal::GRAIN_SIZE / std::max(int64_t{1}, sizes[dim]); + iter.for_each(loop, /*grain_size=*/grain_size); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(sort_stub, &sort_kernel) +REGISTER_DISPATCH(topk_stub, &topk_kernel) + +} //at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SparseFactories.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SparseFactories.cpp new file mode 100644 index 0000000000000000000000000000000000000000..655666b2b0d40282fb182d73ddd8987cd7cbee7f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SparseFactories.cpp @@ -0,0 +1,65 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { +void _spdiags_kernel_cpu( + TensorIterator& iter, + const TensorBase& diagonals, + TensorBase& values, + TensorBase& indices) { + auto* row_index_write_ptr = indices.data_ptr(); + auto* col_index_write_ptr = row_index_write_ptr ? row_index_write_ptr + indices.stride(0) : nullptr; + const int64_t diagonals_index_stride = diagonals.stride(0); + const int64_t diagonals_read_stride = diagonals.stride(1); + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND4( + at::ScalarType::BFloat16, + at::ScalarType::Half, + at::ScalarType::Bool, + at::ScalarType::ComplexHalf, + diagonals.scalar_type(), + "spdiags_cpu", + [&] { + auto* const values_write_ptr = values.data_ptr(); + const auto* const diagonals_ptr = diagonals.const_data_ptr(); + + cpu_kernel( + iter, + [&](int64_t diag_index, + int64_t diag_offset, + int64_t out_offset, + int64_t n_out) -> int64_t { + if (n_out > 0) { + auto* rows_start = row_index_write_ptr + out_offset; + auto* cols_start = col_index_write_ptr + out_offset; + auto* vals_start = values_write_ptr + out_offset; + const int64_t first_col = std::max(diag_offset, 0); + const int64_t first_row = first_col - diag_offset; + auto* data_read = (diagonals_ptr + + diagonals_index_stride * diag_index + + first_col * diagonals_read_stride); + for (int64_t i = 0; i < n_out; ++i) { + rows_start[i] = first_row + i; + cols_start[i] = first_col + i; + vals_start[i] = data_read[i * diagonals_read_stride]; + } + } + // dummy return + return 0; + }); + }); +} + +} // namespace + +REGISTER_DISPATCH(spdiags_kernel_stub, &_spdiags_kernel_cpu) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SpmmReduceKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SpmmReduceKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea9abdce86e495e1e619cf603fda9951a95ca75e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SpmmReduceKernel.cpp @@ -0,0 +1,565 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +template +inline void _update(at::opmath_type* out_ptr, int64_t e, int64_t c, const scalar_t val, const scalar_t* other_data, int64_t K) { + using opmath_t = at::opmath_type; + using Vec = vec::Vectorized; + using aVec = VecType; + constexpr int64_t kVecSize = Vec::size(); + constexpr int64_t kVLEN = kVecSize * 4; + + int64_t k = 0; + aVec val_vec = aVec((opmath_t)val); + const scalar_t* other_ptr = other_data + c * K; + + for (; k < K - (K % kVLEN); k += kVLEN) { + aVec out_vec0 = aVec::loadu(out_ptr + k); + aVec out_vec1 = aVec::loadu(out_ptr + k + kVecSize); + aVec out_vec2 = aVec::loadu(out_ptr + k + kVecSize * 2); + aVec out_vec3 = aVec::loadu(out_ptr + k + kVecSize * 3); + + out_vec0 = update(out_vec0, aVec::loadu(other_ptr + k) * val_vec); + out_vec1 = update(out_vec1, aVec::loadu(other_ptr + k + kVecSize) * val_vec); + out_vec2 = update(out_vec2, aVec::loadu(other_ptr + k + kVecSize * 2) * val_vec); + out_vec3 = update(out_vec3, aVec::loadu(other_ptr + k + kVecSize * 3) * val_vec); + + out_vec0.store(out_ptr + k); + out_vec1.store(out_ptr + k + kVecSize); + out_vec2.store(out_ptr + k + kVecSize * 2); + out_vec3.store(out_ptr + k + kVecSize * 3); + } + for (; k < K - (K % kVecSize); k += kVecSize) { + aVec out_vec = aVec::loadu(out_ptr + k); + out_vec = update(out_vec, aVec::loadu(other_ptr + k) * val_vec); + out_vec.store(out_ptr + k); + } + for (; k < K; k++) { + opmath_t out_val = opmath_t(out_ptr[k]); + out_val = update(out_val, opmath_t(other_ptr[k]) * opmath_t(val)); + out_ptr[k] = out_val; + } +} + +template +void spmm_reduce_kernel_impl( + const Tensor& out, + const Tensor& crow_indices, + const Tensor& col_indices, + const Tensor& values, + const Tensor& other_) { + + int64_t nnz = values.numel(); + if (nnz == 0) { + return; + } + + auto other = other_.contiguous(); + + // access `crow_indices`, `col_indices` and `values` via TensorAccessor + scalar_t* out_data = out.data_ptr(); + auto csr_data = crow_indices.accessor(); + auto col_data = col_indices.accessor(); + auto val_data = values.accessor(); + const scalar_t* other_data = other.const_data_ptr(); + + int64_t M = crow_indices.numel() - 1; + int64_t K = other.size(-1); + + int num_threads = at::get_num_threads(); + using opmath_t = at::opmath_type; + Tensor buffer; + opmath_t* buffer_data = nullptr; + static constexpr bool need_acc = is_reduced_floating_point_v; + if constexpr (need_acc) { + auto acc_type = at::toAccumulateType(out.scalar_type(), /*is_cuda=*/true); + buffer = at::zeros({num_threads, K}, out.options().dtype(acc_type)); + buffer_data = buffer.data_ptr(); + } + + utils::parallel_sparse_csr(csr_data, M, nnz, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, + "expect thread id smaller than ", num_threads, ", got thread id ", tid); + opmath_t* buffer_ptr = nullptr; + + int64_t row_start = 0, row_end = 0; + for (const auto m : c10::irange(begin, end)) { + row_start = csr_data[m]; + row_end = csr_data[m + 1]; + + scalar_t* out_ptr = out_data + m * K; + if constexpr (need_acc) { + buffer_ptr = buffer_data + tid * K; + } else { + buffer_ptr = reinterpret_cast(out_ptr); + } + + // step 1: reinit the output row for reduce type 'amax' and 'amin' + int64_t count = row_end - row_start; + if (count != 0) { + _init(out_ptr, buffer_ptr, K, /*include_self*/false); + } + + // step 2: reduce, do blocking on rowwise to reduce write memory bandwidth + constexpr int64_t CHUNK_SIZE = 16; + for (int64_t e0 = row_start; e0 < row_end; e0 += CHUNK_SIZE) { + int64_t e1 = std::min(e0 + CHUNK_SIZE, row_end); + for (const auto e : c10::irange(e0, e1)) { + int64_t c = col_data[e]; + scalar_t val = val_data[e]; + _update(buffer_ptr, e, c, val, other_data, K); + } + } + if constexpr (need_acc) { + if (count != 0) { + vec::convert(buffer_ptr, out_ptr, K); + } + } + + // step 3: finalize + write(out_ptr, count, K); + } + }); +} + +// update both val and arg, used for `amin` and `amax` +// it is a little troublesome to vectorize it since `scalar_t` and `index_t` +// might have different vector length, for example, each vector holds 8 floats +// and 4 int64_t. +template +inline void update_with_index(scalar_t *val, scalar_t new_val, index_t *arg, index_t new_arg) { + if ((reduce == ReductionType::MIN && new_val < *val) || + (reduce == ReductionType::MAX && new_val > *val) || + at::_isnan(new_val)) { + *val = new_val; + *arg = new_arg; + } +} + +template +void spmm_reduce_arg_kernel_impl( + const Tensor& out, + const Tensor& arg_out, + const Tensor& crow_indices, + const Tensor& col_indices, + const Tensor& values, + const Tensor& other_) { + + TORCH_CHECK(reduce == ReductionType::MAX || reduce == ReductionType::MIN); + int64_t nnz = values.numel(); + if (nnz == 0) { + return; + } + + auto other = other_.contiguous(); + + scalar_t* out_data = out.data_ptr(); + index_t* arg_out_data = arg_out.data_ptr(); + auto csr_data = crow_indices.accessor(); + auto col_data = col_indices.accessor(); + auto val_data = values.accessor(); + const scalar_t* other_data = other.const_data_ptr(); + + int64_t M = crow_indices.numel() - 1; + int64_t K = other.size(-1); + + int num_threads = at::get_num_threads(); + using opmath_t = at::opmath_type; + Tensor buffer; + opmath_t* buffer_data = nullptr; + static constexpr bool need_acc = is_reduced_floating_point_v; + if constexpr (need_acc) { + auto acc_type = at::toAccumulateType(out.scalar_type(), /*is_cuda=*/true); + buffer = at::zeros({num_threads, K}, out.options().dtype(acc_type)); + buffer_data = buffer.data_ptr(); + } + + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, + "expect thread id smaller than ", num_threads, ", got thread id ", tid); + opmath_t* buffer_ptr = nullptr; + + int64_t row_start = 0, row_end = 0, c = 0; + for (const auto m : c10::irange(begin, end)) { + row_start = csr_data[m]; + row_end = csr_data[m + 1]; + + scalar_t* out_ptr = out_data + m * K; + index_t* arg_out_ptr = arg_out_data + m * K; + if constexpr (need_acc) { + buffer_ptr = buffer_data + tid * K; + } else { + buffer_ptr = reinterpret_cast(out_ptr); + } + + if (row_end != row_start) { + _init(out_ptr, buffer_ptr, K, /*include_self*/false); + for (const auto e : c10::irange(row_start, row_end)) { + c = col_data[e]; + opmath_t val = opmath_t(val_data[e]); + + const scalar_t* other_ptr = other_data + c * K; + for (const auto k : c10::irange(K)) { + update_with_index( + &buffer_ptr[k], opmath_t(val * other_ptr[k]), &arg_out_ptr[k], index_t(e)); + }; + } + } + if constexpr (need_acc) { + if (row_end != row_start) { + vec::convert(buffer_ptr, out_ptr, K); + } + } + } + }); +} + +template +void spmm_reduce_backward_input_kernel_impl( + const Tensor& grad_self, + const Tensor& grad_out_, + const Tensor& crow_indices, + const Tensor& col_indices, + const Tensor& other_, + const Tensor& row_indices) { + + int64_t nnz = grad_self._nnz(); + if (nnz == 0) { + return; + } + + auto grad_out = grad_out_.contiguous(); + auto other = other_.contiguous(); + + auto values = grad_self.values(); + auto grad_values_data = values.accessor(); + const scalar_t* grad_out_data = grad_out.const_data_ptr(); + auto crow_data = crow_indices.accessor(); + auto col_data = col_indices.accessor(); + const scalar_t* other_data = other.const_data_ptr(); + auto row_data = row_indices.accessor(); + + int64_t K = grad_out.size(1); + + using Vec = vec::Vectorized>; + at::parallel_for(0, nnz, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + index_t row = row_data[i], col = col_data[i]; + + scalar_t val = vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + other_data + col * K, + grad_out_data + row * K, + K); + + if (reduce == ReductionType::MEAN) { + index_t row_start = crow_data[row], row_end = crow_data[row + 1]; + val /= (row_end - row_start); + } + + grad_values_data[i] = val; + } + }); +} + +// backward for reduce type 'amax' or 'amin' +template +void spmm_reduce_backward_input_arg_kernel_impl( + const Tensor& grad_self, + const Tensor& grad_out_, + const Tensor& col_indices, + const Tensor& other_, + const Tensor& arg_out_) { + + int64_t nnz = grad_self._nnz(); + if (nnz == 0) { + return; + } + + auto grad_out = grad_out_.contiguous(); + auto other = other_.contiguous(); + auto arg_out = arg_out_.contiguous(); + + auto grad_values = grad_self.values(); + auto grad_values_data = grad_values.accessor(); + const scalar_t* grad_out_data = grad_out.const_data_ptr(); + auto col_data = col_indices.accessor(); + const scalar_t* other_data = other.const_data_ptr(); + const index_t* arg_out_data = arg_out.const_data_ptr(); + + int64_t M = grad_out.size(0); + int64_t K = grad_out.size(1); + auto grad = at::empty({M, K}, grad_out.options()); + scalar_t* grad_data = grad.mutable_data_ptr(); + + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + for (const auto m : c10::irange(begin, end)) { + const scalar_t* grad_out_ptr = grad_out_data + m * K; + scalar_t* grad_ptr = grad_data + m * K; + const index_t* arg_out_ptr = arg_out_data + m * K; + + for (const auto k : c10::irange(K)) { + if (arg_out_ptr[k] == index_t(nnz)) { + grad_ptr[k] = scalar_t(0); + } else { + // collect weight at max/min indices + index_t col = col_data[arg_out_data[m * K + k]]; + grad_ptr[k] = other_data[col * K + k] * grad_out_ptr[k]; + } + } + } + }); + + // scatter_add, consider to parallel this with atomic + for (const auto i : c10::irange(M * K)) { + index_t ind = arg_out_data[i]; + if (ind != index_t(nnz)) { + grad_values_data[ind] += grad_data[i]; + } + } +} + +template +void spmm_reduce_normalize_values_kernel_impl( + const Tensor& normalized_values, + const Tensor& values, + const Tensor& crow_indices, + const Tensor& row_indices) { + + int64_t nnz = values.numel(); + if (nnz == 0) { + return; + } + + auto normalized_values_data = normalized_values.accessor(); + auto values_data = values.accessor(); + auto crow_data = crow_indices.accessor(); + auto row_data = row_indices.accessor(); + + at::parallel_for(0, nnz, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + index_t row = row_data[i]; + index_t row_start = crow_data[row], row_end = crow_data[row + 1]; + // Note that when the row index row is listed in row_indices, + // then crow_indices[row+1] > crow_indices[row] holds + normalized_values_data[i] = values_data[i] / (row_end - row_start); + } + }); +} + +template +void spmm_reduce_backward_other_arg_kernel_impl( + const Tensor& grad_other, + const Tensor& grad_out_, + const Tensor& col_indices, + const Tensor& values, + const Tensor& arg_out_) { + + int64_t nnz = values.numel(); + if (nnz == 0) { + return; + } + + auto grad_out = grad_out_.contiguous(); + auto arg_out = arg_out_.contiguous(); + + scalar_t* grad_other_data = grad_other.data_ptr(); + const scalar_t* grad_out_data = grad_out.const_data_ptr(); + auto col_data = col_indices.accessor(); + auto values_data = values.accessor(); + const index_t* arg_out_data = arg_out.const_data_ptr(); + + int64_t M = grad_out.size(0); + int64_t K = grad_out.size(1); + auto grad = at::empty({M, K}, grad_out.options()); + scalar_t* grad_data = grad.mutable_data_ptr(); + + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + for (const auto m : c10::irange(begin, end)) { + const scalar_t* grad_out_ptr = grad_out_data + m * K; + scalar_t* grad_ptr = grad_data + m * K; + const index_t* arg_out_ptr = arg_out_data + m * K; + + for (const auto k : c10::irange(K)) { + if (arg_out_ptr[k] == index_t(nnz)) { + grad_ptr[k] = scalar_t(0); + } else { + grad_ptr[k] = values_data[arg_out_ptr[k]] * grad_out_ptr[k]; + } + } + } + }); + + // scatter_add, consider to parallel this with atomic + for (const auto m : c10::irange(M)) { + for (const auto k : c10::irange(K)) { + index_t ind = arg_out_data[m * K + k]; + if (ind != index_t(nnz)) { + index_t col = col_data[ind]; + grad_other_data[col * K + k] += grad_data[m * K + k]; + } + } + } +} + +void spmm_reduce_kernel( + const Tensor& out, + const Tensor& crow_indices, + const Tensor& col_indices, + const Tensor& values, + const Tensor& other, + ReductionType reduce_op) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, values.scalar_type(), "spmm_reduce_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(col_indices.scalar_type(), "spmm_reduce_indices", [&]() { + AT_DISPATCH_REDUCTION_TYPES(reduce_op, [&]() { + spmm_reduce_kernel_impl( + out, crow_indices, col_indices, values, other); + }); + }); + }); +} + +void spmm_reduce_arg_kernel( + const Tensor& out, + const Tensor& arg_out, + const Tensor& crow_indices, + const Tensor& col_indices, + const Tensor& values, + const Tensor& other, + ReductionType reduce_op) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, values.scalar_type(), "spmm_reduce_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(col_indices.scalar_type(), "spmm_reduce_indices", [&]() { + AT_DISPATCH_REDUCTION_TYPES(reduce_op, [&]() { + spmm_reduce_arg_kernel_impl( + out, arg_out, crow_indices, col_indices, values, other); + }); + }); + }); +} + +void spmm_reduce_backward_input_kernel( + const Tensor& grad_self, + const Tensor& grad_out, + const Tensor& crow_indices, + const Tensor& col_indices, + const Tensor& other, + const Tensor& row_indices, + ReductionType reduce_op) { + TORCH_CHECK(reduce_op == ReductionType::SUM || reduce_op == ReductionType::MEAN); + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, other.scalar_type(), "spmm_reduce_backward_input_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(col_indices.scalar_type(), "spmm_reduce_backward_input_indices", [&]() { + AT_DISPATCH_REDUCTION_TYPES(reduce_op, [&]() { + spmm_reduce_backward_input_kernel_impl( + grad_self, grad_out, crow_indices, col_indices, other, row_indices); + }); + }); + }); +} + +void spmm_reduce_backward_input_arg_kernel( + const Tensor& grad_self, + const Tensor& grad_out, + const Tensor& col_indices, + const Tensor& other, + const Tensor& arg_out, + ReductionType reduce_op) { + TORCH_CHECK(reduce_op == ReductionType::MAX || reduce_op == ReductionType::MIN); + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, other.scalar_type(), "spmm_reduce_backward_input_arg_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(col_indices.scalar_type(), "spmm_reduce_backward_input_arg_indices", [&]() { + spmm_reduce_backward_input_arg_kernel_impl( + grad_self, grad_out, col_indices, other, arg_out); + }); + }); +} + +void spmm_reduce_normalize_values_kernel( + const Tensor& normalized_values, + const Tensor& values, + const Tensor& crow_indices, + const Tensor& row_indices) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, values.scalar_type(), "spmm_reduce_normalize_values_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(crow_indices.scalar_type(), "spmm_reduce_normalize_values_indices", [&]() { + spmm_reduce_normalize_values_kernel_impl( + normalized_values, values, crow_indices, row_indices); + }); + }); +} + +void spmm_reduce_backward_other_kernel( + const Tensor& grad_other, + const Tensor& grad_out, + const Tensor& crow_indices, + const Tensor& values, + const Tensor& row_indices, + const Tensor& ccol_indices, + const Tensor& csr2csc, + ReductionType reduce_op) { + TORCH_CHECK(reduce_op == ReductionType::SUM || reduce_op == ReductionType::MEAN); + // need to permute row_indices to CSC order + auto row = row_indices.index_select(0, csr2csc); + + Tensor val; + if (reduce_op == ReductionType::MEAN) { + // for reduce type "mean", need to normalize the values + // with rowcount for each of the nonzero element. + Tensor normalized_values = at::empty(values.sizes(), values.options()); + spmm_reduce_normalize_values_kernel(normalized_values, values, crow_indices, row_indices); + val = normalized_values.index_select(0, csr2csc); + } else { + val = values.index_select(0, csr2csc); + } + + spmm_reduce_kernel(grad_other, ccol_indices, row, val, grad_out, ReductionType::SUM); +} + +void spmm_reduce_backward_other_arg_kernel( + const Tensor& grad_other, + const Tensor& grad_out, + const Tensor& col_indices, + const Tensor& values, + const Tensor& arg_out, + ReductionType reduce_op) { + TORCH_CHECK(reduce_op == ReductionType::MAX || reduce_op == ReductionType::MIN); + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, values.scalar_type(), "spmm_reduce_backward_other_arg_kernel", [&]() { + AT_DISPATCH_INDEX_TYPES(col_indices.scalar_type(), "spmm_reduce_backward_other_arg_indices", [&]() { + spmm_reduce_backward_other_arg_kernel_impl( + grad_other, grad_out, col_indices, values, arg_out); + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(spmm_reduce_stub, &spmm_reduce_kernel) +REGISTER_DISPATCH(spmm_reduce_arg_stub, &spmm_reduce_arg_kernel) +REGISTER_DISPATCH(spmm_reduce_backward_input_stub, &spmm_reduce_backward_input_kernel) +REGISTER_DISPATCH(spmm_reduce_backward_input_arg_stub, &spmm_reduce_backward_input_arg_kernel) +REGISTER_DISPATCH(spmm_reduce_backward_other_stub, &spmm_reduce_backward_other_kernel) +REGISTER_DISPATCH(spmm_reduce_backward_other_arg_stub, &spmm_reduce_backward_other_arg_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SpmmReduceKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SpmmReduceKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..dba26240e57fb552aa051278dbdc7d07914a9aea --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SpmmReduceKernel.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include +#include + +namespace at::native { + +using spmm_reduce_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op); +using spmm_reduce_arg_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op); +using spmm_reduce_backward_input_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op); +using spmm_reduce_backward_input_arg_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op); +using spmm_reduce_backward_other_fn = void(*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, const Tensor&, ReductionType op); + +DECLARE_DISPATCH(spmm_reduce_fn, spmm_reduce_stub) +DECLARE_DISPATCH(spmm_reduce_arg_fn, spmm_reduce_arg_stub) +DECLARE_DISPATCH(spmm_reduce_backward_input_fn, spmm_reduce_backward_input_stub) +DECLARE_DISPATCH(spmm_reduce_backward_input_arg_fn, spmm_reduce_backward_input_arg_stub) +DECLARE_DISPATCH(spmm_reduce_backward_other_fn, spmm_reduce_backward_other_stub) +DECLARE_DISPATCH(spmm_reduce_backward_input_arg_fn, spmm_reduce_backward_other_arg_stub) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/StackKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/StackKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ff4cd661c4a306e2b472deb97f74fca14e2efba --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/StackKernel.cpp @@ -0,0 +1,24 @@ +// Copyright 2004-present Facebook. All Rights Reserved. +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include + +namespace at::native { + +namespace { + +void stack_serial_kernel(Tensor& result, TensorList tensors, int64_t dim) { + AT_DISPATCH_FLOATING_TYPES( + result.scalar_type(), "stack_serial_kernel", [&]() { + detail::stack_serial_kernel_impl(result, tensors, dim); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(stack_serial_stub, &stack_serial_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/StackKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/StackKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3bd5f585f9d23896bd26259b4370a486db288f37 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/StackKernel.h @@ -0,0 +1,12 @@ +// Copyright 2004-present Facebook. All Rights Reserved. +#pragma once + +#include +#include + +namespace at::native { + +using stack_serial_fn = void(*)(Tensor &, TensorList, int64_t); +DECLARE_DISPATCH(stack_serial_fn, stack_serial_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SumKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SumKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9adbdabbd21d25666eb5853c8fdd3563ddd373c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/SumKernel.cpp @@ -0,0 +1,646 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +// Load vector from a smaller type (more elements) to a larger type (fewer elements), +// reducing neighboring elements until it fits into the vector size. +template +Vectorized load_reduce_vec(const scalar_t* data, F reduce, acc_t ident) { + using vec_t = Vectorized; + using vacc_t = Vectorized; + static_assert(vacc_t::size() <= vec_t::size()); + const auto val = vec_t::loadu(data); + alignas(64) std::array values; + val.store(values.data()); + + constexpr int vstride = vec_t::size() / vacc_t::size(); + alignas(64) std::array acc; + acc.fill(ident); + for (const auto k : c10::irange(vstride)) { + for (const auto i : c10::irange(vacc_t::size())) { + acc[i] = reduce(acc[i], values[i * vstride + k]); + } + } + + return vacc_t::loadu(acc.data()); +} + +template +struct LoadPolicy { + static constexpr int64_t memsize() { + return sizeof(scalar_t); + } + + static scalar_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto *ptr = reinterpret_cast(data + index * stride); + return *ptr; + } +}; + +template +struct LoadPolicy> { + static constexpr int64_t memsize() { + return sizeof(scalar_t) * Vectorized::size(); + } + + static Vectorized load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto *ptr = data + index * stride; + return Vectorized::loadu(ptr); + } +}; + +/* When summing float16 or BFloat16, addition has to be performed in float since + * that's all the hardware supports. These cast-load policies ensure the entire sum + * loop is done in float which improves both performance and accuracy. + */ + +template +struct CastLoadPolicy { + static constexpr int64_t memsize() { + return sizeof(scalar_t); + } + + static acc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + const auto val = LoadPolicy::load(data, stride, index); + return acc_t(val); + } +}; + +template +struct CastLoadPolicy: + LoadPolicy { +}; + +// For inner sum, load full vec_t then sum partials down to vacc_t size +template +struct InnerSumCastLoadPolicy; + +template +struct InnerSumCastLoadPolicy >) && + !std::is_same_v>> { + using scalar_t = vechold_type; + using acc_t = vechold_type; + + static constexpr int64_t memsize() { + return LoadPolicy::memsize(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto ptr = reinterpret_cast(data + stride * index); + return load_reduce_vec(ptr, [](acc_t a, scalar_t b) { + return a + b; + }, acc_t(0)); + } +}; + +template +struct InnerSumCastLoadPolicy: + LoadPolicy { +}; + +template +struct InnerSumCastLoadPolicy >>> { + using scalar_t = vechold_type; + + static constexpr int64_t memsize() { + return LoadPolicy::memsize(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto ptr = reinterpret_cast(data + stride * index); + vacc_t first, second; + vec::load_to_float(ptr, first, second); + return first + second; + } +}; + +// For outer sum, load a partial vec_t of size vacc_t then cast to vacc_t +template +struct OuterSumCastLoadPolicy; + +template +struct OuterSumCastLoadPolicy >) && + !std::is_same_v>> { + + using scalar_t = vechold_type; + using acc_t = vechold_type; + + static constexpr int64_t memsize() { + return sizeof(scalar_t) * vacc_t::size(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + static_assert(vacc_t::size() <= vec_t::size()); + const auto val = vec_t::loadu(data + stride * index, vacc_t::size()); + alignas(64) scalar_t values[vec_t::size()]; + val.store(values); + + alignas(64) acc_t acc[vacc_t::size()]; + for (const auto i : c10::irange(vacc_t::size())) { + acc[i] = values[i]; + } + + return vacc_t::loadu(acc); + } +}; + +template +struct OuterSumCastLoadPolicy >>> { + using scalar_t = vechold_type; + + static constexpr int64_t memsize() { + return sizeof(scalar_t) * vacc_t::size(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto ptr = reinterpret_cast(data + stride * index); + vacc_t values; + vec::load_to_float(ptr, values); + return values; + } +}; + +template +struct OuterSumCastLoadPolicy: + LoadPolicy { +}; + +/* To implement nansum, augment the load operation to mask out nans before + * entering the normal sum loop. + */ + +template +struct NanSumLoadPolicy { + static constexpr int64_t memsize() { + return sizeof(scalar_t); + } + + static scalar_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto val = LoadPolicy::load(data, stride, index); + return at::_isnan(val) ? scalar_t(0) : val; + } +}; + +template +struct NanSumLoadPolicy> { + using vec_t = Vectorized; + + static constexpr int64_t memsize() { + return LoadPolicy::memsize(); + } + + static vec_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto val = LoadPolicy::load(data, stride, index); + return vec_t::blendv(val, vec_t(0), val.isnan()); + } +}; + +template +struct NanSumCastLoadPolicy { + static constexpr int64_t memsize() { + return sizeof(scalar_t); + } + + static acc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto val = CastLoadPolicy::load(data, stride, index); + return at::_isnan(val) ? acc_t(0) : val; + } +}; + +template +struct InnerNanSumCastLoadPolicy; + +template +struct InnerNanSumCastLoadPolicy >) && + !std::is_same_v>> { + using scalar_t = vechold_type; + using acc_t = vechold_type; + + static constexpr int64_t memsize() { + return LoadPolicy::memsize(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto ptr = reinterpret_cast(data + stride * index); + return load_reduce_vec(ptr, [](acc_t a, scalar_t b) { + return at::_isnan(b) ? a : a + b; + }, acc_t(0)); + } +}; + +template +struct InnerNanSumCastLoadPolicy: + NanSumLoadPolicy { +}; + +template +struct InnerNanSumCastLoadPolicy >>> { + using scalar_t = vechold_type; + + static constexpr int64_t memsize() { + return LoadPolicy::memsize(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto ptr = reinterpret_cast(data + stride * index); + vacc_t first, second; + vec::load_to_float(ptr, first, second); + const vacc_t zero(0); + return (vacc_t::blendv(first, zero, first.isnan()) + + vacc_t::blendv(second, zero, second.isnan())); + } +}; + +template +struct OuterNanSumCastLoadPolicy { + static constexpr int64_t memsize() { + return OuterSumCastLoadPolicy::memsize(); + } + + static vacc_t load(const char * C10_RESTRICT data, int64_t stride, int64_t index) { + auto val = OuterSumCastLoadPolicy::load(data, stride, index); + return vacc_t::blendv(val, vacc_t(0), val.isnan()); + } +}; + +template +struct CastStoreAccumulate { + static void store(char * C10_RESTRICT data, int64_t stride, int64_t index, acc_t value) { + auto * ptr = reinterpret_cast(data + index * stride); + *ptr += value; + } +}; + +template +void store(char * C10_RESTRICT data, int64_t stride, int64_t index, scalar_t value) { + StorePolicy::store(data, stride, index, value); +} + +template +void store(char * C10_RESTRICT data, int64_t stride, int64_t index, + const std::array &values) { + auto *base_ptr = data + stride * index; + for (const auto k : c10::irange(numel)) { + auto val = values[k]; + StorePolicy::store(base_ptr, stride, k, val); + } +} + +template +void store(char * C10_RESTRICT data, int64_t stride, int64_t index, + const Vectorized &values) { + using vec_t = Vectorized; + alignas(64) std::array array_values{}; + values.store(array_values.data()); + store(data, stride, index, array_values); +} + +/** Simultaneously sum over n rows at once + +This algorithm calculates the sum without loss of precision over large axes. It +does this by chunking the sum into groups of 16 or more elements. The sums of +these chunks are also summed in chunks and so on until there is just a single sum +value remaining. This means only numbers of a similar order of magnitude are +added together, thus minimising rounding errors. + +This is done in a single linear pass over the data and with O(1) extra storage. +A simplified recursive implementation would look like this: + + scalar_t row_sum(const scalar_t * data, int64_t n) { + // Note, in practice the chunk size can increase with n + // This allows the recursion depth to be limited to O(1). + constexpr int64_t min_chunk_size = 16; + + scalar_t sum = 0; + if (n <= min_chunk_size) { + // Recursive base case, calculate a simple running sum + for (const auto i : c10::irange(n)) { + sum += data[i]; + } + return sum; + } + + // Recursively sum larger chunks of elements + const int64_t chunk_size = std::max(divup(n, min_chunk_size), min_chunk_size); + for (int64_t i = 0; i < n; i += chunk_size) { + sum += row_sum(data + i, std::min(chunk_size, n - i)); + } + return sum; + } +*/ +template +std::array multi_row_sum( + const char * C10_RESTRICT in_data, + const int64_t row_stride, + const int64_t col_stride, + const int64_t size) { + constexpr int64_t num_levels = 4; + + const int64_t level_power = + std::max(int64_t(4), utils::CeilLog2(size) / num_levels); + const int64_t level_step = (1 << level_power); + const int64_t level_mask = level_step - 1; + + std::array, num_levels> acc{}; + for (auto &row:acc) { + row.fill(scalar_t(0)); + } + + int64_t i = 0; + for (; i + level_step <= size;) { + for (int64_t j = 0; j < level_step; ++j, ++i) { + const char * sum_base = in_data + i * row_stride; + #if !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto k : c10::irange(nrows)) { + acc[0][k] += LoadPolicy::load(sum_base, col_stride, k); + } + } + + for (const auto j : c10::irange(1, num_levels)) { + #if !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto k : c10::irange(nrows)) { + acc[j][k] += acc[j-1][k]; + acc[j-1][k] = scalar_t(0); + } + + const auto mask = (level_mask << (j * level_power)); + if ((i & mask) != 0) { + break; + } + } + } + + for (; i < size; ++i) { + const char * sum_base = in_data + i * row_stride; + #if !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto k : c10::irange(nrows)) { + acc[0][k] += LoadPolicy::load(sum_base, col_stride, k); + } + } + + for (const auto j : c10::irange(1, num_levels)) { + #if !defined(COMPILING_FOR_MIN_SIZE) + # pragma unroll + #endif + for (const auto k : c10::irange(nrows)) { + acc[0][k] += acc[j][k]; + } + } + return acc[0]; +} + +template +scalar_t row_sum(const char * C10_RESTRICT in_data, + const int64_t in_stride, const int64_t size) { + constexpr int64_t ilp_factor = 4; + + // Interpret row as a (-1, ilp_factor) shaped array to find partial sums + const int64_t size_ilp = size / ilp_factor; + auto partial_sums = multi_row_sum( + in_data, in_stride * ilp_factor, in_stride, size_ilp); + + for (int64_t i = size_ilp * ilp_factor; i < size; ++i) { + partial_sums[0] += LoadPolicy::load(in_data, in_stride, i); + } + + for (const auto k : c10::irange(1, ilp_factor)) { + partial_sums[0] += partial_sums[k]; + } + + return partial_sums[0]; +} + +template +void vectorized_inner_sum( + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + char * C10_RESTRICT data[2], int64_t outer_stride, int64_t out_stride, + int64_t size0, int64_t size1) { + using vacc_t = Vectorized; + constexpr int64_t vec_stride = VecLoadPolicy::memsize(); + constexpr int64_t scalar_stride = ScalarLoadPolicy::memsize(); + constexpr int64_t vec_numel = vec_stride / scalar_stride; + const int64_t vec_size = size0 / vec_numel; + + // Input is contiguous over the first (reduced) dimension + for (const auto j : c10::irange(size1)) { + const auto *row_in = data[1] + j * outer_stride; + auto vec_acc = row_sum(row_in, vec_stride, vec_size); + + acc_t final_acc = 0; + for (int64_t k = vec_size * vec_numel; k < size0; ++k) { + final_acc += ScalarLoadPolicy::load(row_in, scalar_stride, k); + } + + alignas(64) std::array partials{}; + vec_acc.store(partials.data()); + for (const auto k : c10::irange(partials.size())) { + final_acc += partials[k]; + } + store(data[0], out_stride, j, final_acc); + } +} + +template +void scalar_inner_sum( + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + char * C10_RESTRICT data[2], int64_t in_strides[2], int64_t out_stride, + int64_t size0, int64_t size1) { + for (const auto j : c10::irange(size1)) { + const auto *row_in = data[1] + j * in_strides[1]; + auto ans = row_sum(row_in, in_strides[0], size0); + store(data[0], out_stride, j, ans); + } +} + +template +void vectorized_outer_sum( + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + char * C10_RESTRICT data[2], int64_t inner_stride, int64_t out_stride, + int64_t size0, int64_t size1) { + using vacc_t = Vectorized; + constexpr int64_t scalar_stride = ScalarLoadPolicy::memsize(); + constexpr int64_t vec_stride = VecLoadPolicy::memsize(); + constexpr int64_t nrows = 4; + + // Input is contiguous over the second (non-reduced) dimension + int64_t j = 0; + for (; j + nrows * vacc_t::size() <= size1; j += nrows * vacc_t::size()) { + const auto *row_in = data[1] + j * scalar_stride; + auto sums = multi_row_sum( + row_in, inner_stride, vec_stride, size0); + + for (const auto i : c10::irange(nrows)) { + const int64_t base_idx = j + i * vacc_t::size(); + store(data[0], out_stride, base_idx, sums[i]); + } + } + + for (; j + vacc_t::size() <= size1; j += vacc_t::size()) { + const auto *row_in = data[1] + j * scalar_stride; + const vacc_t sums = row_sum( + row_in, inner_stride, size0); + + store(data[0], out_stride, j, sums); + } + + for (; j < size1; ++j) { + const auto *row_in = data[1] + j * scalar_stride; + auto ans = row_sum(row_in, inner_stride, size0); + store(data[0], out_stride, j, ans); + } +} + +template +void scalar_outer_sum( + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + char * C10_RESTRICT data[2], int64_t in_strides[2], int64_t out_stride, + int64_t size0, int64_t size1) { + constexpr int64_t nrows = 4; + int64_t j = 0; + for (; j + (nrows - 1) < size1; j += nrows) { + const auto *row_in = data[1] + j * in_strides[1]; + auto sums = multi_row_sum( + row_in, in_strides[0], in_strides[1], size0); + store(data[0], out_stride, j, sums); + } + + for (; j < size1; ++j) { + const auto *row_in = data[1] + j * in_strides[1]; + auto ans = row_sum( + row_in, in_strides[0], size0); + store(data[0], out_stride, j, ans); + } +} + +// Custom floating point sum for better accuracy +template +void cascade_sum(TensorIterator &iter) { + iter.output_base().fill_(scalar_t(0)); + iter.parallel_reduce( + [&](char** data, const int64_t* strides, int64_t size0, int64_t size1) { + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + int64_t in_strides[] = { strides[1], strides[3] }; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + int64_t out_strides[] = { strides[0], strides[2] }; + + // Move reduction to be the 1st dim + if (out_strides[0] != 0 && out_strides[1] == 0) { + std::swap(in_strides[0], in_strides[1]); + std::swap(out_strides[0], out_strides[1]); + std::swap(size0, size1); + } + + // Special case? - not a true reduction + if (out_strides[0] != 0 && out_strides[1] != 0) { + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + int64_t outer_strides[] = { strides[2], strides[3] }; + UNARY_OUTER_LOOP(data, outer_strides, size1, [&] { + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + char* ptrs[3] = { data[0], data[0], data[1] }; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + int64_t inner_strides[3] = { strides[0], strides[0], strides[1] }; + if constexpr (ignore_nan) { + basic_loop(ptrs, inner_strides, 0, size0, [](scalar_t a, scalar_t b) { + auto a_notnan = at::_isnan(a) ? scalar_t(0) : a; + auto b_notnan = at::_isnan(b) ? scalar_t(0) : b; + return a_notnan + b_notnan; + }); + } else { + basic_loop(ptrs, inner_strides, 0, size0, + [](scalar_t a, scalar_t b) { return a + b; }); + } + }); + return; + } + + const int64_t out_stride = out_strides[1]; + TORCH_INTERNAL_ASSERT(out_strides[0] == 0); + + using vec_t = Vectorized; + using acc_t = at::acc_type; + using vacc_t = Vectorized; + using ScalarLoadPolicy = std::conditional_t< + ignore_nan, + NanSumCastLoadPolicy, + CastLoadPolicy>; + using StorePolicy = CastStoreAccumulate; + + if (in_strides[0] == sizeof(scalar_t) && size0 >= vec_t::size()) { + // Contiguous inner reduction + using VecLoadPolicy = std::conditional_t< + ignore_nan, + InnerNanSumCastLoadPolicy, + InnerSumCastLoadPolicy>; + vectorized_inner_sum( + data, in_strides[1], out_stride, size0, size1); + } else if (in_strides[1] == sizeof(scalar_t) && size1 >= vec_t::size()) { + // Contiguous outer reduction + using VecLoadPolicy = std::conditional_t< + ignore_nan, + OuterNanSumCastLoadPolicy, + OuterSumCastLoadPolicy>; + vectorized_outer_sum( + data, in_strides[0], out_stride, size0, size1); + } else if (in_strides[0] < in_strides[1]) { + scalar_inner_sum( + data, in_strides, out_stride, size0, size1); + } else { + scalar_outer_sum( + data, in_strides, out_stride, size0, size1); + } + }); +} + +void sum_kernel_impl(TensorIterator &iter) { + if (isIntegralType(iter.dtype(), /*includeBool=*/ true)) { + AT_DISPATCH_INTEGRAL_TYPES_AND(ScalarType::Bool, iter.dtype(), "sum_cpu", + [&] { + binary_kernel_reduce_vec( + iter, [=](scalar_t a, scalar_t b) -> scalar_t { return a + b; }, + [=](Vectorized a, Vectorized b) { return a + b; }); + }); + return; + } + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, iter.dtype(), "sum_cpu", [&] { + cascade_sum(iter); + }); +} + +void nansum_kernel_impl(TensorIterator &iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, iter.dtype(), "nansum_cpu", [&] { + cascade_sum(iter); + }); +} + +} // namespace (anonymous) + +// nansum on Float16 has poor accuracy with AVX2, and more so with AVX512. +// So until it's fixed, it won't be dispatched with AVX512. GH issue 59415. +// Besides, these kernels are slower with AVX512 than with AVX2. +REGISTER_DISPATCH(nansum_stub, &nansum_kernel_impl) +REGISTER_DISPATCH(sum_stub, &sum_kernel_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/TensorCompareKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/TensorCompareKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6cd3f69bf50531dbea02630d379ddbdfe1556ab --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/TensorCompareKernel.cpp @@ -0,0 +1,417 @@ +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at::native { namespace { + +template +inline void compare_base_kernel_core( + const Tensor& result1, + const Tensor& result2, + const Tensor& self, + int64_t dim, + bool keepdim, + const loop1d_t& loop) { + auto self_sizes = ensure_nonempty_vec(self.sizes().vec()); + self_sizes[dim] = 1; + + // result1 and result2 may be a empty tensor, if not, + // reshape them as self dims + if (!keepdim) { + if (result1.ndimension() >= dim) { + result1.unsqueeze_(dim); + } + if (result2.ndimension() >= dim) { + result2.unsqueeze_(dim); + } + } + + at::native::resize_output(result1, self_sizes); + at::native::resize_output(result2, self_sizes); + + auto iter = TensorIteratorConfig() + .check_all_same_dtype(false) + .resize_outputs(false) + .declare_static_shape(self.sizes(), /*squash_dims=*/dim) + .add_output(result1) + .add_output(result2) + .add_const_input(self) + .build(); + + iter.for_each(loop, /* grain_size */ 1); + + if (!keepdim) { + result1.squeeze_(dim); + result2.squeeze_(dim); + } +} + +template +inline void compare_base_kernel(const Tensor& result1, const Tensor& result2, + const Tensor& self, + int64_t dim, + bool keepdim, + const func_t& f) { + + auto self_dim_stride = ensure_nonempty_stride(self, dim); + + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* result1_data_bytes = data[0]; + auto* result2_data_bytes = data[1]; + const auto* self_data_bytes = data[2]; + for ([[maybe_unused]] const auto i : c10::irange(n)) { + f((scalar_t*)result1_data_bytes, + (scalar_t_2*)result2_data_bytes, + (scalar_t*)self_data_bytes, + self_dim_stride); + result1_data_bytes += strides[0]; + result2_data_bytes += strides[1]; + self_data_bytes += strides[2]; + } + }; + + compare_base_kernel_core( + result1, result2, self, dim, keepdim, loop); +} + +void min_kernel_impl( + const Tensor& result, + const Tensor& indice, + const Tensor& self, + int64_t dim, + bool keepdim) { + int64_t self_dim_size = ensure_nonempty_size(self, dim); + + AT_DISPATCH_ALL_TYPES_AND3(ScalarType::Half, ScalarType::BFloat16, ScalarType::Bool, self.scalar_type(), "min_cpu", [&] { + compare_base_kernel(result, indice, self, dim, keepdim, [&] ( + scalar_t* result_data, int64_t* indice_data, + const scalar_t* self_data, auto self_dim_stride) { + using value_t = typename c10::scalar_value_type::type; + value_t (*zabs_)(scalar_t) = zabs; + scalar_t min_number = c10::load(self_data); + int64_t index = 0; + for (const auto i : c10::irange(self_dim_size)) { + scalar_t value = c10::load(&self_data[i * self_dim_stride]); + if (!(zabs_(value) >= zabs_(min_number))) { + min_number = value; + index = i; + if (_isnan(value)) { + break; + } + } + } + *result_data = min_number; + *indice_data = index; + } + ); + }); +} + +void max_kernel_impl( + const Tensor& result, + const Tensor& indice, + const Tensor& self, + int64_t dim, + bool keepdim) { + int64_t self_dim_size = ensure_nonempty_size(self, dim); + + AT_DISPATCH_ALL_TYPES_AND3(ScalarType::Half, ScalarType::BFloat16, ScalarType::Bool, self.scalar_type(), "max_cpu", [&] { + compare_base_kernel(result, indice, self, dim, keepdim, [&] ( + scalar_t* result_data, int64_t* indice_data, + const scalar_t* self_data, auto self_dim_stride) { + using value_t = typename c10::scalar_value_type::type; + value_t (*zabs_)(scalar_t) = zabs; + scalar_t max_number = c10::load(self_data); + int64_t index = 0; + for (const auto i : c10::irange(self_dim_size)) { + scalar_t value = c10::load(&self_data[i * self_dim_stride]); + if (!(zabs_(value) <= zabs_(max_number))) { + max_number = value; + index = i; + if (_isnan(value)) { + break; + } + } + } + *result_data = max_number; + *indice_data = index; + } + ); + }); +} + +void aminmax_kernel( + const Tensor& self, + int64_t dim, + bool keepdim, + Tensor& min_result, + Tensor& max_result) { + auto wrap_dim = maybe_wrap_dim(dim, self.dim()); + int64_t self_dim_size = ensure_nonempty_size(self, wrap_dim); + + TORCH_CHECK(min_result.scalar_type() == self.scalar_type() && max_result.scalar_type() == self.scalar_type(), + "Expect min and max dtype ", self.scalar_type(), + " but got ", min_result.scalar_type(), " and ", max_result.scalar_type()); + + if (self.numel() == 1 && self.ndimension() == 0) { + TORCH_CHECK(!self.is_complex(), "aminmax not implemented for ", self.scalar_type()); + min_result.resize_({}); + max_result.resize_({}); + min_result.fill_(self); + max_result.fill_(self); + return; + } + + AT_DISPATCH_ALL_TYPES_AND3(ScalarType::Bool, ScalarType::BFloat16, ScalarType::Half, self.scalar_type(), "aminmax_cpu", [&] { + compare_base_kernel(min_result, max_result, self, wrap_dim, keepdim, [&] ( + scalar_t* min_result_data, scalar_t* max_result_data, + const scalar_t* self_data, auto self_dim_stride) { + scalar_t min_number = c10::load(self_data); + scalar_t max_number = min_number; + for (const auto i : c10::irange(self_dim_size)) { + scalar_t value = c10::load(&self_data[i * self_dim_stride]); + // note: comparison is written this way to handle NaN correctly + if (!(value >= min_number)) { + min_number = value; + if (_isnan(value)) { + max_number = value; + break; + } + } else if (!(value <= max_number)) { + max_number = value; + } + } + *min_result_data = min_number; + *max_result_data = max_number; + } + ); + }); +} + +void where_kernel_impl(TensorIterator &iter) { + AT_DISPATCH_V2( + opaqueScalarType(iter.dtype()), "where_cpu", [&] { + cpu_kernel_opaque( + iter, + [=](bool cond_val, scalar_t self_val, scalar_t other_val) -> scalar_t { + return cond_val ? self_val : other_val; + }); + }, AT_EXPAND(AT_OPAQUE_TYPES)); +} + +void isposinf_kernel_impl(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(), "isposinf_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a) -> bool { return a == std::numeric_limits::infinity(); }); + }); +} + +void isneginf_kernel_impl(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(), "isneginf_cpu", [&]() { + cpu_kernel(iter, [](scalar_t a) -> bool { return a == -std::numeric_limits::infinity(); }); + }); +} + +void mode_kernel_impl( + Tensor& values, + Tensor& indices, + const Tensor& self, + int64_t dim, + bool keepdim) { + auto self_dim_size = ensure_nonempty_size(self, dim); + auto self_dim_stride = ensure_nonempty_stride(self, dim); + + AT_DISPATCH_ALL_TYPES_AND3( + kHalf, kBFloat16, kBool, self.scalar_type(), "mode_cpu", [&] { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + auto* values_data_bytes = data[0]; + auto* indices_data_bytes = data[1]; + const auto* self_data_bytes = data[2]; + + std::vector> elements(self_dim_size); + + for ([[maybe_unused]] const auto k : c10::irange(n)) { + scalar_t* values_data = (scalar_t*)values_data_bytes; + int64_t* indices_data = (int64_t*)indices_data_bytes; + const scalar_t* self_data = (scalar_t*)self_data_bytes; + + scalar_t mode = 0; + int64_t modei = 0; + int64_t temp_freq = 0; + int64_t max_freq = 0; + + for (const auto i : c10::irange(self_dim_size)) { + elements[i] = std::make_pair(c10::load(&self_data[i * self_dim_stride]), i); + } + + // Even though, theoretically, we don't need to specify this lambda + // (it's basically the same as std::less), doing so degrades + // performance. That is because its implementation for std::pair + // uses 3 comparisons. + std::sort( + elements.begin(), + elements.end(), + [=](const auto& i, const auto& j) { + return i.first < j.first; + }); + + for (const auto i : c10::irange(self_dim_size)) { + temp_freq++; + if ((i == self_dim_size - 1) || + (elements[i].first != elements[i + 1].first)) { + if (temp_freq > max_freq) { + mode = elements[i].first; + modei = elements[i].second; + max_freq = temp_freq; + } + temp_freq = 0; + } + } + + *values_data = mode; + *indices_data = modei; + + values_data_bytes += strides[0]; + indices_data_bytes += strides[1]; + self_data_bytes += strides[2]; + } + }; + + compare_base_kernel_core( + values, indices, self, dim, keepdim, loop); + }); +} + +// Default brute force implementation of isin(). Used when the number of test elements is small. +// Iterates through each element and checks it against each test element. +void isin_default_kernel_cpu( + const Tensor& elements, + const Tensor& test_elements, + bool invert, + const Tensor& out) { + // Since test elements is not an input of the TensorIterator, type promotion + // must be done manually. + ScalarType common_type = at::native::result_type(elements, test_elements); + Tensor promoted_elements = elements.to(common_type); + Tensor test_elements_flat = test_elements.to(common_type).view(-1); + auto test_elements_stride = test_elements_flat.stride(0); + + auto iter = TensorIteratorConfig() + .add_output(out) + .add_const_input(promoted_elements) + .check_all_same_dtype(false) + .build(); + // Dispatch based on promoted type. + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, iter.dtype(1), "isin_default_cpu", [&]() { + cpu_kernel(iter, [&](scalar_t element_val) -> bool { + const auto* test_element_data = test_elements_flat.const_data_ptr(); + for (const auto j : c10::irange(test_elements_flat.numel())) { + if (element_val == *(test_element_data + test_elements_stride * j)) { + return !invert; + } + } + return invert; + }); + }); +} + +void clamp_kernel_impl(TensorIteratorBase& iter) { + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "clamp_cpu", [&]() { + cpu_kernel_vec(iter, + [](scalar_t a, scalar_t min, scalar_t max) -> scalar_t { + if (min != min || max != max) { + return std::numeric_limits::quiet_NaN(); + } else { + return std::min(std::max(a, min), max); + } + }, + [](Vectorized a, Vectorized min, Vectorized max) { + return vec::minimum(vec::maximum(a, min), max); + }); + }); +} + +void clamp_scalar_kernel_impl(TensorIteratorBase& iter, const Scalar& min_, const Scalar& max_) { + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "clamp_scalar_cpu", [&]() { + const auto min = min_.to(); + const auto max = max_.to(); + const Vectorized min_vec(min); + const Vectorized max_vec(max); + cpu_kernel_vec(iter, + [=](scalar_t a) -> scalar_t { + return std::min(std::max(a, min), max); + }, + [=](Vectorized a) { + return vec::clamp(a, min_vec, max_vec); + }); + }); +} + +void clamp_max_scalar_kernel_impl(TensorIteratorBase& iter, Scalar max_) { + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "clamp_max_scalar_cpu", [&]() { + const auto max = max_.to(); + const Vectorized max_vec(max); + cpu_kernel_vec(iter, + [=](scalar_t a) -> scalar_t { + return std::min(a, max); + }, + [=](Vectorized a) { + return vec::clamp_max(a, max_vec); + }); + }); +} + +void clamp_min_scalar_kernel_impl(TensorIteratorBase& iter, Scalar min_) { + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "clamp_min_scalar_cpu", [&]() { + const auto min = min_.to(); + const Vectorized min_vec(min); + cpu_kernel_vec(iter, + [=](scalar_t a) -> scalar_t { + return std::max(a, min); + }, + [=](Vectorized a) { + return vec::clamp_min(a, min_vec); + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(max_stub, &max_kernel_impl) +REGISTER_DISPATCH(min_stub, &min_kernel_impl) +REGISTER_DISPATCH(aminmax_stub, &aminmax_kernel) +REGISTER_DISPATCH(where_kernel, &where_kernel_impl) +REGISTER_DISPATCH(isposinf_stub, &isposinf_kernel_impl) +REGISTER_DISPATCH(isneginf_stub, &isneginf_kernel_impl) +REGISTER_DISPATCH(mode_stub, &mode_kernel_impl) +REGISTER_DISPATCH(clamp_stub, &clamp_kernel_impl) +REGISTER_DISPATCH(clamp_scalar_stub, &clamp_scalar_kernel_impl) +REGISTER_DISPATCH(clamp_min_scalar_stub, &clamp_min_scalar_kernel_impl) +REGISTER_DISPATCH(clamp_max_scalar_stub, &clamp_max_scalar_kernel_impl) +REGISTER_DISPATCH(isin_default_stub, &isin_default_kernel_cpu) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UnaryOpsKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UnaryOpsKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..792e9f66d0e438b8af2bf322f4236cb710147e2b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UnaryOpsKernel.cpp @@ -0,0 +1,891 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#if AT_MKL_ENABLED() +#include +#endif + +namespace at::native { + +inline namespace CPU_CAPABILITY { + +using namespace vec; + +static void sigmoid_kernel(TensorIteratorBase& iter) { + const auto dtype = iter.common_dtype(); + if (at::isReducedFloatingType(dtype)) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(dtype, "sigmoid_cpu_reduced_float", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { + float a0 = static_cast(a); + return static_cast(1) / (static_cast(1) + std::exp((-a0))); + }, + [=](Vectorized a) { + auto [a0, a1] = convert_to_float(a); + a0 = (Vectorized(static_cast(1)) + a0.neg().exp()).reciprocal(); + a1 = (Vectorized(static_cast(1)) + a1.neg().exp()).reciprocal(); + return convert_from_float(a0, a1); + }); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES(dtype, "sigmoid_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { + return (static_cast(1) / (static_cast(1) + std::exp((-a)))); + }, + [=](Vectorized a) { + a = (Vectorized(static_cast(1)) + a.neg().exp()).reciprocal(); + return a; + }); + }); + } +} + +#if AT_MKL_ENABLED() + +template +void VmlLog(int64_t N, const T* X, T* Y) { + constexpr int64_t K = Vectorized::size(); + at::parallel_for(0, N, K, [=](int64_t begin, int64_t end) { + using VT = at::opmath_type; + vec::map( + [](Vectorized x_vec) { return x_vec.log(); }, + Y + begin, + X + begin, + end - begin); + }); +} + +template <> +void VmlLog(int64_t N, const float* X, float* Y) { + vsLn(N, X, Y); +} + +template <> +void VmlLog(int64_t N, const double* X, double* Y) { + vdLn(N, X, Y); +} + +template +void LogitMKLKernel(T eps, TensorIteratorBase* it) { + if (!it->can_use_32bit_indexing()) { + for (auto& sub_it : it->with_32bit_indexing()) { + LogitMKLKernel(eps, &sub_it); + } + return; + } + + constexpr int64_t K = Vectorized::size(); + const int64_t N = it->numel(); + const T* X_data = static_cast(it->data_ptr(1)); + T* Y_data = static_cast(it->data_ptr(0)); + if (eps < T(0)) { + at::parallel_for(0, N, K, [=](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + Y_data[i] = X_data[i] == T(1) ? std::numeric_limits::infinity() + : X_data[i] / (T(1) - X_data[i]); + } + VmlLog(end - begin, Y_data + begin, Y_data + begin); + }); + } else { + const T lo = eps; + const T hi = T(1) - eps; + at::parallel_for(0, N, K, [=](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + const T x = X_data[i] < lo ? lo : (X_data[i] > hi ? hi : X_data[i]); + Y_data[i] = + x == T(1) ? std::numeric_limits::infinity() : (x / (T(1) - x)); + } + VmlLog(end - begin, Y_data + begin, Y_data + begin); + }); + } +} + +#else + +template +void LogitMKLKernel(T eps, TensorIteratorBase* it) { + TORCH_CHECK(false, "ATen not compiled with MKL"); +} + +#endif // AT_MKL_ENABLED + +static void logit_kernel(TensorIteratorBase& iter, const Scalar& eps_scalar) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "logit_cpu", [&]() { + const scalar_t eps = eps_scalar.to(); + if (at::hasMKL() && iter.is_contiguous()) { + LogitMKLKernel(eps, &iter); + iter.cast_outputs(); + } else if (eps < scalar_t(0)) { + const Vectorized kOneVec(scalar_t(1)); + cpu_kernel_vec( + iter, + [](scalar_t x) { + return x == scalar_t(1) + ? std::numeric_limits::infinity() + : std::log(x / (scalar_t(1) - x)); + }, + [kOneVec](Vectorized x_vec) { + return (x_vec / (kOneVec - x_vec)).log(); + }); + } else { + const scalar_t lo = eps; + const scalar_t hi = scalar_t(1) - eps; + const Vectorized kOneVec(scalar_t(1)); + const Vectorized lo_vec(lo); + const Vectorized hi_vec(hi); + cpu_kernel_vec( + iter, + [lo, hi](scalar_t x) { + x = x < lo ? lo : (x > hi ? hi : x); + return x == scalar_t(1) + ? std::numeric_limits::infinity() + : std::log(x / (scalar_t(1) - x)); + }, + [kOneVec, lo_vec, hi_vec](Vectorized x_vec) { + // Apply lo last so it wins when eps > 1 - eps, matching + // the scalar `x < lo ? lo : (x > hi ? hi : x)` priority. + x_vec = Vectorized::blendv( + Vectorized::blendv(x_vec, hi_vec, x_vec > hi_vec), + lo_vec, + x_vec < lo_vec); + return (x_vec / (kOneVec - x_vec)).log(); + }); + } + }); +} + +#if !defined(C10_MOBILE) +#define _AT_DISPATCH_ABS_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND6( \ + kHalf, kBFloat16, kFloat8_e5m2, kFloat8_e4m3fn, kFloat8_e5m2fnuz, kFloat8_e4m3fnuz, \ + TYPE, NAME, __VA_ARGS__) +#else +#define _AT_DISPATCH_ABS_TYPES(TYPE, NAME, ...) \ + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( \ + kHalf, kBFloat16, \ + TYPE, NAME, __VA_ARGS__) +#endif + +static void abs_kernel(TensorIteratorBase& iter) { + auto dtype = iter.dtype(); + if (dtype == kComplexHalf) { + using scalar_t = c10::complex; + using opmath_t = at::opmath_type; + cpu_kernel(iter, [=](scalar_t a) -> scalar_t { return abs_impl(opmath_t{a}); }); + } else { + _AT_DISPATCH_ABS_TYPES(iter.dtype(), "abs_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return abs_impl(a); }, + [=](Vectorized a) { return a.abs(); }); + }); + } +} + +static void angle_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "angle_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return angle_impl(a); }, + [=](Vectorized a) { return a.angle(); }); + }); +} + +// NB: Ignores the negative bit on tensors +void conj_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_SWITCH(iter.common_dtype(), "conj_cpu", + AT_DISPATCH_CASE_ALL_TYPES_AND3(kBool, kBFloat16, kHalf, [&] { + // conj is a no-op for non-complex types + direct_copy_kernel(iter); + }) + AT_DISPATCH_CASE_COMPLEX_TYPES_AND(kComplexHalf, [&] { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return conj_impl(a); }, + [=](Vectorized a) { return a.conj(); }); + }) + ); +} + +static void bitwise_not_kernel(TensorIteratorBase& iter) { + if (iter.dtype() == ScalarType::Bool) { + // Boolean type does not work with ~ (bitwise NOT) in C++. bitwise_not wraps this operation for both Boolean and + // integral types. + cpu_kernel( + iter, + [](bool a) { + return !a; + }); + } else { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "bitwise_not_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t a) -> scalar_t { + return ~a; + }, + [](Vectorized a) -> Vectorized { + return ~a; + }); + }); + } +} + +static void frac_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "frac_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return a - std::trunc(a); }, + [=](Vectorized a) { return a.frac(); }); + }); +} + +static void logical_not_kernel(TensorIteratorBase& iter) { + // NOTE: this implementation differs from the CUDA implementation which only does single dispatch + // (to avoid expensive compilation) because CPU kernels don't handle dynamic_casting + // (see needs_dynamic_casting). + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(kBool, kHalf, kBFloat16, iter.dtype(1), "logical_not_cpu", [&]() { + using self_t = scalar_t; + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(kBool, kHalf, kBFloat16, iter.dtype(0), "logical_not_cpu", [&]() { + cpu_kernel(iter, [](self_t a) -> scalar_t { return static_cast(!a); }); + }); + }); +} + +void reciprocal_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "reciprocal_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { return static_cast(1.0) / a; }, + [=](Vectorized a) { return a.reciprocal(); }); + }); +} + +// NB: Ignores the negative bit on tensors +void neg_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(kComplexHalf, kBFloat16, kHalf, iter.dtype(), "neg_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return -a; }, + [=](Vectorized a) { return a.neg(); }); + }); +} + +static void sign_kernel(TensorIteratorBase& iter){ + if(iter.dtype() == ScalarType::Bool){ + cpu_kernel(iter, [=](bool x) -> bool { return x; }); + } else { + AT_DISPATCH_ALL_TYPES_AND2(kBFloat16, ScalarType::Half, iter.dtype(), "sign_cpu", [&]() { + auto zero_vec = Vectorized(static_cast(0)); + auto one_vec = Vectorized(static_cast(1)); + + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return (0 < a) - c10::is_negative(a); }, + [=](Vectorized self_vec){ + + // Comparison operators returns bitmask. + auto left = Vectorized::blendv(zero_vec, one_vec, zero_vec < self_vec); + auto right = Vectorized::blendv(zero_vec, one_vec, self_vec < zero_vec); + + return left - right; + }); + }); + } +} + +static void signbit_kernel(TensorIteratorBase& iter){ + // NOTE: signbit does not always support integral arguments. + AT_DISPATCH_SWITCH(iter.input_dtype(), "signbit_cpu", + AT_DISPATCH_CASE_INTEGRAL_TYPES([&] { + cpu_kernel(iter, [](scalar_t a) -> bool { return c10::is_negative(a); }); + }) + AT_DISPATCH_CASE_FLOATING_TYPES_AND2(kBFloat16, ScalarType::Half, [&] { + using opmath_t = at::opmath_type; + cpu_kernel(iter, [](scalar_t a) -> bool { return std::signbit(opmath_t{a}); }); + }) + ); +} + +static void sgn_kernel(TensorIteratorBase& iter) { + auto dtype = iter.dtype(); + if (dtype == kComplexHalf) { + using scalar_t = c10::complex; + using opmath_t = at::opmath_type; + cpu_kernel( + iter, [=](scalar_t a) -> scalar_t { return sgn_impl(opmath_t{a}); }); + } else { + AT_DISPATCH_COMPLEX_TYPES(dtype, "sgn_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return sgn_impl(a); }, + [=](Vectorized a) { return a.sgn(); }); + }); + } +} + +static void sinc_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "sinc_cpu", [&]() { + cpu_kernel( + iter, + [=](scalar_t a) -> scalar_t { + if (a == scalar_t(0)) { + return scalar_t(1); + } else { + using opmath_t = at::opmath_type; + opmath_t product = c10::pi * opmath_t{a}; + return static_cast(std::sin(product) / product); + } + }); + }); +} + +static void sinh_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "sinh_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return std::sinh(a); }, + [=](Vectorized self_vec){return self_vec.sinh();}); + }); +} + +static void cosh_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "cosh_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return std::cosh(a); }, + [=](Vectorized self_vec){return self_vec.cosh();}); + }); +} + +static void acosh_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "acosh_cpu", [&]() { + cpu_kernel( + iter, + [=](scalar_t a) -> scalar_t { return std::acosh(a); }); + }); +} + +static void asinh_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "asinh_cpu", [&]() { + cpu_kernel( + iter, + [=](scalar_t a) -> scalar_t { return std::asinh(a); }); + }); +} + +static void atanh_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "atanh_cpu", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return std::atanh(a); }, + [=](Vectorized self_vec){return self_vec.atanh();}); + }); +} + +static void digamma_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "digamma", [&]() { + cpu_kernel_vec( + iter, + [=](scalar_t a) -> scalar_t { return calc_digamma(a); }, + [=](Vectorized x) { return x.digamma(); }); + }); +} + +static void trigamma_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "trigamma", [&]() { + cpu_kernel( + iter, + [=](scalar_t a) -> scalar_t { return trigamma(a); }); + }); +} + +static void exp2_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + kBFloat16, kHalf, iter.dtype(), "exp2", [&] { + cpu_kernel_vec( + iter, + [](scalar_t a) -> scalar_t { return exp2_impl(a); }, + [](Vectorized a) { return a.exp2(); }); + }); +} + +static void polygamma_kernel(TensorIteratorBase& iter, int64_t n) { + if (n == 0) { + digamma_kernel(iter); + } else if (n == 1) { + trigamma_kernel(iter); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "polygamma", [&]() { + cpu_kernel( + iter, [=](scalar_t a) -> scalar_t { return calc_polygamma(a, n); }); + }); + } +} + +template +inline scalar_t _nan_to_num_replace( + scalar_t a, scalar_t nan_replacement, scalar_t pos_inf_replacement, scalar_t neg_inf_replacement) { + if (at::_isnan(a)) { + return nan_replacement; + } else if (a == std::numeric_limits::infinity()) { + return pos_inf_replacement; + } else if (a == -std::numeric_limits::infinity()) { + return neg_inf_replacement; + } else { + return a; + } +} + +template +inline c10::complex _nan_to_num_replace( + c10::complex a, scalar_t nan, scalar_t posinf, scalar_t neginf) { + return c10::complex( + _nan_to_num_replace(a.real(), nan, posinf, neginf), + _nan_to_num_replace(a.imag(), nan, posinf, neginf) + ); +} + +template +inline Vectorized _nan_to_num_replace( + Vectorized a, scalar_t nan, scalar_t posinf, scalar_t neginf) { + using vec_t = Vectorized; + vec_t inf(std::numeric_limits::infinity()); + vec_t result; + result = vec_t::blendv(a, vec_t(nan), a.isnan()); + result = vec_t::blendv(result, vec_t(posinf), a == inf); + return vec_t::blendv(result, vec_t(neginf), a == inf.neg()); +} + +template +inline Vectorized> _nan_to_num_replace( + Vectorized> a, scalar_t nan, scalar_t posinf, scalar_t neginf) { +#if !defined(_MSC_VER) && (defined(CPU_CAPABILITY_AVX2) || defined(CPU_CAPABILITY_AVX512)) + return {_nan_to_num_replace(Vectorized(a), nan, posinf, neginf)}; +#else + __at_align__ c10::complex buffer[a.size()]; + a.store(buffer); + auto asreal = Vectorized::loadu(buffer); + _nan_to_num_replace(asreal, nan, posinf, neginf).store(buffer); + return Vectorized>::loadu(buffer); +#endif +} + +static void nan_to_num_kernel( + TensorIteratorBase& iter, + std::optional nan, + std::optional pos_inf, + std::optional neg_inf) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "nan_to_num", [&]() { + using value_t = c10::scalar_value_type::type; + value_t nan_replacement = static_cast(nan.value_or(0.)); + value_t pos_inf_replacement = pos_inf.has_value() + ? static_cast(pos_inf.value()) + : std::numeric_limits::max(); + value_t neg_inf_replacement = neg_inf.has_value() + ? static_cast(neg_inf.value()) + : std::numeric_limits::lowest(); + using vec_t = Vectorized; + + cpu_kernel_vec(iter, [=](scalar_t a) -> scalar_t { + return _nan_to_num_replace(a, nan_replacement, pos_inf_replacement, neg_inf_replacement); + }, [=](vec_t a) -> vec_t { + return _nan_to_num_replace(a, nan_replacement, pos_inf_replacement, neg_inf_replacement); + }); + }); +} + +static void kaiser_window_kernel(TensorIteratorBase& iter, int64_t window_length, double beta){ + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "kaiser_window_cpu", [&](){ + using opmath_t = at::opmath_type; + const opmath_t alpha = static_cast((window_length - 1) / 2.0); + const opmath_t beta_ = static_cast(beta); + cpu_kernel(iter, [=](scalar_t a) -> scalar_t { + return calc_i0(beta_ * std::sqrt(std::abs(1 - std::pow((static_cast(a) - alpha) / alpha, static_cast(2.0))))) / calc_i0(beta_); + }); + }); +} + +void rsqrt_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.common_dtype(), "rsqrt_cpu", [&] { + cpu_kernel_vec( + iter, + [=](scalar_t a) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return (static_cast(1)) / std::sqrt(a); + }, + [=](Vectorized a) { return a.rsqrt(); }); + }); +} + +static void entr_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "entr_cpu", [&] { + cpu_kernel(iter, [](scalar_t x) -> scalar_t { + if (at::_isnan(x)) { + return x; + } else if (x > 0) { + return -x * std::log(x); + } else if (x == 0) { + return static_cast(0); + } + return static_cast(-INFINITY); + }); + }); +} + +static void frexp_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, + // The iter.dtype() here is the dtype of mantissa output. + // It's a floating point type and must be the same as the input's dtype. + iter.dtype(), + "frexp_cpu", [&]() { + cpu_kernel_multiple_outputs( + iter, + [](scalar_t a) -> std::tuple { + int32_t exponent; + scalar_t mantissa = std::frexp(a, &exponent); + return std::tuple(mantissa, exponent); + } + ); + }); +} + +static void ndtri_kernel(TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); + AT_DISPATCH_FLOATING_TYPES(iter.common_dtype(), "ndtri_cpu", [&]() { + cpu_kernel(iter, [](scalar_t x) { return calc_ndtri(x); }); + }); +} + +static void log_ndtr_kernel(TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); + AT_DISPATCH_FLOATING_TYPES(iter.common_dtype(), "log_ndtr_cpu", [&]() { + cpu_kernel(iter, [](scalar_t x) { return calc_log_ndtr(x); }); + }); +} + +static void i0e_kernel(TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "i0e_cpu", [&]() { + cpu_kernel_vec( + iter, + [](scalar_t x) { return calc_i0e(x); }, + [](Vectorized x) { return x.i0e(); }); + }); +} + +static void i1_kernel(TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "i1_cpu", [&]() { + cpu_kernel(iter, [](scalar_t x) { return calc_i1(x); }); + }); +} + +static void i1e_kernel(TensorIteratorBase& iter) { + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.common_dtype(), "i1e_cpu", [&]() { + cpu_kernel(iter, [](scalar_t x) { return calc_i1e(x); }); + }); +} + +static void erfcx_kernel(TensorIteratorBase& iter){ + AT_DISPATCH_FLOATING_TYPES(iter.common_dtype(), "erfcx_cpu", [&]() { + cpu_kernel( + iter, + [](scalar_t a) -> scalar_t { return calc_erfcx(a); }); + }); +} + +static void round_decimals_kernel(TensorIteratorBase& iter, int64_t decimals) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.dtype(), "round_cpu", [&]() { + using opmath_t = at::opmath_type; + bool neg_flag = false; + opmath_t ten_pow_decimals; + if (decimals < 0) { + decimals = -decimals; + neg_flag = true; + } + ten_pow_decimals = static_cast(std::pow(10, decimals)); + cpu_kernel(iter, [ten_pow_decimals, neg_flag](scalar_t a) -> scalar_t { + return neg_flag ? std::nearbyint(static_cast(a) / ten_pow_decimals) * ten_pow_decimals + : std::nearbyint(static_cast(a) * ten_pow_decimals) / ten_pow_decimals; + }); + }); +} + +static void bessel_j0_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "bessel_j0_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return bessel_j0_forward(x); + }); + }); +} // bessel_j0_kernel(TensorIteratorBase& iterator) + +static void bessel_j1_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "bessel_j1_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return bessel_j1_forward(x); + }); + }); +} // bessel_j1_kernel(TensorIteratorBase& iterator) + +static void bessel_y0_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "bessel_y0_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return bessel_y0_forward(x); + }); + }); +} // bessel_y0_kernel(TensorIteratorBase& iterator) + +static void bessel_y1_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "bessel_y1_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return bessel_y1_forward(x); + }); + }); +} // bessel_y1_kernel(TensorIteratorBase& iterator) + +static void modified_bessel_i0_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "modified_bessel_i0_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return modified_bessel_i0_forward(x); + }); + }); +} // modified_bessel_i0_kernel(TensorIteratorBase& iterator) + +static void modified_bessel_i1_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "modified_bessel_i1_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return modified_bessel_i1_forward(x); + }); + }); +} // modified_bessel_i1_kernel(TensorIteratorBase& iterator) + +static void modified_bessel_k0_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "modified_bessel_k0_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return modified_bessel_k0_forward(x); + }); + }); +} // modified_bessel_k0_kernel(TensorIteratorBase& iterator) + +static void modified_bessel_k1_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "modified_bessel_k1_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return modified_bessel_k1_forward(x); + }); + }); +} // modified_bessel_k1_kernel(TensorIteratorBase& iterator) + +// TODO: Disable cont. branch to test more risky code + +#define IMPLEMENT_ITERATOR_LAMBDA(op) \ + [&](char** data_, const int64_t* strides, int64_t n) { \ + scalar_t* out_data = reinterpret_cast(data_[0]); \ + scalar_t* in_data = reinterpret_cast(data_[1]); \ + int64_t out_stride = strides[0] / sizeof(scalar_t); \ + int64_t in_stride = strides[1] / sizeof(scalar_t); \ + if (out_stride == 1 && in_stride == 1) { \ + vml::v##op(out_data, in_data, n); \ + return; \ + } \ + static constexpr int64_t WIDTH = (8*1024) / sizeof(scalar_t); \ + for (int64_t i = 0; i < n; i += WIDTH) { \ + scalar_t buffer[WIDTH]; \ + const int64_t width = std::min(WIDTH, n - i); \ + /* If either tensor is contiguous use it, otherwise copy into */ \ + /* a contiguous buffer so compute can still be vectorized */ \ + scalar_t * in_buffer = in_stride == 1 ? &in_data[i] : &buffer[0]; \ + scalar_t * out_buffer = out_stride == 1 ? &out_data[i] : &buffer[0]; \ + if (in_stride != 1) \ + for (const auto j : c10::irange(width)) \ + in_buffer[j] = in_data[in_stride * (i + j)]; \ + vml::v##op(out_buffer, in_buffer, width); \ + if (out_stride != 1) \ + for (const auto j : c10::irange(width)) \ + out_data[out_stride * (i + j)] = out_buffer[j]; \ + } \ + } + +#define IMPLEMENT_FLOAT_KERNEL(op) \ + inline namespace CPU_CAPABILITY { \ + static void op##_kernel(TensorIteratorBase& iter) { \ + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); \ + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), #op "_vml_cpu", [&]() { \ + constexpr int64_t grain_size = 2048; \ + iter.for_each(IMPLEMENT_ITERATOR_LAMBDA(op), grain_size); \ + }); \ + iter.cast_outputs(); \ + } \ + } + +#define IMPLEMENT_FLOAT_KERNEL_WITHOUT_AVX512(op) \ + IMPLEMENT_FLOAT_KERNEL(op) \ + REGISTER_DISPATCH(op##_stub, &CPU_CAPABILITY::op##_kernel) + +#define IMPLEMENT_FLOAT_KERNEL_WITH_AVX512(op) \ + IMPLEMENT_FLOAT_KERNEL(op) \ + ALSO_REGISTER_AVX512_DISPATCH(op##_stub, &CPU_CAPABILITY::op##_kernel) + +#define IMPLEMENT_COMPLEX_KERNEL(op) \ + inline namespace CPU_CAPABILITY { \ + void op##_kernel(TensorIteratorBase& iter) { \ + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); \ + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), #op "_vml_cpu", [&]() { \ + constexpr int64_t grain_size = 2048; \ + iter.for_each(IMPLEMENT_ITERATOR_LAMBDA(op), grain_size); \ + }); \ + iter.cast_outputs(); \ + } \ + } + +#define IMPLEMENT_COMPLEX_KERNEL_WITHOUT_AVX512(op) \ + IMPLEMENT_COMPLEX_KERNEL(op) \ + REGISTER_DISPATCH(op##_stub, &CPU_CAPABILITY::op##_kernel) + +#define IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(op) \ + IMPLEMENT_COMPLEX_KERNEL(op) \ + ALSO_REGISTER_AVX512_DISPATCH(op##_stub, &CPU_CAPABILITY::op##_kernel) + +#define STATIC_IMPLEMENT_COMPLEX_KERNEL(op) \ + inline namespace CPU_CAPABILITY { \ + static void op##_kernel(TensorIteratorBase& iter) { \ + TORCH_INTERNAL_ASSERT(iter.ntensors() == 2); \ + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), #op "_vml_cpu", [&]() { \ + constexpr int64_t grain_size = 2048; \ + iter.for_each(IMPLEMENT_ITERATOR_LAMBDA(op), grain_size); \ + }); \ + iter.cast_outputs(); \ + } \ + } + +#define STATIC_IMPLEMENT_COMPLEX_KERNEL_WITHOUT_AVX512(op) \ + STATIC_IMPLEMENT_COMPLEX_KERNEL(op) \ + REGISTER_DISPATCH(op##_stub, &CPU_CAPABILITY::op##_kernel) + +#define STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(op) \ + STATIC_IMPLEMENT_COMPLEX_KERNEL(op) \ + ALSO_REGISTER_AVX512_DISPATCH(op##_stub, &CPU_CAPABILITY::op##_kernel) + +} // CPU_CAPABILITY namespace + +// The following kernels are slower with AVX512 +REGISTER_DISPATCH(round_decimals_stub, &CPU_CAPABILITY::round_decimals_kernel) +REGISTER_DISPATCH(abs_stub, &CPU_CAPABILITY::abs_kernel) +REGISTER_DISPATCH(angle_stub, &CPU_CAPABILITY::angle_kernel) +REGISTER_DISPATCH(neg_stub, &CPU_CAPABILITY::neg_kernel) +REGISTER_DISPATCH(signbit_stub, &CPU_CAPABILITY::signbit_kernel) +REGISTER_DISPATCH(sinc_stub, &CPU_CAPABILITY::sinc_kernel) +REGISTER_DISPATCH(bitwise_not_stub, &CPU_CAPABILITY::bitwise_not_kernel) +REGISTER_DISPATCH(logical_not_stub, &CPU_CAPABILITY::logical_not_kernel) +REGISTER_DISPATCH(nan_to_num_stub, &CPU_CAPABILITY::nan_to_num_kernel) +REGISTER_DISPATCH(conj_physical_stub, &CPU_CAPABILITY::conj_kernel) +REGISTER_DISPATCH(rsqrt_stub, &CPU_CAPABILITY::rsqrt_kernel) +REGISTER_DISPATCH(frac_stub, &CPU_CAPABILITY::frac_kernel) +REGISTER_DISPATCH(special_entr_stub, &CPU_CAPABILITY::entr_kernel) +REGISTER_DISPATCH(special_i0e_stub, &CPU_CAPABILITY::i0e_kernel) +REGISTER_DISPATCH(special_ndtri_stub, &CPU_CAPABILITY::ndtri_kernel) +REGISTER_DISPATCH(special_modified_bessel_k0_stub, &CPU_CAPABILITY::modified_bessel_k0_kernel) +REGISTER_DISPATCH(special_modified_bessel_k1_stub, &CPU_CAPABILITY::modified_bessel_k1_kernel) +IMPLEMENT_FLOAT_KERNEL_WITHOUT_AVX512(ceil) +IMPLEMENT_FLOAT_KERNEL_WITHOUT_AVX512(floor) +IMPLEMENT_FLOAT_KERNEL_WITHOUT_AVX512(round) +IMPLEMENT_COMPLEX_KERNEL_WITHOUT_AVX512(sqrt) +IMPLEMENT_FLOAT_KERNEL_WITHOUT_AVX512(trunc) +IMPLEMENT_FLOAT_KERNEL_WITHOUT_AVX512(i0) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITHOUT_AVX512(sin) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITHOUT_AVX512(cos) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITHOUT_AVX512(tan) + +// The following kernels are compute-intensive & are compiled with both AVX512 +// & AVX2 +ALSO_REGISTER_AVX512_DISPATCH(sign_stub, &CPU_CAPABILITY::sign_kernel) +ALSO_REGISTER_AVX512_DISPATCH(sgn_stub, &CPU_CAPABILITY::sgn_kernel) +ALSO_REGISTER_AVX512_DISPATCH(reciprocal_stub, &CPU_CAPABILITY::reciprocal_kernel) +ALSO_REGISTER_AVX512_DISPATCH(exp2_stub, &CPU_CAPABILITY::exp2_kernel) +ALSO_REGISTER_AVX512_DISPATCH(sigmoid_stub, &CPU_CAPABILITY::sigmoid_kernel) +ALSO_REGISTER_AVX512_DISPATCH(logit_stub, &CPU_CAPABILITY::logit_kernel) +ALSO_REGISTER_AVX512_DISPATCH(sinh_stub, &CPU_CAPABILITY::sinh_kernel) +ALSO_REGISTER_AVX512_DISPATCH(cosh_stub, &CPU_CAPABILITY::cosh_kernel) +ALSO_REGISTER_AVX512_DISPATCH(atanh_stub, &CPU_CAPABILITY::atanh_kernel) + +// Might enable AVX512 dispatch after enabling explicit vectorization for them +REGISTER_DISPATCH(acosh_stub, &CPU_CAPABILITY::acosh_kernel) +REGISTER_DISPATCH(asinh_stub, &CPU_CAPABILITY::asinh_kernel) +REGISTER_DISPATCH(digamma_stub, &CPU_CAPABILITY::digamma_kernel) +REGISTER_DISPATCH(trigamma_stub, &CPU_CAPABILITY::trigamma_kernel) +REGISTER_DISPATCH(polygamma_stub, &CPU_CAPABILITY::polygamma_kernel) +REGISTER_DISPATCH(kaiser_window_stub, &CPU_CAPABILITY::kaiser_window_kernel) +REGISTER_DISPATCH(frexp_stub, &CPU_CAPABILITY::frexp_kernel) +REGISTER_DISPATCH(special_log_ndtr_stub, &CPU_CAPABILITY::log_ndtr_kernel) +REGISTER_DISPATCH(special_i1_stub, &CPU_CAPABILITY::i1_kernel) +REGISTER_DISPATCH(special_i1e_stub, &CPU_CAPABILITY::i1e_kernel) +REGISTER_DISPATCH(special_erfcx_stub, &CPU_CAPABILITY::erfcx_kernel) +REGISTER_DISPATCH(special_bessel_j0_stub, &CPU_CAPABILITY::bessel_j0_kernel) +REGISTER_DISPATCH(special_bessel_j1_stub, &CPU_CAPABILITY::bessel_j1_kernel) +REGISTER_DISPATCH(special_bessel_y0_stub, &CPU_CAPABILITY::bessel_y0_kernel) +REGISTER_DISPATCH(special_bessel_y1_stub, &CPU_CAPABILITY::bessel_y1_kernel) +REGISTER_DISPATCH(special_modified_bessel_i0_stub, &CPU_CAPABILITY::modified_bessel_i0_kernel) +REGISTER_DISPATCH(special_modified_bessel_i1_stub, &CPU_CAPABILITY::modified_bessel_i1_kernel) + +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(acos) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(asin) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(atan) +IMPLEMENT_FLOAT_KERNEL_WITH_AVX512(erf) +IMPLEMENT_FLOAT_KERNEL_WITH_AVX512(erfc) +IMPLEMENT_FLOAT_KERNEL_WITH_AVX512(erfinv) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(exp) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(expm1) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(log) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(log10) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(log1p) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(log2) +STATIC_IMPLEMENT_COMPLEX_KERNEL_WITH_AVX512(tanh) +IMPLEMENT_FLOAT_KERNEL_WITH_AVX512(lgamma) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Unfold2d.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Unfold2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..696c2850305a981d2cdd36447ded332bc3d4df0e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/Unfold2d.cpp @@ -0,0 +1,445 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +inline void cadd( + scalar_t* z, + const scalar_t* x, + const scalar_t* y, + int64_t n) { + using Vec = vec::Vectorized; + // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) + char* ptrs[] = {reinterpret_cast(z), + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + reinterpret_cast(const_cast(x)), + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + reinterpret_cast(const_cast(y))}; + vectorized_loop( + ptrs, + n, + -1, + [](scalar_t x, scalar_t y) -> scalar_t { return x + y; }, + [](Vec x, Vec y) -> Vec { return x + y; }); +} + +template +void unfolded2d_acc( + scalar_t* finput_data, + scalar_t* input_data, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t output_height, + int64_t output_width) { + at::parallel_for(0, n_input_plane, 0, [&](int64_t start, int64_t end) { + for (const auto nip : c10::irange(start, end)) { + for (int64_t kh = 0; kh < kH; kh++) { + for (int64_t kw = 0; kw < kW; kw++) { + scalar_t* src = finput_data + + nip * ((size_t)kH * kW * output_height * output_width) + + kh * ((size_t)kW * output_height * output_width) + + kw * ((size_t)output_height * output_width); + scalar_t* dst = + input_data + nip * ((size_t)input_height * input_width); + if (padW > 0 || padH > 0) { + for (int64_t y = 0; y < output_height; y++) { + auto iy = y * dH - padH + kh; + if (iy < 0 || iy >= input_height) { + } else { + if (dW == 1) { + auto ix = 0 - padW + kw; + auto lpad = std::max(0, padW - kw); + auto rpad = std::max(0, padW - (kW - kw - 1)); + scalar_t* dst_slice = + dst + (size_t)iy * input_width + ix + lpad; + cadd( + dst_slice, + dst_slice, + src + (size_t)y * output_width + lpad, + output_width - lpad - rpad); + } else { + for (int64_t x = 0; x < output_width; x++) { + auto ix = x * dW - padW + kw; + if (ix < 0 || ix >= input_width) { + } else { + scalar_t* dst_slice = dst + (size_t)iy * input_width + ix; + *dst_slice = *dst_slice + src[(size_t)y * output_width + x]; + } + } + } + } + } + } else { + for (int64_t y = 0; y < output_height; y++) { + auto iy = y * dH + kh; + auto ix = 0 + kw; + if (dW == 1) { + scalar_t* dst_slice = dst + (size_t)iy * input_width + ix; + cadd( + dst_slice, + dst_slice, + src + (size_t)y * output_width, + output_width); + } else { + for (int64_t x = 0; x < output_width; x++) { + scalar_t* dst_slice = + dst + (size_t)iy * input_width + ix + x * dW; + *dst_slice = *dst_slice + src[(size_t)y * output_width + x]; + } + } + } + } + } + } + } + }); +} + +template +void unfolded2d_acc_channels_last( + scalar_t* finput_data, + scalar_t* input_data, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t output_height, + int64_t output_width) { + + for (int64_t y = 0; y < output_height; y++) { + for (int64_t x = 0; x < output_width; x++) { + scalar_t* src = finput_data + y * output_width * kH * kW * n_input_plane + x * kH * kW * n_input_plane; + scalar_t* dst = input_data; + + if (padW > 0 || padH > 0) { + for (int64_t kh = 0; kh < kH; kh++) { + for (int64_t kw = 0; kw < kW; kw++) { + int64_t iy = y * dH - padH + kh; + int64_t ix = x * dW - padW + kw; + if (iy < 0 || iy >= input_height || ix < 0 || ix >= input_width) { + } else { + scalar_t* dst_slice = dst + iy * input_width * n_input_plane + ix * n_input_plane; + scalar_t* src_slice = src + kh * kW * n_input_plane + kw * n_input_plane; + cadd(dst_slice, + dst_slice, + src_slice, + n_input_plane); + } + } + } + } else { + for (int64_t kh = 0; kh < kH; kh++) { + for (int64_t kw = 0; kw < kW; kw++) { + int64_t iy = y * dH + kh; + int64_t ix = x * dW + kw; + scalar_t* dst_slice = dst + iy * input_width * n_input_plane + ix * n_input_plane; + scalar_t* src_slice = src + kh * kW * n_input_plane + kw * n_input_plane; + cadd(dst_slice, + dst_slice, + src_slice, + n_input_plane); + } + } + } + } + } +} + +/* note: due to write issues, this one cannot be parallelized as well as + * unfolded2d_copy */ +#if defined(__GNUC__) && __GNUC__ == 14 && defined(__ARM_FEATURE_SVE) +// Workaround for gcc-14.2.0 ICE during RTL pass: vregs when compiling for SVE +// NS: With or without BF16, see https://github.com/pytorch/pytorch/issues/172630 +__attribute__((optimize("no-tree-vectorize"))) +#endif +void unfolded2d_acc_kernel( + ScalarType dtype, + void *finput_data, + void *input_data, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t output_height, + int64_t output_width, + bool is_channels_last) { + // This function assumes that + // output_height*dH does not overflow a int64_t + // output_width*dW does not overflow a int64_t + + if (is_channels_last) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, dtype, "unfolded2d_acc_channels_last", [&] { + unfolded2d_acc_channels_last( + static_cast(finput_data), + static_cast(input_data), + kH, kW, + dH, dW, + padH, padW, + n_input_plane, + input_height, + input_width, + output_height, + output_width); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, dtype, "unfolded2d_acc", [&] { + unfolded2d_acc( + static_cast(finput_data), + static_cast(input_data), + kH, kW, + dH, dW, + padH, padW, + n_input_plane, + input_height, + input_width, + output_height, + output_width); + }); + } +} + +template +void unfolded2d_copy( + const scalar_t* input_data, + scalar_t* finput_data, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t output_height, + int64_t output_width) { + at::parallel_for( + 0, n_input_plane * kH * kW, 0, [&](int64_t start, int64_t end) { + for (const auto k : c10::irange(start, end)) { + int64_t nip = k / (kH * kW); + int64_t rest = k % (kH * kW); + int64_t kh = rest / kW; + int64_t kw = rest % kW; + scalar_t* dst = finput_data + + nip * ((size_t)kH * kW * output_height * output_width) + + kh * ((size_t)kW * output_height * output_width) + + kw * ((size_t)output_height * output_width); + const scalar_t* src = + input_data + nip * ((size_t)input_height * input_width); + if (padW > 0 || padH > 0) { + for (int64_t y = 0; y < output_height; y++) { + auto iy = y * dH - padH + kh; + if (iy < 0 || iy >= input_height) { + memset( + dst + (size_t)y * output_width, + 0, + sizeof(scalar_t) * output_width); + } else { + if (dW == 1) { + auto ix = 0 - padW + kw; + auto lpad = std::max(0, padW - kw); + auto rpad = std::max(0, padW - (kW - kw - 1)); + if (output_width - rpad - lpad <= 0) { + memset( + dst + (size_t)y * output_width, + 0, + sizeof(scalar_t) * output_width); + } else { + if (lpad > 0) + memset( + dst + (size_t)y * output_width, + 0, + sizeof(scalar_t) * lpad); + memcpy( + dst + (size_t)y * output_width + lpad, + src + (size_t)iy * input_width + ix + lpad, + sizeof(scalar_t) * (output_width - rpad - lpad)); + if (rpad > 0) + memset( + dst + (size_t)y * output_width + output_width - rpad, + 0, + sizeof(scalar_t) * rpad); + } + } else { + for (int64_t x = 0; x < output_width; x++) { + auto ix = x * dW - padW + kw; + if (ix < 0 || ix >= input_width) + memset( + dst + (size_t)y * output_width + x, + 0, + sizeof(scalar_t) * 1); + else + memcpy( + dst + (size_t)y * output_width + x, + src + (size_t)iy * input_width + ix, + sizeof(scalar_t) * 1); + } + } + } + } + } else { + for (int64_t y = 0; y < output_height; y++) { + auto iy = y * dH + kh; + auto ix = 0 + kw; + if (dW == 1) + memcpy( + dst + (size_t)y * output_width, + src + (size_t)iy * input_width + ix, + sizeof(scalar_t) * output_width); + else { + for (int64_t x = 0; x < output_width; x++) + memcpy( + dst + (size_t)y * output_width + x, + src + (size_t)iy * input_width + ix + x * dW, + sizeof(scalar_t) * 1); + } + } + } + } + }); +} + +template +void unfolded2d_copy_channels_last( + const scalar_t* input_data, + scalar_t* finput_data, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t output_height, + int64_t output_width) { + at::parallel_for(0, output_height * output_width, 0, [&](int64_t start, int64_t end) { + int64_t y = 0; + int64_t x = 0; + data_index_init(start, y, output_height, x, output_width); + + for (const auto k [[maybe_unused]] : c10::irange(start, end)) { + scalar_t* dst = finput_data + y * output_width * kH * kW * n_input_plane + + x * kH * kW * n_input_plane; + const scalar_t* src = input_data; + + if (padW > 0 || padH > 0) { + for (int64_t kh = 0; kh < kH; kh++) { + for (int64_t kw = 0; kw < kW; kw++) { + int64_t iy = y * dH - padH + kh; + int64_t ix = x * dW - padW + kw; + if (iy < 0 || iy >= input_height || ix < 0 || ix >= input_width) { + memset(dst + kh * kW * n_input_plane + kw * n_input_plane, + 0, + sizeof(scalar_t) * n_input_plane); + } else { + memcpy(dst + kh * kW * n_input_plane + kw * n_input_plane, + src + iy * input_width * n_input_plane + ix * n_input_plane, + sizeof(scalar_t) * n_input_plane); + } + } + } + } else { + for (int64_t kh = 0; kh < kH; kh++) { + for (int64_t kw = 0; kw < kW; kw++) { + int64_t iy = y * dH + kh; + int64_t ix = x * dW + kw; + memcpy(dst + kh * kW * n_input_plane + kw * n_input_plane, + src + iy * input_width * n_input_plane + ix * n_input_plane, + sizeof(scalar_t) * n_input_plane); + } + } + } + // move on to next output index + data_index_step(y, output_height, x, output_width); + } + }); +} + +void unfolded2d_copy_kernel( + ScalarType dtype, + void *finput_data, + const void *input_data, + int64_t kH, + int64_t kW, + int64_t dH, + int64_t dW, + int64_t padH, + int64_t padW, + int64_t n_input_plane, + int64_t input_height, + int64_t input_width, + int64_t output_height, + int64_t output_width, + bool is_channels_last) { + // This function assumes that + // kH*kW does not overflow an int + // n_input_plane*kH*kW does not overflow a int64_t + // output_height*dH does not overflow a int64_t + // output_width*dW does not overflow a int64_t + + if (is_channels_last) { + AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, dtype, "unfolded2d_copy_channels_last", [&] { + unfolded2d_copy_channels_last( + static_cast(input_data), + static_cast(finput_data), + kH, kW, + dH, dW, + padH, padW, + n_input_plane, + input_height, + input_width, + output_height, + output_width); + }); + } else { + AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::BFloat16, at::ScalarType::Half, dtype, "unfolded2d_copy", [&] { + unfolded2d_copy( + static_cast(input_data), + static_cast(finput_data), + kH, kW, + dH, dW, + padH, padW, + n_input_plane, + input_height, + input_width, + output_height, + output_width); + }); + } +} + +} // namespace + +REGISTER_DISPATCH(unfolded2d_copy_stub, &unfolded2d_copy_kernel) +REGISTER_DISPATCH(unfolded2d_acc_stub, &unfolded2d_acc_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UnfoldBackwardKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UnfoldBackwardKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a50c91fc0c44b648f54be09124791224697a015 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UnfoldBackwardKernel.cpp @@ -0,0 +1,152 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#if (defined(_WIN32) || defined(_WIN64)) +#define RESTRICT __restrict +#else +#define RESTRICT __restrict__ +#endif + +// Note on naming: it is unconventional. +// grad_in does not mean that it is a gradient wrt to input, +// grad_in/grad_out is just an input/output of unfold_backward kernel. +// +// unfold_backward, the algorithm. +// +// Consider out = in.unfold(dim, size, step), then +// out.shape[dim] == (in.shape[dim] - size) / step + 1, +// out.shape[-1] == size. +// out.dims() == in.dims() + 1 +// +// unfold_backward receives grad_in and returns grad_out such that +// grad_in.shape == out.shape, +// grad_out.shape = in.shape. +// +// unfold_backward considers the following two cases: +// case1. step >= size. +// case2. step < size. +// +// case1. step >= size. +// In this case the iteration takes over grad_in and performs the following copy: +// grad_out[..., i_out_dim,...] = grad_in[..., i_in_dim,..., i_in_last_dim], +// where i_out_dim = i_in_dim * step + i_in_last_dim. +// +// case2. step < size. +// In this case the iteration takes over grad_out, +// where grad_out[...,i_out_dim,...] accumulates all values +// grad_in[...,i_in_dim,...,i_in_last_dim], where +// i_in_dim is in [left_idx_fold, right_idx_fold], +// i_in_last_dim = i_out_dim - i_in_dim * step, +// left_idx_fold = (i_out_dim - size) / step +// if i_out_dim in [left_idx_fold * step, left_idx_fold * step + size) +// else (i_out_dim - size) / step + 1, +// right_idx_fold = i_out_dim / step. +// +// Simply put, given i_out_dim, we find which folds of grad_in +// intersect with i_out_dim, these are precisely [left_idx_fold, right_idx_fold], +// and then the corresponding value of grad_in[...,i_in_dim,...,i_in_last_dim] +// gets added up to grad_out[...,i_out_dim,...]. + +namespace at::native { + +namespace { + +template +void _unfold_backward_internal_kernel( + TensorIterator& iter, + int64_t size, + int64_t step, + int64_t grad_in_dim_stride, + int64_t grad_in_last_dim_stride, + int64_t grad_in_dim_size, + int64_t grad_out_dim_stride +) { + if (iter.numel() == 0) { + return; + } + + auto loop = [&](char** data, const int64_t* strides, int64_t nelems) { + auto* RESTRICT grad_out_ptr = data[0]; + auto* RESTRICT grad_in_ptr = data[1]; + auto* RESTRICT idx_dim_ptr = data[2]; + + for ([[maybe_unused]] const auto elem : c10::irange(nelems)) { + auto* RESTRICT grad_out_data = reinterpret_cast(grad_out_ptr); + auto* RESTRICT grad_in_data = reinterpret_cast(grad_in_ptr); + + auto idx_dim = *reinterpret_cast(idx_dim_ptr); + + // left_fold potentially intersecting with idx_dim + // is either (idx_dim - size) / step or the next integer. + int64_t left_fold_idx = (idx_dim > size) ? (idx_dim - size) / step : 0; + if (!(left_fold_idx * step <= idx_dim && idx_dim < left_fold_idx * step + size)) { + ++left_fold_idx; + } + + auto right_fold_idx = idx_dim / step; + right_fold_idx = (right_fold_idx >= grad_in_dim_size) + ? (grad_in_dim_size - 1) : right_fold_idx; + + for (auto fold_idx = left_fold_idx; fold_idx <= right_fold_idx; ++fold_idx) { + auto idx_last_dim = idx_dim - fold_idx * step; + *grad_out_data += grad_in_data[fold_idx * grad_in_dim_stride + + idx_last_dim * grad_in_last_dim_stride]; + } + + grad_out_ptr += strides[0]; + grad_in_ptr += strides[1]; + idx_dim_ptr += strides[2]; + } + }; + + iter.for_each(loop); +} + +void unfold_backward_cpu_kernel( + Tensor& grad_out, + const Tensor& grad_in, + int64_t dim, + int64_t size, + int64_t step +) { + dim = maybe_wrap_dim(dim, grad_out.dim()); + // last dim stores the folds + auto last_dim = maybe_wrap_dim(-1, grad_in.dim()); + + auto grad_in_dim_stride = ensure_nonempty_stride(grad_in, dim); + auto grad_in_last_dim_stride = ensure_nonempty_stride(grad_in, last_dim); + auto grad_in_dim_size = ensure_nonempty_size(grad_in, dim); + + auto grad_out_dim_stride = ensure_nonempty_stride(grad_out, dim); + + TensorIterator iter = _make_unfold_backward_iter_over_grad_out( + grad_out, grad_in, dim, size, step); + + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + at::ScalarType::Half, at::ScalarType::Bool, at::ScalarType::BFloat16, + iter.dtype(), + "unfold_backward_cpu", [&] { + _unfold_backward_internal_kernel( + iter, + size, + step, + grad_in_dim_stride, + grad_in_last_dim_stride, + grad_in_dim_size, + grad_out_dim_stride + ); + } + ); +} + +} + +REGISTER_DISPATCH(unfold_backward_stub, &unfold_backward_cpu_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bd972119b6f1d7ffb9cc0170f03b39963e7d969 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernel.cpp @@ -0,0 +1,2226 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#endif + +namespace at::native { +namespace { + +using scale_t = std::vector>; + +// Naming conventions used in this file: +// +// - "non_separable": All spatial dimensions are interpolated in a single +// TensorIterator pass, using the recursive InterpolateNonSeparable struct. +// Non-separable is always multi-dimensional (Nd). +// +// - "separable": The multi-dimensional interpolation is decomposed into a +// sequence of 1d passes (one per spatial dimension). The entry point is Nd +// (it loops over dims), and inner functions are 1d. +// +// - "1d": Refers to processing a single spatial dimension within the +// separable approach. Not to be confused with 1d interpolation (e.g. +// linear); it means one dimension of a multi-dimensional separable +// decomposition. +// +// - "Nd": Templated on out_ndims (1, 2, or 3) for the separable approach. + + +// ---- Non-separable interpolation ---- +// +// Used by: nearest, linear, bilinear (float), cubic (float), trilinear. +// Processes all spatial dims in a single TensorIterator pass via the recursive +// InterpolateNonSeparable struct. +// +// Call chain: +// upsample_non_separable_Nd_kernel_impl +// -> upsample_non_separable +// -> basic_loop_non_separable +// -> interpolate_non_separable +// -> InterpolateNonSeparable (recursive struct) +// +// Helper structs and methods for upsample_non_separable +// +// Interpolation structure to compute output value in n-dimensional case. +// - recursively compute interpolated output for each dimension +// - we rely a lot on compiler's code optimization such that implemented operations +// can be automatically factorized and vectorized using SSE and AVX2 +template +struct InterpolateNonSeparable { + static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) { + index_t ids = *(index_t*)&data[0][i * strides[0]]; + opmath_t wts = *(scalar_t*)&data[1][i * strides[1]]; + opmath_t t = InterpolateNonSeparable::eval(src + ids, &data[2 * interp_size], &strides[2 * interp_size], i); + opmath_t output = t * wts; + for (const auto j : c10::irange(1, interp_size)) { + ids = *(index_t*)&data[2 * j + 0][i * strides[2 * j + 0]]; + wts = *(scalar_t*)&data[2 * j + 1][i * strides[2 * j + 1]]; + t = InterpolateNonSeparable::eval(src + ids, &data[2 * interp_size], &strides[2 * interp_size], i); + output += t * wts; + } + return output; + } +}; + +template +struct InterpolateNonSeparable<1, scalar_t, opmath_t, index_t, interp_size> { + static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) { + index_t ids = *(index_t*)&data[0][i * strides[0]]; + opmath_t wts = *(scalar_t*)&data[1][i * strides[1]]; + opmath_t t = *(scalar_t *)&src[ids]; + opmath_t output = t * wts; + for (const auto j : c10::irange(1, interp_size)) { + ids = *(index_t*)&data[2 * j + 0][i * strides[2 * j + 0]]; + wts = *(scalar_t*)&data[2 * j + 1][i * strides[2 * j + 1]]; + t = *(scalar_t *)&src[ids]; + output += t * wts; + } + return output; + } +}; + +template +struct InterpolateNonSeparable { + static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) { + index_t ids = *(index_t*)&data[0][i * strides[0]]; + return InterpolateNonSeparable::eval(src + ids, &data[2], &strides[2], i); + } +}; + +template +struct InterpolateNonSeparable<1, scalar_t, opmath_t, index_t, 1> { + static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) { + index_t ids = *(index_t*)&data[0][i * strides[0]]; + return *(scalar_t *)&src[ids]; + } +}; + +// There is an unexpected 2x slowdown for upsample_trilinear3d channels_first +// for both 1 and 6 threads. We have to specialize this case as below: +// Once the issue is fixed we can keep generic implementation and remove: +// struct InterpolateNonSeparable and +// struct InterpolateNonSeparable<1, scalar_t, index_t, 2> +template +struct InterpolateNonSeparable { + static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) { + index_t i0 = *(index_t*)&data[0][i * strides[0]]; + index_t i1 = *(index_t*)&data[2][i * strides[2]]; + opmath_t w0 = *(scalar_t *)&data[1][i * strides[1]]; + opmath_t w1 = *(scalar_t *)&data[3][i * strides[3]]; + + opmath_t t0 = InterpolateNonSeparable::eval(src + i0, &data[4], &strides[4], i); + opmath_t t1 = InterpolateNonSeparable::eval(src + i1, &data[4], &strides[4], i); + + return t0 * w0 + t1 * w1; + } +}; + +template +struct InterpolateNonSeparable<1, scalar_t, opmath_t, index_t, 2> { + static inline opmath_t eval(char* src, char** data, const int64_t* strides, int64_t i) { + index_t i0 = *(index_t*)&data[0][i * strides[0]]; + index_t i1 = *(index_t*)&data[2][i * strides[2]]; + opmath_t w0 = *(scalar_t *)&data[1][i * strides[1]]; + opmath_t w1 = *(scalar_t *)&data[3][i * strides[3]]; + opmath_t t0 = *(scalar_t *)&src[i0]; + opmath_t t1 = *(scalar_t *)&src[i1]; + return t0 * w0 + t1 * w1; + } +}; + +template +inline scalar_t interpolate_non_separable(char* src, char** data, const int64_t* strides, int64_t i) { + using opmath_t = at::opmath_type; + return InterpolateNonSeparable::eval(src, data, strides, i); +} + +// ---- Separable interpolation ---- +// +// Used by: bilinear/bicubic with antialias=True, and bilinear/bicubic uint8 +// (as fallback when AVX isn't supported). +// Processes one spatial dimension at a time. The outer loop over dimensions +// is in upsample_separable_Nd_kernel_impl. +// +// Call chain: +// upsample_separable_Nd_kernel_impl (loops over dims) +// -> upsample_separable_1d +// -> basic_loop_separable_1d_horizontal (for last spatial dim, i.e. W) +// -> interpolate_separable_1d +// -> basic_loop_separable_1d_vertical (for other spatial dims, e.g. H, D) +// -> interpolate_separable_1d_zero_strides + +template +inline scalar_t interpolate_separable_1d_zero_strides( + char* src, + char** data, + const index_t ids_stride) { + const index_t ids_min = *(index_t*)&data[0][0]; + const index_t ids_size = *(index_t*)&data[1][0]; + + char* src_min = src + ids_min; + + scalar_t t = *(scalar_t*)&src_min[0]; + index_t wts_idx = *(index_t*)&data[4][0]; + scalar_t* wts_ptr = (scalar_t*)&data[3][wts_idx]; + scalar_t wts = wts_ptr[0]; + + scalar_t output = t * wts; + for (const auto j : c10::irange(1, ids_size)) { + wts = wts_ptr[j]; + t = *(scalar_t*)&src_min[j * ids_stride]; + output += t * wts; + } + return output; +} + +template +inline scalar_t interpolate_separable_1d( + char* src, + char** data, + const int64_t* strides, + int64_t i, + const index_t ids_stride) { + index_t ids_min = *(index_t*)&data[0][i * strides[0]]; + index_t ids_size = *(index_t*)&data[1][i * strides[1]]; + + char* src_min = src + ids_min; + + scalar_t t = *(scalar_t*)&src_min[0]; + index_t wts_idx = *(index_t*)&data[4][i * strides[4]]; + scalar_t* wts_ptr = (scalar_t*)&data[3][wts_idx]; + scalar_t wts = wts_ptr[0]; + + scalar_t output = t * wts; + for (const auto j : c10::irange(1, ids_size)) { + wts = wts_ptr[j]; + t = *(scalar_t*)&src_min[j * ids_stride]; + output += t * wts; + } + return output; +} + +template +inline bool is_zero_stride(const int64_t* strides) { + bool output = strides[0] == 0; + for (const auto i : c10::irange(1, m)) { + output &= (strides[i] == 0); + } + return output; +} + +template +inline bool is_contiguous_stride(const int64_t* strides) { + bool output = (strides[0] == sizeof(index_t)) && (strides[1] == sizeof(scalar_t)); + for (int i=2; i<2 * interp_size; i+=2) { + output &= (strides[i] == sizeof(index_t)) && (strides[i + 1] == sizeof(scalar_t)); + } + return output; +} + +// Helper class to recursively check if all input strides corresponding to interpolated dimensions +// are equal zero except on a single dimension. +// +// Note: "zero-stride" and "non-zero stride" here refer to the strides of the +// pre-computed indices and weights tensors (extra TensorIterator inputs), NOT +// to the contiguity of the input or output data tensors. +// +// Inputs: array of strides of size N, non_zero_stride_dim which can be -1, 0, 1, 2, ... +// if non_zero_stride_dim, we check that all strides are equal zero, otherwise +// 4 strides corresponding to the strides for index_0, weight_0, index_1 and weight_1 for non_zero_stride_dim +// dimension should be non zero. +// +// Unit check of the recursion is to verify whether 4 strides for one interpolated dimension are either zero, +// see method is_zero_stride, or (sizeof(index_t), sizeof(scalar_t), sizeof(index_t), sizeof(scalar_t)), see +// method is_contiguous_stride. +// +// In practice, we have the following cases: +// - for ND, float32, channel first, strides are +// dimN-1, dim1, dim0 +// i0, w0, i1, w1, ..., i0, w0, i1, w1, i0, w0, i1, w1 +// strides=(0, 0, 0, 0, ..., 0, 0, 0, 0, 4, 4, 4, 4) +// +// if size dim0 is 1 then its strides are 0 and dim1 strides are equal 4 +// +// - for ND, float32, channel last, strides are +// dimN-1, dimN-2, dim0 +// i0, w0, i1, w1, i0, w0, i1, w1, ... i0, w0, i1, w1 +// strides=(0, 0, 0, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0) +// +// Using these methods we can hint the compiler to factorize constant indices and weights +// in upsample_non_separable +template +struct CheckAlmostAllZeroStrides { + static inline bool eval(const int64_t* strides) { + // N is dim index: N -> dim0, N-1 -> dim1, ... + // non_zero_stride_dim should be out_dims - dim + bool output = false; + if constexpr (N == non_zero_stride_dim) { + output = is_contiguous_stride(strides); + } else { + output = is_zero_stride<2 * interp_size>(strides); + } + return output && + CheckAlmostAllZeroStrides::eval( + &strides[2 * interp_size]); + } +}; + +template +struct CheckAlmostAllZeroStrides<0, non_zero_stride_dim, scalar_t, index_t, interp_size> { + static inline bool eval(const int64_t* /*strides*/) { + return true; + } +}; + +template +inline bool check_almost_all_zero_stride(const int64_t* strides) { + return CheckAlmostAllZeroStrides::eval(strides); +} + +// Helper method to compute interpolation for nearest, linear, cubic modes +template +inline void basic_loop_non_separable(char** data, const int64_t* strides, int64_t n) { + char* dst = data[0]; + char* src = data[1]; + for (const auto i : c10::irange(n)) { + *(scalar_t*)&dst[i * strides[0]] = interpolate_non_separable( + src + i * strides[1], &data[2], &strides[2], i); + } +} + +template +inline void basic_loop_separable_1d_vertical( + char** data, + const int64_t* strides, + int64_t n, + unsigned int weights_precision) { + char* dst = data[0]; + char* src = data[1]; + // index stride is constant for the given dimension + const int64_t ids_stride = *(int64_t*)&data[2 + 2][0]; + + for (const auto i : c10::irange(n)) { + *(scalar_t*)&dst[i * strides[0]] = + interpolate_separable_1d_zero_strides( + src + i * strides[1], &data[2], ids_stride); + } +} + +template <> +inline void basic_loop_separable_1d_vertical( + char** data, + const int64_t* strides, + int64_t n, + unsigned int weights_precision) { + // See Note [ Weights computation for uint8_t and multiplication trick ] + char* dst = data[0]; + char* src = data[1]; + + // index stride is constant for the given dimension + const int64_t ids_stride = *(int64_t*)&data[2 + 2][0]; + const int64_t ids_size = *(int64_t*)&data[2 + 1][0]; + const int64_t ids_min = *(int64_t*)&data[2 + 0][0]; + + int64_t i = 0; + + for (; i> weights_precision, 0, 255); + } +} + +template +inline void basic_loop_separable_1d_horizontal( + char** data, + const int64_t* strides, + int64_t n, + unsigned int weights_precision) { + char* dst = data[0]; + char* src = data[1]; + // index stride is constant for the given dimension + const int64_t ids_stride = *(int64_t*)&data[2 + 2][0]; + + if (strides[1] == 0) { + for (const auto i : c10::irange(n)) { + *(scalar_t*)&dst[i * strides[0]] = + interpolate_separable_1d( + src, &data[2], &strides[2], i, ids_stride); + } + } else { + for (const auto i : c10::irange(n)) { + *(scalar_t*)&dst[i * strides[0]] = + interpolate_separable_1d( + src + i * strides[1], &data[2], &strides[2], i, ids_stride); + } + } +} + +template <> +inline void basic_loop_separable_1d_horizontal( + char** data, + const int64_t* strides, + int64_t n, + unsigned int weights_precision) { + // See Note [ Weights computation for uint8_t and multiplication trick ] + char* dst = data[0]; + char* src = data[1]; + // index stride is constant for the given dimension + const int64_t ids_stride = *(int64_t*)&data[2 + 2][0]; + + int64_t i = 0; + + // Here we are implementing data interpolation within the same line (vs between the lines) + // output[x, y] = input[xmin[x], y] * W[x] + input[xmin[x] + 1, y] * W[x + 1] + ... + input[xmin[x] + xsize, y] * W[x + xsize] + + for (; i> weights_precision, 0, 255); + } +} + +// Generic upsampling computation method using TensorIterator for Nd case. +// Supports: nearest, linear, cubic modes with interp_size template argument: 1, 2, 4 +// +// Single loop function for 1d, 2d and 3d cases and modes +// For N dimensions, output value up to Di dimension can be computed as +// +// output_i[a] = interpolate(output_{i+1}[a], w_{i+1}[a], output_{i+1}[a+1], w_{i+1}[a+1], ...) +// with +// output_DN[a] = interpolate(input_DN[a], w_DN[a], input_DN[a+1], w_DN[a+1], ...) +// and i - dimension index and a - linear index for spatial coordinates +// +// The recursive call is implemented with the InterpolateNonSeparable struct using template for +// the loop unrolling on compile time. +template +void upsample_non_separable(at::TensorIterator& iter) +{ + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + // special-cases to let the compiler apply compile-time input-specific optimizations + if ((strides[0] == sizeof(scalar_t) && (strides[1] == 0) && + // NOLINTNEXTLINE(bugprone-branch-clone) + check_almost_all_zero_stride(&strides[2]))) { + // contiguous channels-first case + basic_loop_non_separable(data, strides, n); + } else if ((strides[0] == sizeof(scalar_t) && (strides[1] == sizeof(scalar_t)) && + check_almost_all_zero_stride(&strides[2]))) { + // contiguous channels-last case + basic_loop_non_separable(data, strides, n); + } else { + // fallback + basic_loop_non_separable(data, strides, n); + } + }; + iter.for_each(loop); +} + +template +void upsample_nearest_channels_last( + const Tensor& output_, + const Tensor& input_, + const scale_type& scales) { + TORCH_CHECK(input_.dtype() == output_.dtype(), "expected dtype ", input_.dtype(), + " for `output` but got dtype ", output_.dtype()); + + auto input_sizes = input_.sizes().vec(); + auto output_sizes = output_.sizes().vec(); + auto ndim = input_sizes.size(); + TORCH_CHECK(ndim >=4 && ndim <= 5, "Upsample with NHWC format supports tensors with 4 or 5 dims.") + + auto channels_last_memory_format = ndim == 4 ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(channels_last_memory_format); + auto output = output_.contiguous(channels_last_memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t num_batches = input_sizes[0]; + int64_t channels = input_sizes[1]; + int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = input_sizes[ndim - 2]; + int64_t output_height = output_sizes[ndim - 2]; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + int64_t numel = output.numel(); + + TORCH_CHECK(channels > 0, "expected input and output channels greater than 0 but got ", channels); + + using Vec = vec::Vectorized; + auto copy = [](scalar_t* out, const scalar_t* in, int64_t size) { + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec out_vec = Vec::loadu(in + d); + out_vec.store(out + d); + } + for (; d < size; d++) { + out[d] = in[d]; + } + }; + + auto loop2d = [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, num_batches, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[0]); + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[1]); + scalar_t* output_ptr = output_data + i * channels; + const scalar_t* input_ptr = input_data + n * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + copy(output_ptr, input_ptr, channels); + data_index_step(n, num_batches, oh, output_height, ow, output_width); + } + }; + + auto loop3d = [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t od = 0; + int64_t oh = 0; + int64_t ow = 0; + data_index_init(begin, n, num_batches, od, output_depth, oh, output_height, ow, output_width); + + for (const auto i : c10::irange(begin, end)) { + int64_t id = nearest_idx_fn(od, input_depth, output_depth, scales[0]); + int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[1]); + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[2]); + scalar_t* output_ptr = output_data + i * channels; + const scalar_t* input_ptr = input_data + n * input_depth * input_height * input_width * channels + + id * input_height * input_width * channels + + ih * input_width * channels + iw * channels; + copy(output_ptr, input_ptr, channels); + data_index_step(n, num_batches, od, output_depth, oh, output_height, ow, output_width); + } + }; + + if (ndim == 4) { + // upsample nearest 2d + at::parallel_for(0, numel / channels, at::internal::GRAIN_SIZE / channels, loop2d); + } else { + // upsample nearest 3d + TORCH_INTERNAL_ASSERT(ndim == 5); + at::parallel_for(0, numel / channels, at::internal::GRAIN_SIZE / channels, loop3d); + } + + if (!output_.is_contiguous(channels_last_memory_format)) { + output_.copy_(output); + } +} + +template +inline VecType interpolate(const scalar_t* t, accscalar_t w) { + return VecType::loadu(t) * VecType(w); +} + +template +inline VecType interpolate(const scalar_t* t, accscalar_t w, Args... args) { + return VecType::loadu(t) * VecType(w) + interpolate(args...); +} + +template +void upsample_linear_channels_last( + const Tensor& output_, + const Tensor& input_, + bool align_corners, + const scale_type& scales) { + TORCH_CHECK(input_.dtype() == output_.dtype(), "expected dtype ", input_.dtype(), + " for `output` but got dtype ", output_.dtype()); + + auto input_sizes = input_.sizes().vec(); + auto output_sizes = output_.sizes().vec(); + auto ndim = input_sizes.size(); + TORCH_CHECK(ndim >=4 && ndim <= 5, "Upsample with NHWC format supports tensors with 4 or 5 dims.") + + auto channels_last_memory_format = ndim == 4 ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::ChannelsLast3d; + auto input = input_.contiguous(channels_last_memory_format); + auto output = output_.contiguous(channels_last_memory_format); + + auto input_data = input.const_data_ptr(); + auto output_data = output.data_ptr(); + + int64_t num_batches = input_sizes[0]; + int64_t channels = input_sizes[1]; + int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = input_sizes[ndim - 2]; + int64_t output_height = output_sizes[ndim - 2]; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + + TORCH_CHECK(channels > 0, "expected input and output channels greater than 0 but got ", channels); + int64_t output_slice_size = output_depth * output_height * output_width * channels; + + using opmath_t = at::opmath_type; + using Vec = vec::Vectorized; + auto loop2d = [&](int64_t begin, int64_t end) { + const auto height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[0]); + const auto width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[1]); + + auto input_indexr = [=](int64_t n, int64_t h, int64_t w) { + return input_data + n * input_height * input_width * channels + + h * input_width * channels + w * channels; + }; + + int64_t ih0 = 0, ih1 = 0, iw0 = 0, iw1 = 0; + opmath_t h0lambda, h1lambda, w0lambda, w1lambda; + for (const auto n : c10::irange(begin, end)) { + for (const auto oh : c10::irange(output_height)) { + compute_source_index_and_lambda( + ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners); + for (const auto ow : c10::irange(output_width)) { + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + + scalar_t* out = output_data + n * output_slice_size + + oh * output_width * channels + ow * channels; + const scalar_t* i00 = input_indexr(n, ih0, iw0); + const scalar_t* i01 = input_indexr(n, ih0, iw1); + const scalar_t* i10 = input_indexr(n, ih1, iw0); + const scalar_t* i11 = input_indexr(n, ih1, iw1); + opmath_t w00 = h0lambda * w0lambda; + opmath_t w01 = h0lambda * w1lambda; + opmath_t w10 = h1lambda * w0lambda; + opmath_t w11 = h1lambda * w1lambda; + + int64_t size = channels; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + auto out_vec = interpolate(i00 + d, w00, i01 + d, w01, i10 + d, w10, i11 + d, w11); + out_vec.store(out + d); + } + for (; d < size; d++) { + out[d] = i00[d] * w00 + i01[d] * w01 + i10[d] * w10 + i11[d] * w11; + } + } + } + } + }; + + auto loop3d = [&](int64_t begin, int64_t end) { + const auto depth_scale = area_pixel_compute_scale( + input_depth, output_depth, align_corners, scales[0]); + const auto height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[1]); + const auto width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[2]); + + auto input_indexr = [=](int64_t n, int64_t d, int64_t h, int64_t w) { + return input_data + n * input_depth * input_height * input_width * channels + + d * input_height * input_width * channels + + h * input_width * channels + w * channels; + }; + + int64_t id0 = 0, id1 = 0, ih0 = 0, ih1 = 0, iw0 = 0, iw1 = 0; + opmath_t d0lambda, d1lambda, h0lambda, h1lambda, w0lambda, w1lambda; + for (const auto n : c10::irange(begin, end)) { + for (const auto od : c10::irange(output_depth)) { + compute_source_index_and_lambda( + id0, id1, d0lambda, d1lambda, depth_scale, od, input_depth, output_depth, align_corners); + for (const auto oh : c10::irange(output_height)) { + compute_source_index_and_lambda( + ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners); + for (const auto ow : c10::irange(output_width)) { + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + + scalar_t* out = output_data + n * output_slice_size + + od * output_height * output_width * channels + + oh * output_width * channels + ow * channels; + const scalar_t* i000 = input_indexr(n, id0, ih0, iw0); + const scalar_t* i001 = input_indexr(n, id0, ih0, iw1); + const scalar_t* i010 = input_indexr(n, id0, ih1, iw0); + const scalar_t* i011 = input_indexr(n, id0, ih1, iw1); + const scalar_t* i100 = input_indexr(n, id1, ih0, iw0); + const scalar_t* i101 = input_indexr(n, id1, ih0, iw1); + const scalar_t* i110 = input_indexr(n, id1, ih1, iw0); + const scalar_t* i111 = input_indexr(n, id1, ih1, iw1); + opmath_t w000 = d0lambda * h0lambda * w0lambda; + opmath_t w001 = d0lambda * h0lambda * w1lambda; + opmath_t w010 = d0lambda * h1lambda * w0lambda; + opmath_t w011 = d0lambda * h1lambda * w1lambda; + opmath_t w100 = d1lambda * h0lambda * w0lambda; + opmath_t w101 = d1lambda * h0lambda * w1lambda; + opmath_t w110 = d1lambda * h1lambda * w0lambda; + opmath_t w111 = d1lambda * h1lambda * w1lambda; + + int64_t size = channels; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + auto out_vec = interpolate( + i000 + d, w000, i001 + d, w001, i010 + d, w010, i011 + d, w011, + i100 + d, w100, i101 + d, w101, i110 + d, w110, i111 + d, w111); + out_vec.store(out + d); + } + for (; d < size; d++) { + out[d] = + i000[d] * w000 + i001[d] * w001 + i010[d] * w010 + i011[d] * w011 + + i100[d] * w100 + i101[d] * w101 + i110[d] * w110 + i111[d] * w111; + } + } + } + } + } + }; + + if (ndim == 4) { + // bilinear 2d + at::parallel_for(0, num_batches, at::internal::GRAIN_SIZE / output_slice_size / 4, loop2d); + } else { + // trilinear 3d + TORCH_INTERNAL_ASSERT(ndim == 5); + at::parallel_for(0, num_batches, at::internal::GRAIN_SIZE / output_slice_size / 8, loop3d); + } + + if (!output_.is_contiguous(channels_last_memory_format)) { + output_.copy_(output); + } +} + +// Helper structs to use with upsample_non_separable_Nd_kernel_impl +struct HelperInterpBase { + + static inline void init_indices_weights( + at::ScalarType output_type, + std::vector & output, int64_t output_size, int64_t ndims, + int64_t reshape_dim, int interp_size + ) { + + auto new_shape = std::vector(ndims, 1); + new_shape[reshape_dim] = output_size; + + for ([[maybe_unused]] const auto j : c10::irange(interp_size)) { + output.emplace_back( + empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType()))); + output.emplace_back(empty(new_shape, at::device(kCPU).dtype(output_type))); + } + } + + // This is a helper function for _compute_index_ranges_weights method that computes + // source two int64 scalars index min and size and a list weights (of size max_interp_size) + // for interpolation with antialiasing=true mode. It returns the maximal weights value + template + static inline scalar_t _compute_indices_min_size_weights_aa( + const int64_t i, const int64_t input_size, const scalar_t scale, const scalar_t support, + scalar_t* wt_ptr, const int64_t max_interp_size, aa_filter_fn_t filter_fn, + int64_t& xmin, int64_t& xsize + ) { + + scalar_t center = scale * (i + 0.5); + scalar_t total_w = 0.0; + scalar_t invscale = (scale >= 1.0) ? 1.0 / scale : 1.0; + xmin = std::max( + static_cast(center - support + 0.5), static_cast(0)); + xsize = std::min( + static_cast(center + support + 0.5), input_size) - xmin; + // There are rare cases when due to precision xsize can be larger than max_interp_size by one. + // We have to clip the value + xsize = std::clamp(xsize, static_cast(0), max_interp_size); + + int64_t j = 0; + for (; j < xsize; j++) { + scalar_t w = filter_fn((j + xmin - center + 0.5) * invscale); + wt_ptr[j] = w; + total_w += w; + } + + scalar_t wt_max = 0.0; + if (total_w != 0.0) { + for (j = 0; j < xsize; j++) { + wt_ptr[j] /= total_w; + wt_max = std::max(wt_max, wt_ptr[j]); + } + } + + for (; j < max_interp_size; j++) { + wt_ptr[j] = static_cast(0.0); + } + return wt_max; + } + + // This is a helper function for _compute_index_ranges_weights method that computes + // source two int64 scalars index min and size and a list weights (of size max_interp_size) + // for interpolation with antialiasing=false mode. It returns the maximal weights value. + // This function is templated with scalar_t for type of scale and weights but is only used for + // bilinear/bicubic modes on uint8 input and antialiasing=false (in this case scalar_t is double). + // For float input types we are using upsample_non_separable_Nd_kernel_impl and compute_indices_weights methods + template + static inline scalar_t _compute_indices_min_size_weights( + const int64_t i, const int64_t input_size, const scalar_t scale, + scalar_t* wt_ptr, const int64_t max_interp_size, aa_filter_fn_t filter_fn, + bool align_corners, int64_t& index_min, int64_t& index_size + ) { + // Notes. We do not use opmath_t in this method as f16 and other smaller float types are not routed here. + // Typical usage of this method is with scalar_t = double when computing indices and weights for uint8 input + // The code below partly adapts indices and lambda computation from compute_indices_weights method and + // index_min/index_size from _compute_indices_min_size_weights_aa + + bool cubic = max_interp_size > 2; + const auto real_input_index = area_pixel_compute_source_index( + scale, i, align_corners, /*cubic=*/cubic); + + scalar_t lambda; + int64_t input_index = 0; + guard_index_and_lambda(real_input_index, input_size, input_index, lambda); + + const auto support = static_cast(max_interp_size * 0.5); + const auto unbound_index_min = input_index - support + 1; + const auto unbound_index_max = input_index + support + 1; + index_min = std::max(unbound_index_min, static_cast(0)); + index_size = std::min(unbound_index_max, input_size) - index_min; + // There are rare cases when due to precision xsize can be larger than max_interp_size by one. + // We have to clip the value + index_size = std::clamp(index_size, static_cast(0), max_interp_size); + + // Below the weights are computed using filter_fn and accumulating values for indices being out of bounds + // For example, for bicubic mode for output index i = 0, we have input_index = -1, + // then we have unbound_index_min = -2 and unbound_index_max = 1 => unbounded input indices are [-2, -1, 0, 1] and + // valid input indices will be [0, 1] + // For unbounded input indices we compute four non-zero weights values [w0, w1, w2, w3] and as only two weights can + // be used with valid input indcies, we accumulate values in the following way: [w0 + w1 + w2, w3, 0.0, 0.0] + // This is equivalent to the float path which would compute indices as [0, 0, 0, 1] and weights as [w0, w1, w2, s3]. + // A similar accumulation should done for unbounded indices larger than input size. + auto w_index = 0; + scalar_t wt_max = 0.0; + for (const auto j : c10::irange(max_interp_size)) { + // initialize weights value as we will accumulate below + wt_ptr[j] = 0.0; + + scalar_t w = filter_fn(static_cast(j + 1 - support) - lambda); + if (unbound_index_min + j <= 0) { + w_index = 0; + } else if (unbound_index_min + j >= input_size - 1) { + w_index = index_size - 1; + } + wt_ptr[w_index] += w; + wt_max = std::max(wt_max, wt_ptr[w_index]); + w_index++; + } + + return wt_max; + } + + // Note [ Support for antialias=False as a subcase of antialias=True ] + // This function was originally written with the hard assumption that + // antialias=True and it was later extended to support antialias=False. + // The only difference between aa and no-aa is in how the + // weights and indices are computed (and their number). In aa their number is + // variable but with no-aa, they're fixed to interp_size. The same "filters" + // can be used otherwise. HOWEVER, support for antialias=False here may not be + // optimally optimized: the code assumes an arbitrary number of weights and + // indices, but this can be optimized further when aa=False since we know + // their actual dimensions. + template + static inline std::tuple, int, scalar_t> _compute_index_ranges_weights( + int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims, + int64_t reshape_dim, scalar_t scale, + int interp_size, aa_filter_fn_t aa_filter_fn, bool antialias, bool align_corners + ) { + + std::vector output; + + scalar_t support; + int max_interp_size = 0; + if (antialias) { + support = (scale >= 1.0) ? (interp_size * 0.5) * scale : interp_size * 0.5; + max_interp_size = (int) std::ceil(support) * 2 + 1; + } else { + support = interp_size * 0.5; + max_interp_size = interp_size; + } + + auto new_shape = std::vector(ndims, 1); + new_shape[reshape_dim] = output_size; + + // Bounds approach as in PIL: xmin/xmax + output.emplace_back( + empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType()))); + output.emplace_back( + empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType()))); + output.emplace_back( + empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType()))); + + { + // Weights + new_shape[reshape_dim] = output_size * max_interp_size; + auto wts = empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType())); + auto strides = wts.strides().vec(); + strides[reshape_dim] = 0; + new_shape[reshape_dim] = output_size; + wts = wts.as_strided(new_shape, strides); + output.emplace_back(wts); + // Weights indices + output.emplace_back( + empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType()))); + } + + int64_t* idx_ptr_xmin = output[0].data_ptr(); + int64_t* idx_ptr_size = output[1].data_ptr(); + int64_t* idx_ptr_stride = output[2].data_ptr(); + scalar_t* wt_ptr = output[3].data_ptr(); + int64_t* wt_idx_ptr = output[4].data_ptr(); + + scalar_t wt_max = 0.0; + for (const auto i : c10::irange(output_size)) { + int64_t xmin = 0, xsize = 0; + scalar_t wt_max_i; + if (antialias) { + wt_max_i = HelperInterpBase::_compute_indices_min_size_weights_aa( + i, + input_size, + scale, + support, + wt_ptr + i * max_interp_size, + max_interp_size, + aa_filter_fn, + xmin, + xsize); + } else { + wt_max_i = HelperInterpBase::_compute_indices_min_size_weights( + i, + input_size, + scale, + wt_ptr + i * max_interp_size, + max_interp_size, + aa_filter_fn, + align_corners, + xmin, + xsize); + } + wt_max = std::max(wt_max, wt_max_i); + + idx_ptr_xmin[i] = xmin * stride; + idx_ptr_size[i] = xsize; + idx_ptr_stride[i] = stride; + wt_idx_ptr[i] = i * max_interp_size * weight_index_stride; + } + return {std::move(output), max_interp_size, wt_max}; + } + + /* + NOTE [ Weights computation for uint8_t and multiplication trick ] + When the input/output dtype is uint8_t, we still compute the interpolation + weights as double, but then convert them to int16 via some conversion logic + detailed below. This allows us to compute all interpolation operation (sum of + multiplications) as ints instead of floats. The result is converted back into + uint8 in basic_loop_separable_1d_horizontal (and vertical) + + In essence the idea is to avoid a multiplication between a float (the + weight) and an int (the pixel value) and instead run a multiplication between + 2 ints: + + ```py + COEF_PREC = 16 + + def mul(a:float, b:int) -> Tuple[float, int]: + # return a * b, round(a * b) + actual = a * b + + assert a > 0 # I'm lazy + int_a = floor(0.5 + a * (1 << COEF_PREC)) + with_trick = ((int_a * b) + (1 << (COEF_PREC - 1))) >> COEF_PREC + + return actual, with_trick # round(actual) == with_trick!! + ``` + + Here's how it works: + N == COEFF_PREC + 1 << N == 2**N + floor(0.5 + x) == round(x) + + So the operation is something like + + int_a = round(a * 2**N) -- let's just say it's `a * 2**N` for simplicity + + res = ((int_a * b) + (1 << (N - 1))) >> N + = ((a * 2**N * b + 2**(N - 1)) / 2**N + = a * b + 0.5 + = round(a * b) + = what we wanted + */ + template + static inline std::tuple, int, unsigned int> _compute_index_ranges_int16_weights( + int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims, + int64_t reshape_dim, bool align_corners, const std::optional& opt_scale, + int interp_size, aa_filter_fn_t aa_filter_fn, bool antialias, bool align_i32=false + ) { + + double scale = area_pixel_compute_scale( + input_size, output_size, align_corners, opt_scale); + + auto [indices_weights, aligned_interp_size, wt_max] = HelperInterpBase::_compute_index_ranges_weights( + input_size, output_size, stride, ndims, reshape_dim, scale, interp_size, aa_filter_fn, antialias, align_corners); + interp_size = aligned_interp_size; + + // Rescale float weights to int16 and compute weights precision + auto weights_f64 = indices_weights[3]; + double * data_f64 = weights_f64. template data_ptr(); + + unsigned int weights_precision = 0; + for (weights_precision = 0; weights_precision < 22; ++weights_precision) { + int next_value = (int) (0.5 + wt_max * (1 << (weights_precision + 1))); + if (next_value >= (1 << 15)) + break; + } + + // Rescale float values to int16 + int16_t * data_i16 = (int16_t *) data_f64; + + if (align_i32) { + // We should respect int32 alignment as we will load int16 data as int32 + // See ImagingResampleHorizontalConvolution8u4x, mmk0 = _mm256_set1_epi32(*(int32_t*)&k[x]); + // compute aligned_interp_size = nearest pair value to interp_size + while (aligned_interp_size % sizeof(int32_t) != 0) { + aligned_interp_size += 1; + } + // assert that we won't go out of bounds + TORCH_INTERNAL_ASSERT(aligned_interp_size * sizeof(int16_t) < interp_size * sizeof(double)); + } + + for (const auto j : c10::irange(output_size)) { + for (const auto k : c10::irange(interp_size)) { + double v = data_f64[j * interp_size + k] * (1 << weights_precision); + data_i16[j * aligned_interp_size + k] = (v < 0) ? (int) (-0.5 + v) : (int) (0.5 + v); + } + } + + return {std::move(indices_weights), aligned_interp_size, weights_precision}; + } +}; + +struct HelperInterpNearest : public HelperInterpBase { + // This structure implements outdated and buggy method to compute indices + // for nearest neighbours interpolation + // We keep this structure for BC and consider as deprecated. + // See HelperInterpNearestExact as replacement + + static constexpr int interp_size = 1; + + static inline void init_indices_weights( + at::ScalarType output_type, + std::vector & output, int64_t output_size, int64_t ndims, + int64_t reshape_dim, int interp_size + ) { + auto new_shape = std::vector(ndims, 1); + new_shape[reshape_dim] = output_size; + + for ([[maybe_unused]] const auto j : c10::irange(interp_size)) { + output.emplace_back( + empty(new_shape, at::device(kCPU).dtype(c10::CppTypeToScalarType()))); + // Defines weights for consistency, but not used + output.emplace_back(at::ones(new_shape, at::device(kCPU).dtype(output_type))); + } + } + + // Compute nearest mode indices and weights for each interpolated dimension + // indices_weights = { + // {indices_0, 1.0, }, // dim -n + // {indices_0, 1.0, }, // dim -(n-1) + // ... + // {indices_0, 1.0, }, // dim -1 + // } + // Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to + // fit input/output tensors. + // Indices are already containing the strides to optimize the computations + static inline std::vector compute_indices_weights( + at::ScalarType scalar_type, + int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims, + int64_t reshape_dim, bool align_corners, const std::optional& opt_scale + ) { + + TORCH_INTERNAL_ASSERT(!align_corners); + std::vector output; + HelperInterpNearest::init_indices_weights( + scalar_type, output, output_size, ndims, reshape_dim, HelperInterpNearest::interp_size); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, scalar_type, "compute_indices_weights_nearest", [&] { + using opmath_t = at::opmath_type; + opmath_t scale = area_pixel_compute_scale(input_size, output_size, align_corners, opt_scale); + + auto input_index_ptr = output[0].data_ptr(); + int64_t input_index; + + // Indices are computed as following: + // scale = 1.0 * isize / osize + // index_f32 = (output_index) * scale + // input_index = floor(index_f32) + // Same as OpenCV INTER_NEAREST + for (const auto i : c10::irange(output_size)) { + const auto real_input_index = + area_pixel_compute_source_index( + scale, i, /*align_corners=*/true, /*cubic=*/false); + input_index = static_cast(floorf(real_input_index)); + input_index_ptr[i] = static_cast(std::min(input_index, input_size - 1)) * stride; + } + } + ); + return output; + } + +}; + +struct HelperInterpNearestExact : public HelperInterpNearest { + + // Compute nearest mode indices and weights for each interpolated dimension + // indices_weights = { + // {indices_0, 1.0, }, // dim -n + // {indices_0, 1.0, }, // dim -(n-1) + // ... + // {indices_0, 1.0, }, // dim -1 + // } + // Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to + // fit input/output tensors. + // Indices are already containing the strides to optimize the computations + static inline std::vector compute_indices_weights( + at::ScalarType scalar_type, + int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims, + int64_t reshape_dim, bool align_corners, const std::optional& opt_scale + ) { + + TORCH_INTERNAL_ASSERT(!align_corners); + std::vector output; + HelperInterpNearest::init_indices_weights( + scalar_type, output, output_size, ndims, reshape_dim, HelperInterpNearest::interp_size); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, scalar_type, "compute_indices_weights_nearest", [&] { + using opmath_t = at::opmath_type; + opmath_t scale = area_pixel_compute_scale(input_size, output_size, align_corners, opt_scale); + + auto input_index_ptr = output[0].data_ptr(); + int64_t input_index; + + // Indices should be computed as following: + // scale = 1.0 * isize / osize + // index_f32 = (output_index + 0.5) * scale - 0.5 + // input_index = round(index_f32) + // Same as Pillow and Scikit-Image/Scipy ndi.zoom + for (const auto i : c10::irange(output_size)) { + const auto real_input_index = + area_pixel_compute_source_index( + scale, i, /*align_corners=*/align_corners, /*cubic=*/false); + input_index = static_cast(floorf(real_input_index + 0.5)); + input_index_ptr[i] = static_cast(std::min(input_index, input_size - 1)) * stride; + } + } + ); + return output; + } +}; + +struct HelperInterpLinear : public HelperInterpBase { + + static constexpr int interp_size = 2; + + // Compute indices and weights for each interpolated dimension + // indices_weights = { + // {indices_0, weights_0, indices_1, weights_1}, // dim -n + // {indices_0, weights_0, indices_1, weights_1}, // dim -(n-1) + // ... + // {indices_0, weights_0, indices_1, weights_1}, // dim -1 + // } + // Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to + // fit input/output tensors. + // Indices are already containing the strides to optimize the computations + static inline std::vector compute_indices_weights( + at::ScalarType scalar_type, + int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims, int64_t reshape_dim, + bool align_corners, const std::optional& opt_scale + ) { + std::vector output; + HelperInterpLinear::init_indices_weights( + scalar_type, output, output_size, ndims, reshape_dim, HelperInterpLinear::interp_size); + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, scalar_type, "compute_indices_weights_linear", [&] { + using opmath_t = at::opmath_type; + opmath_t scale = area_pixel_compute_scale(input_size, output_size, align_corners, opt_scale); + + auto input_index0_ptr = output[0].data_ptr(); + auto lambda0_ptr = output[1].data_ptr(); + auto input_index1_ptr = output[2].data_ptr(); + auto lambda1_ptr = output[3].data_ptr(); + + for (const auto i : c10::irange(output_size)) { + + compute_source_index_and_lambda( + input_index0_ptr[i], input_index1_ptr[i], + lambda0_ptr[i], lambda1_ptr[i], + scale, i, input_size, output_size, align_corners + ); + // put stride into indices + // index values correspond to input indices (0, 1, 2, 3, ...) + // when multiplied by input stride, maximum possible value + // input_size[dim-1] * input_size[dim-2] * ... for the given dimension. + input_index0_ptr[i] *= stride; + input_index1_ptr[i] *= stride; + } + } + ); + return output; + } + + // taken from + // https://github.com/python-pillow/Pillow/blob/6812205f18ca4ef54372e87e1a13ce4a859434df/ + // src/libImaging/Resample.c#L20-L29 + template + static inline scalar_t aa_filter(scalar_t x) { + x = std::abs(x); + if (x < 1.0) { + return 1.0 - x; + } + return 0.0; + } + + static inline std::vector compute_index_ranges_weights( + at::ScalarType scalar_type, + int64_t input_size, + int64_t output_size, + int64_t stride, + int64_t ndims, + int64_t reshape_dim, + bool align_corners, + const std::optional& opt_scale, + bool antialias + ) { + + std::vector indices_weights; + AT_DISPATCH_FLOATING_TYPES( + scalar_type, "compute_index_ranges_weights", [&] { + + scalar_t scale = area_pixel_compute_scale( + input_size, output_size, align_corners, opt_scale); + + auto interp_size = HelperInterpLinear::interp_size; + + indices_weights = std::get<0>(HelperInterpLinear::_compute_index_ranges_weights( + input_size, + output_size, + stride, + ndims, + reshape_dim, + scale, + interp_size, + &HelperInterpLinear::aa_filter, + /*antialias=*/antialias, + /*align_corners=*/align_corners)); + } + ); + return indices_weights; + } + + static inline std::tuple, int, unsigned int> compute_index_ranges_int16_weights( + int64_t input_size, + int64_t output_size, + int64_t stride, + int64_t ndims, + int64_t reshape_dim, + bool align_corners, + const std::optional& opt_scale, + bool antialias, + bool align_i32=false + ) { + + auto interp_size = HelperInterpLinear::interp_size; + auto fn = HelperInterpLinear::aa_filter; + return HelperInterpLinear::_compute_index_ranges_int16_weights( + input_size, output_size, stride, ndims, reshape_dim, + align_corners, opt_scale, interp_size, fn, antialias, align_i32); + } +}; + +struct HelperInterpCubic : public HelperInterpBase { + + static constexpr int interp_size = 4; + + // Compute indices and weights for each interpolated dimension + // indices_weights = { + // {indices_0, weights_0, indices_1, weights_1, ..., indices_3, weights_3}, // dim -n + // {indices_0, weights_0, indices_1, weights_1, ..., indices_3, weights_3}, // dim -(n-1) + // ... + // {indices_0, weights_0, indices_1, weights_1, ..., indices_3, weights_3}, // dim -1 + // } + // Indices and weights are reshaped as (1, 1, ..., N, ..., 1, 1) to + // fit input/output tensors. + // Indices are already containing the strides to optimize the computations + static inline std::vector compute_indices_weights( + at::ScalarType scalar_type, + int64_t input_size, int64_t output_size, int64_t stride, int64_t ndims, int64_t reshape_dim, + bool align_corners, const std::optional& opt_scale + ) { + std::vector output; + HelperInterpCubic::init_indices_weights( + scalar_type, output, output_size, ndims, reshape_dim, HelperInterpCubic::interp_size); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, scalar_type, "compute_indices_weights_cubic", [&] { + using opmath_t = at::opmath_type; + opmath_t scale = area_pixel_compute_scale(input_size, output_size, align_corners, opt_scale); + + int64_t input_index; + int64_t zero = static_cast(0); + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) + opmath_t coeffs[4]; + + int64_t * idx_ptr; + scalar_t * wt_ptr; + for (const auto i : c10::irange(output_size)) { + const auto real_input_index = + area_pixel_compute_source_index( + scale, i, align_corners, /*cubic=*/true); + opmath_t lambda; + guard_index_and_lambda(real_input_index, input_size, input_index, lambda); + get_cubic_upsample_coefficients(coeffs, lambda); + + for (const auto j : c10::irange(interp_size)) { + idx_ptr = output[2 * j + 0].data_ptr(); + idx_ptr[i] = static_cast(std::max(std::min(input_index + j - 1, input_size - 1), zero)) * stride; + wt_ptr = output[2 * j + 1].data_ptr(); + wt_ptr[i] = coeffs[j]; + } + } + } + ); + return output; + } + + // taken from + // https://github.com/python-pillow/Pillow/blob/6812205f18ca4ef54372e87e1a13ce4a859434df/ + // src/libImaging/Resample.c#L46-L62 + template + static inline scalar_t aa_filter(scalar_t x) { + // https://en.wikipedia.org/wiki/Bicubic_interpolation#Bicubic_convolution_algorithm + // a = -0.5 was proposed by R. Keys in "Cubic convolution interpolation for digital image processing" + // We are using -0.5 for bicubic, antialiasing=true (compatibility with PIL) + // and using -0.75 for bicubic, antialiasing=false (compatibility with Opencv) + constexpr scalar_t a = use_keys_cubic ? -0.5 : -0.75; + + x = std::abs(x); + if (x < 1.0) { + return cubic_convolution1(x, a); + } + if (x < 2.0) { + return cubic_convolution2(x, a); + } + return 0.0; + } + + static inline std::vector compute_index_ranges_weights( + at::ScalarType scalar_type, + int64_t input_size, + int64_t output_size, + int64_t stride, + int64_t ndims, + int64_t reshape_dim, + bool align_corners, + const std::optional& opt_scale, + bool antialias + ) { + + std::vector indices_weights; + AT_DISPATCH_FLOATING_TYPES( + scalar_type, "compute_index_ranges_weights", [&] { + + scalar_t scale = area_pixel_compute_scale( + input_size, output_size, align_corners, opt_scale); + + auto interp_size = HelperInterpCubic::interp_size; + + indices_weights = std::get<0>(HelperInterpCubic::_compute_index_ranges_weights( + input_size, + output_size, + stride, + ndims, + reshape_dim, + scale, + interp_size, + &HelperInterpCubic::aa_filter, + /*antialias=*/antialias, + /*align_corners=*/align_corners)); + } + ); + return indices_weights; + } + + static inline std::tuple, int, unsigned int> compute_index_ranges_int16_weights( + int64_t input_size, + int64_t output_size, + int64_t stride, + int64_t ndims, + int64_t reshape_dim, + bool align_corners, + const std::optional& opt_scale, + bool antialias, + bool align_i32=false + ) { + + auto interp_size = HelperInterpCubic::interp_size; + // We have to use the -0.75 constant when aa is False so that this uint8 + // path is as close as possible to float results. + auto fn = antialias ? HelperInterpCubic::aa_filter : HelperInterpCubic::aa_filter; + return HelperInterpCubic::_compute_index_ranges_int16_weights( + input_size, output_size, stride, ndims, reshape_dim, + align_corners, opt_scale, interp_size, fn, antialias, align_i32); + } + +}; + +struct HelperInterpLanczos : public HelperInterpBase { + + static constexpr int interp_size = 6; + + // Taken from + // https://github.com/python-pillow/Pillow/blob/8004234d879254cc354935ad42fbb51b1700925e/src/libImaging/Resample.c#L64-L86 + template + static inline scalar_t sinc_filter(scalar_t x) { + if (x == 0.0) { + return 1.0; + } + x *= c10::pi; + return std::sin(x) / x; + } + + template + static inline scalar_t aa_filter(scalar_t x) { + // Lanczos-3 filter: sinc(x) * sinc(x/3) for |x| < 3 + x = std::abs(x); + if (x < 3.0) { + return sinc_filter(x) * sinc_filter(x / 3.0); + } + return 0.0; + } + + static inline std::vector compute_index_ranges_weights( + at::ScalarType scalar_type, + int64_t input_size, + int64_t output_size, + int64_t stride, + int64_t ndims, + int64_t reshape_dim, + bool align_corners, + const std::optional& opt_scale, + bool antialias + ) { + + std::vector indices_weights; + AT_DISPATCH_FLOATING_TYPES( + scalar_type, "compute_index_ranges_weights", [&] { + + scalar_t scale = area_pixel_compute_scale( + input_size, output_size, align_corners, opt_scale); + + auto interp_size = HelperInterpLanczos::interp_size; + + indices_weights = std::get<0>(HelperInterpLanczos::_compute_index_ranges_weights( + input_size, + output_size, + stride, + ndims, + reshape_dim, + scale, + interp_size, + &HelperInterpLanczos::aa_filter, + /*antialias=*/antialias, + /*align_corners=*/align_corners)); + } + ); + return indices_weights; + } + + static inline std::tuple, int, unsigned int> compute_index_ranges_int16_weights( + int64_t input_size, + int64_t output_size, + int64_t stride, + int64_t ndims, + int64_t reshape_dim, + bool align_corners, + const std::optional& opt_scale, + bool antialias, + bool align_i32=false + ) { + + auto interp_size = HelperInterpLanczos::interp_size; + auto fn = HelperInterpLanczos::aa_filter; + return HelperInterpLanczos::_compute_index_ranges_int16_weights( + input_size, output_size, stride, ndims, reshape_dim, + align_corners, opt_scale, interp_size, fn, antialias, align_i32); + } + +}; + +// Generic upsampling interpolation kernel for N-d case. +// Input is assumed to be like NCHW, NCL, NCKHW - interpolated spatial dimension +// are those from the end up to batch size N and number of channels C. +// +// Internally, it uses TensorIterator to optimize the computations. +// - out_ndims is the number of interpolated dims: 1, 2, 3 +// - scale_type is template type for scales, typically std::optional +// - template class F is one of the above structs to compute indices and weights +template +void upsample_non_separable_Nd_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + const scale_type& scales) { + + + // input can be NCHW, NCL or NCKHW + auto shape = input.sizes().vec(); + auto strides = input.strides().vec(); + auto oshape = output.sizes(); + + TORCH_INTERNAL_ASSERT( + shape.size() == oshape.size() && shape.size() == 2 + out_ndims + ); + TORCH_INTERNAL_ASSERT(strides.size() == 2 + out_ndims); + + for (const auto i : c10::irange(out_ndims)) { + shape[i + 2] = oshape[i + 2]; + strides[i + 2] = 0; + } + auto restrided_input = input.as_strided(shape, strides); + + + constexpr int interp_size = F::interp_size; + auto input_scalar_type = input.scalar_type(); + if ((interp_size == 1 && input_scalar_type == at::ScalarType::Byte)) { + // nearest also supports uint8 tensor, but we have to use float + // with compute_indices_weights + input_scalar_type = at::ScalarType::Float; + } + + std::vector> indices_weights; + indices_weights.reserve(out_ndims); + for (const auto i : c10::irange(out_ndims)) { + indices_weights.emplace_back( + F::compute_indices_weights( + input_scalar_type, input.size(i + 2), oshape[i + 2], + input.stride(i + 2) * input.element_size(), + input.dim(), i + 2, align_corners, scales[i] + ) + ); + } + + TensorIteratorConfig config; + config.check_all_same_dtype(false) + .declare_static_dtype_and_device(input.scalar_type(), input.device()) + .add_output(output) + .add_const_input(restrided_input); + + for (auto & idx_weight: indices_weights) { + for (auto& tensor : idx_weight) { + config.add_const_input(tensor); + } + } + + auto iter = config.build(); + + if (interp_size > 1) { + // Nearest also supports uint8 tensor, so need to handle it separately + // Dispatch name should be "upsample_non_separable" but we keep the old + // name for internal BC. + AT_DISPATCH_FLOATING_TYPES_AND2( + kBFloat16, kHalf, iter.dtype(), "upsample_generic_Nd", [&] { + // MSVC can not catch constexpr int interp_size here + constexpr int mode = F::interp_size; + upsample_non_separable(iter); + }); + } else { + // Dispatch name should be "upsample_non_separable" but we keep the old + // name for internal BC. + AT_DISPATCH_FLOATING_TYPES_AND3(kByte, kBFloat16, kHalf, + iter.dtype(), "upsample_generic_Nd", [&] { + constexpr int mode = F::interp_size; + upsample_non_separable(iter); + }); + } +} + +template +void upsample_separable_1d( + const Tensor& output, + const Tensor& input, + int interp_dim, + bool align_corners, + const scale_type& scales, + bool antialias) { + + // input can be NCHW, NCL or NCKHW + auto shape = input.sizes().vec(); + auto strides = input.strides().vec(); + auto oshape = output.sizes(); + + TORCH_INTERNAL_ASSERT( + shape.size() == oshape.size() && shape.size() == 2 + out_ndims); + TORCH_INTERNAL_ASSERT(strides.size() == 2 + out_ndims); + + for (const auto i : c10::irange(out_ndims)) { + shape[i + 2] = oshape[i + 2]; + } + strides[interp_dim] = 0; + auto restrided_input = input.as_strided(shape, strides); + + auto input_scalar_type = input.scalar_type(); + + std::vector indices_weights; + unsigned int weights_precision = 0; + + if (input_scalar_type == at::kByte) { + // This is a special branch to provide uint8 dtype support for bilinear, bicubic and lanczos modes only + TORCH_INTERNAL_ASSERT(F::interp_size == 2 || F::interp_size == 4 || F::interp_size == 6); + int unused = 0; + std::tie(indices_weights, unused, weights_precision) = + F::compute_index_ranges_int16_weights( + input.size(interp_dim), oshape[interp_dim], + input.stride(interp_dim) * input.element_size(), + input.dim(), interp_dim, align_corners, scales[interp_dim - 2], + antialias); + TORCH_INTERNAL_ASSERT(weights_precision > 0); + } else { + indices_weights = + F::compute_index_ranges_weights( + input_scalar_type, input.size(interp_dim), oshape[interp_dim], + input.stride(interp_dim) * input.element_size(), + input.dim(), interp_dim, align_corners, scales[interp_dim - 2], + antialias); + } + + TensorIteratorConfig config; + config.check_all_same_dtype(false) + .declare_static_dtype_and_device(input.scalar_type(), input.device()) + .add_output(output) + .add_const_input(restrided_input); + + for (auto& tensor : indices_weights) { + config.add_const_input(tensor); + } + + auto iter = config.build(); + + // Dispatch name should be "upsample_separable_1d" but we keep the old + // name for internal BC. + AT_DISPATCH_FLOATING_TYPES_AND( + at::ScalarType::Byte, iter.dtype(), "upsample_generic_Nd_aa", [&] { + auto loop = [&](char** data, const int64_t* strides, int64_t n) { + if constexpr (is_horizontal) { + // Strides are : X 0 | 8 8 8 0 8 (Channels first) + // Strides are : X X | 0 0 0 0 0 (Channels last) + basic_loop_separable_1d_horizontal(data, strides, n, weights_precision); + } else { + // Strides are : X Y | 0 0 0 0 0 (Channels first) + // Strides are : X X | 0 0 0 0 0 (Channels last) + basic_loop_separable_1d_vertical(data, strides, n, weights_precision); + } + }; + iter.for_each(loop); + }); +} + +// Generic separable upsampling interpolation kernel for N-d case with anti-aliasing. +// It also supports antialias=False iff +// (dtype == uint8 and mode in ("bilinear", "bicubic")): this is used as +// fallback in these settings when AVX isn't supported. +template +void upsample_separable_Nd_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + const scale_type& scales, + bool antialias) { + + auto output_shape = output.sizes(); + auto input_shape = input.sizes(); + auto temp_oshape = input_shape.vec(); + + if (output_shape == input_shape) { + output.copy_(input); + return; + } + + at::Tensor temp_output, temp_input = input; + + int interp_dim = 0; + // Precompute the number of 1d resize ops + // to avoid copying temporary buffer to output + int num_1d_ops = 0; + for (const auto i : c10::irange(out_ndims)) { + interp_dim = 2 + out_ndims - 1 - i; + if (output_shape[interp_dim] != input_shape[interp_dim]) { + num_1d_ops += 1; + } + } + + // Horizontal resampling (last spatial dim, i.e. W) + interp_dim = 2 + out_ndims - 1; + if (output_shape[interp_dim] != input_shape[interp_dim]) { + + num_1d_ops -= 1; + if (num_1d_ops > 0) { + temp_oshape[interp_dim] = output_shape[interp_dim]; + temp_output = at::empty(temp_oshape, input.options()); + } else { + temp_output = output; + } + + upsample_separable_1d< + out_ndims, + scale_t, + F, + true>( + temp_output, temp_input, interp_dim, align_corners, scales, antialias); + temp_input = temp_output; + } + + // Vertical resampling (remaining spatial dims, e.g. H, D) + for (const auto i : c10::irange(1, out_ndims)) { + interp_dim = 2 + out_ndims - 1 - i; + if (output_shape[interp_dim] != input_shape[interp_dim]) { + + num_1d_ops -= 1; + if (num_1d_ops > 0) { + temp_oshape[interp_dim] = output_shape[interp_dim]; + temp_output = at::empty(temp_oshape, input.options()); + } else { + temp_output = output; + } + + upsample_separable_1d< + out_ndims, + scale_t, + F, + false>( + temp_output, temp_input, interp_dim, align_corners, scales, antialias); + temp_input = temp_output; + } + } +} + +void upsample_nearest1d_kernel_impl( + const Tensor& output, + const Tensor& input, + std::optional scales_w) { + upsample_non_separable_Nd_kernel_impl<1, scale_t, HelperInterpNearest>( + output, input, false, {scales_w}); +} + +void _upsample_nearest_exact1d_kernel_impl( + const Tensor& output, + const Tensor& input, + std::optional scales_w) { + upsample_non_separable_Nd_kernel_impl<1, scale_t, HelperInterpNearestExact>( + output, input, false, {scales_w}); +} + +int _use_channels_last_kernel_2d( + const Tensor& output, + const Tensor& input) { + // This condition is used to know whether we should dispatch to a + // channels-last-optimized kernel, or to the more general + // upsample_non_separable_Nd_kernel_impl(). For now, the channels-last kernels + // are only optimized for channels_last and when C >= 4 (shape = NCHW). + // For a very wide range of use-cases (typically image or mask resizing + // where we have C < 4), using upsample_non_separable_Nd_kernel_impl() is + // actually faster. On top of that, benchmarks showed that this also + // depends on the *output* size (output_H + output_W), for both + // upsampling and downsampling. The current 128 threshold was determined + // through benchmarks. + return ((input.is_contiguous(at::MemoryFormat::ChannelsLast)) && (input.size(1) > 3)) || ((output.size(-2) + output.size(-1)) <= 128); +} + +int _use_channels_last_kernel_3d( + // Similar to _use_channels_last_kernel_2d() but for 3d resampling (e.g. videos) + // Note that unlike the 2d case, this is not subject to small output size + // overhead - hence the absence of the 128 threshold in the condition. + const Tensor& output, + const Tensor& input) { + return ((input.is_contiguous(at::MemoryFormat::ChannelsLast3d)) && (input.size(1) > 3)); +} + + +void upsample_nearest2d_kernel_impl( + const Tensor& output, + const Tensor& input, + std::optional scales_h, + std::optional scales_w) { + if (_use_channels_last_kernel_2d(output, input)) { + AT_DISPATCH_FLOATING_TYPES_AND3(kByte, kBFloat16, kHalf, + input.scalar_type(), "upsample_nearest2d_channels_last", [&] { + upsample_nearest_channels_last(output, input, {scales_h, scales_w}); + }); + } else { + upsample_non_separable_Nd_kernel_impl<2, scale_t, HelperInterpNearest>( + output, input, false, {scales_h, scales_w}); + } +} + +void _upsample_nearest_exact2d_kernel_impl( + const Tensor& output, + const Tensor& input, + std::optional scales_h, + std::optional scales_w) { + if (_use_channels_last_kernel_2d(output, input)) { + AT_DISPATCH_FLOATING_TYPES_AND3(kByte, kBFloat16, kHalf, input.scalar_type(), "upsample_nearest2d_channels_last", [&] { + upsample_nearest_channels_last(output, input, {scales_h, scales_w}); + }); + } else { + upsample_non_separable_Nd_kernel_impl<2, scale_t, HelperInterpNearestExact>( + output, input, false, {scales_h, scales_w}); + } +} + +void upsample_nearest3d_kernel_impl( + const Tensor& output, + const Tensor& input, + std::optional scales_d, + std::optional scales_h, + std::optional scales_w) { + if (_use_channels_last_kernel_3d(output, input)) { + AT_DISPATCH_FLOATING_TYPES_AND3(kByte, kBFloat16, kHalf, + input.scalar_type(), "upsample_nearest3d_channels_last", [&] { + upsample_nearest_channels_last(output, input, {scales_d, scales_h, scales_w}); + }); + } else { + upsample_non_separable_Nd_kernel_impl<3, scale_t, HelperInterpNearest>( + output, input, false, {scales_d, scales_h, scales_w}); + } +} + +void _upsample_nearest_exact3d_kernel_impl( + const Tensor& output, + const Tensor& input, + std::optional scales_d, + std::optional scales_h, + std::optional scales_w) { + if (_use_channels_last_kernel_3d(output, input)) { + AT_DISPATCH_FLOATING_TYPES_AND3(kByte, kBFloat16, kHalf, input.scalar_type(), "upsample_nearest3d_channels_last", [&] { + upsample_nearest_channels_last(output, input, {scales_d, scales_h, scales_w}); + }); + } else { + upsample_non_separable_Nd_kernel_impl<3, scale_t, HelperInterpNearestExact>( + output, input, false, {scales_d, scales_h, scales_w}); + } +} + +void upsample_linear1d_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_w) { + upsample_non_separable_Nd_kernel_impl<1, scale_t, HelperInterpLinear>( + output, input, align_corners, {scales_w}); +} + + +void upsample_bilinear2d_kernel_impl_float( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + + // See note above about _use_channels_last_kernel_2d(output, input). The extra cond is present + // because benchmarks showed that with only 1 thread, images (C == 3) were + // slightly faster with the channels-last kernel than with the generic one. + // That's not the case for masks though (C == 1), which strongly benefit from + // using the generic kernel. + if ((_use_channels_last_kernel_2d(output, input)) || (at::get_num_threads() == 1 && input.size(1) == 3)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "upsample_bilinear2d_channels_last", [&] { + upsample_linear_channels_last(output, input, align_corners, {scales_h, scales_w}); + }); + } else { + upsample_non_separable_Nd_kernel_impl<2, scale_t, HelperInterpLinear>( + output, input, align_corners, {scales_h, scales_w}); + } +} + +void upsample_bilinear2d_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + + if (input.dtype() == at::kByte) { + #ifdef CPU_CAPABILITY_AVX2 + if (input.size(1) <= 4) { + return upsample_avx_bilinear_bicubic_uint8(input, + output, align_corners, {scales_h, scales_w}, + /*antialias=*/false); + } + #elif defined(__aarch64__) + if (input.size(1) == 3 + && input.is_contiguous(at::MemoryFormat::ChannelsLast) + && output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + return upsample_neon_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/false); + } + #endif // CPU_CAPABILITY_AVX2 + return upsample_separable_Nd_kernel_impl<2, scale_t, HelperInterpLinear>( + output, input, align_corners, {scales_h, scales_w}, + /*antialias=*/false); + } + return upsample_bilinear2d_kernel_impl_float(output, input, align_corners, scales_h, scales_w); +} + + +void upsample_bilinear2d_aa_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + if (input.dtype() == at::kByte) { + #ifdef CPU_CAPABILITY_AVX2 + if (input.size(1) <= 4) { + return upsample_avx_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/true); + } + #elif defined(__aarch64__) + if (input.size(1) == 3 + && input.is_contiguous(at::MemoryFormat::ChannelsLast) + && output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + return upsample_neon_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/true); + } + #endif // CPU_CAPABILITY_AVX2 + } + return upsample_separable_Nd_kernel_impl<2, scale_t, HelperInterpLinear>( + output, input, align_corners, {scales_h, scales_w}, + /*antialias=*/true); +} + +void upsample_trilinear3d_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_d, + std::optional scales_h, + std::optional scales_w) { + if ((_use_channels_last_kernel_3d(output, input))) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, input.scalar_type(), "upsample_trilinear3d_channels_last", [&] { + upsample_linear_channels_last(output, input, align_corners, {scales_d, scales_h, scales_w}); + }); + } else { + upsample_non_separable_Nd_kernel_impl<3, scale_t, HelperInterpLinear>( + output, input, align_corners, {scales_d, scales_h, scales_w}); + } +} + +void upsample_bicubic2d_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + + if (input.dtype() == at::kByte) { + #ifdef CPU_CAPABILITY_AVX2 + if (input.size(1) <= 4) { + return upsample_avx_bilinear_bicubic_uint8(input, + output, align_corners, {scales_h, scales_w}, + /*antialias=*/false); + } + #elif defined(__aarch64__) + if (input.size(1) == 3 + && input.is_contiguous(at::MemoryFormat::ChannelsLast) + && output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + return upsample_neon_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/false); + } + #endif // CPU_CAPABILITY_AVX2 + return upsample_separable_Nd_kernel_impl<2, scale_t, HelperInterpCubic>( + output, input, align_corners, {scales_h, scales_w}, + /*antialias=*/false); + } + return upsample_non_separable_Nd_kernel_impl<2, scale_t, HelperInterpCubic>( + output, input, align_corners, {scales_h, scales_w}); +} + +void upsample_bicubic2d_aa_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + + if (input.dtype() == at::kByte) { + #ifdef CPU_CAPABILITY_AVX2 + if (input.size(1) <= 4) { + return upsample_avx_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/true); + } + #elif defined(__aarch64__) + if (input.size(1) == 3 + && input.is_contiguous(at::MemoryFormat::ChannelsLast) + && output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + return upsample_neon_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/true); + } + #endif // CPU_CAPABILITY_AVX2 + } + return upsample_separable_Nd_kernel_impl<2, scale_t, HelperInterpCubic>( + output, input, align_corners, {scales_h, scales_w}, + /*antialias=*/true); +} + +void upsample_lanczos2d_aa_kernel_impl( + const Tensor& output, + const Tensor& input, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + + if (input.dtype() == at::kByte) { + #ifdef CPU_CAPABILITY_AVX2 + if (input.size(1) <= 4) { + return upsample_avx_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/true); + } + #elif defined(__aarch64__) + if (input.size(1) == 3 + && input.is_contiguous(at::MemoryFormat::ChannelsLast) + && output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + return upsample_neon_bilinear_bicubic_uint8( + input, output, align_corners, {scales_h, scales_w}, + /*antialias=*/true); + } + #endif // CPU_CAPABILITY_AVX2 + } + return upsample_separable_Nd_kernel_impl<2, scale_t, HelperInterpLanczos>( + output, input, align_corners, {scales_h, scales_w}, + /*antialias=*/true); +} + +template < + typename scalar_t, + typename scale_type, + class F> +void upsample_separable_Nd_backward_aa( + const Tensor& grad_input_, + const Tensor& grad_output_, + bool align_corners, + const scale_type& scales) { + TORCH_CHECK(grad_input_.dtype() == grad_output_.dtype(), "expected dtype ", grad_output_.dtype(), + " for `grad_input` but got dtype ", grad_input_.dtype()); + + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + auto input_sizes = grad_input.sizes().vec(); + auto output_sizes = grad_output.sizes().vec(); + auto ndim = input_sizes.size(); + + // treat nbatch and channels as one dimension + int64_t channels = input_sizes[0] * input_sizes[1]; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = (ndim >= 4) ? input_sizes[ndim - 2] : 1; + int64_t output_height = (ndim >= 4) ? output_sizes[ndim - 2] : 1; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + + int64_t output_slice_size = output_depth * output_height * output_width; + int interp_size = F::interp_size; + + auto loop2d = [&](int64_t begin, int64_t end) { + const scalar_t height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[0]); + const scalar_t width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[1]); + + auto input_indexr = [=](int64_t c, int64_t h, int64_t w) { + return grad_input_data + c * input_height * input_width + + h * input_width + w; + }; + + const scalar_t support_h = (height_scale >= 1.0) + ? (interp_size * 0.5) * height_scale + : interp_size * 0.5; + const scalar_t support_w = (width_scale >= 1.0) + ? (interp_size * 0.5) * width_scale + : interp_size * 0.5; + + const int interp_height = (int)ceilf(support_h) * 2 + 1; + const int interp_width = (int)ceilf(support_w) * 2 + 1; + + std::vector wx(interp_width, 0.0); + std::vector wy(interp_height, 0.0); + + int64_t xmin = 0, ymin = 0; + int64_t xsize = 0, ysize = 0; + + typedef scalar_t (*aa_filter_fn_t)(scalar_t); + aa_filter_fn_t filter_fn = &F::aa_filter; + + for (const auto oh : c10::irange(output_height)) { + F::_compute_indices_min_size_weights_aa( + oh, + input_height, + height_scale, + support_h, + wy.data(), + interp_height, + filter_fn, + ymin, + ysize); + + for (const auto ow : c10::irange(output_width)) { + F::_compute_indices_min_size_weights_aa( + ow, + input_width, + width_scale, + support_w, + wx.data(), + interp_width, + filter_fn, + xmin, + xsize); + + for (const auto c : c10::irange(begin, end)) { + scalar_t grad_output_value = + grad_output_data[c * output_slice_size + oh * output_width + ow]; + + for (const auto y : c10::irange(ysize)) { + for (const auto x : c10::irange(xsize)) { + *input_indexr(c, ymin + y, xmin + x) += + wx[x] * wy[y] * grad_output_value; + } + } + } + } + } + }; + + if (ndim == 4) { + // upsample bilinear 2d + at::parallel_for( + 0, channels, at::internal::GRAIN_SIZE / output_slice_size / 4, loop2d); + } else { + TORCH_CHECK(false, "Unsupported tensor ndim"); + } + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +void upsample_bilinear2d_aa_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + AT_DISPATCH_FLOATING_TYPES( + grad_output.scalar_type(), "upsample_bilinear2d_aa_backward_cpu", [&] { + upsample_separable_Nd_backward_aa( + grad_input, grad_output, align_corners, {scales_h, scales_w}); + }); +} + +void upsample_bicubic2d_aa_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + AT_DISPATCH_FLOATING_TYPES( + grad_output.scalar_type(), "upsample_bicubic2d_aa_backward_cpu", [&] { + upsample_separable_Nd_backward_aa( + grad_input, grad_output, align_corners, {scales_h, scales_w}); + }); +} + +void upsample_lanczos2d_aa_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + AT_DISPATCH_FLOATING_TYPES( + grad_output.scalar_type(), "upsample_lanczos2d_aa_backward_cpu", [&] { + upsample_separable_Nd_backward_aa( + grad_input, grad_output, align_corners, {scales_h, scales_w}); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(upsample_nearest1d_kernel, &upsample_nearest1d_kernel_impl) +REGISTER_DISPATCH(_upsample_nearest_exact1d_kernel, &_upsample_nearest_exact1d_kernel_impl) +REGISTER_DISPATCH(upsample_nearest2d_kernel, &upsample_nearest2d_kernel_impl) +REGISTER_DISPATCH(_upsample_nearest_exact2d_kernel, &_upsample_nearest_exact2d_kernel_impl) +REGISTER_DISPATCH(upsample_nearest3d_kernel, &upsample_nearest3d_kernel_impl) +REGISTER_DISPATCH(_upsample_nearest_exact3d_kernel, &_upsample_nearest_exact3d_kernel_impl) + +REGISTER_DISPATCH(upsample_linear1d_kernel, &upsample_linear1d_kernel_impl) +REGISTER_DISPATCH(upsample_bilinear2d_kernel, &upsample_bilinear2d_kernel_impl) +REGISTER_DISPATCH(_upsample_bilinear2d_aa_kernel, &upsample_bilinear2d_aa_kernel_impl) +REGISTER_DISPATCH(_upsample_bilinear2d_aa_backward_kernel, &upsample_bilinear2d_aa_backward_kernel_impl) +REGISTER_DISPATCH(upsample_trilinear3d_kernel, &upsample_trilinear3d_kernel_impl) + +REGISTER_DISPATCH(upsample_bicubic2d_kernel, &upsample_bicubic2d_kernel_impl) +REGISTER_DISPATCH(_upsample_bicubic2d_aa_kernel, &upsample_bicubic2d_aa_kernel_impl) +REGISTER_DISPATCH(_upsample_bicubic2d_aa_backward_kernel, &upsample_bicubic2d_aa_backward_kernel_impl) + +REGISTER_DISPATCH(_upsample_lanczos2d_aa_kernel, &upsample_lanczos2d_aa_kernel_impl) +REGISTER_DISPATCH(_upsample_lanczos2d_aa_backward_kernel, &upsample_lanczos2d_aa_backward_kernel_impl) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernelAVXAntialias.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernelAVXAntialias.h new file mode 100644 index 0000000000000000000000000000000000000000..bc4a7042d3f61fb981584daad3ac821431a36687 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernelAVXAntialias.h @@ -0,0 +1,1376 @@ +/* +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh + +Pillow is the friendly PIL fork. It is + + Copyright © 2010-2022 by Alex Clark and contributors + +Like PIL, Pillow is licensed under the open source HPND License +*/ + +// This code is heavily inspired from PILLOW-SIMD's implementation: +// https://github.com/uploadcare/pillow-simd/blob/simd/master/src/libImaging/Resample.c + +#pragma once +#ifdef CPU_CAPABILITY_AVX2 +// TODO: This file only supports AVX2. We could split the AVX kernels into +// smaller logical blocks in order to port them into the Vec.h logic. This would +// allow to support other vectorization architectures and perhaps also support +// the non-vectorized fallback (we'd need to make sure it's not slower than the +// current fallback). + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + + +namespace { + +inline __m128i mm_cvtsi32_si128(const uint8_t* C10_RESTRICT ptr, bool i32_aligned) { + int32_t v; + if (i32_aligned) { + v = *(const int32_t*)ptr; + } else { + std::memcpy(&v, ptr, 4); + } + return _mm_cvtsi32_si128(v); +} + +inline __m128i mm_cvtepu8_epi32(const uint8_t* C10_RESTRICT ptr, bool i32_aligned) { + return _mm_cvtepu8_epi32(mm_cvtsi32_si128(ptr, i32_aligned)); +} + +inline void _write_endline_rgb_as_uint32( + uint8_t* C10_RESTRICT output, + uint32_t data +) { + // data is (R G B X), output is (X1 X2 X3 | R1 B1 G1 R2 ...) + // Here we explicitly set X as R1 + uint8_t* data_ptr = reinterpret_cast(&data); + data_ptr[3] = output[3]; + std::memcpy(output, data_ptr, 4); +} + +at::Tensor unpack_rgb(const at::Tensor& packed_tensor) { + // Convert a "packed" tensor (typically RGBRGBRGB if channels_last) into + // RGBARGBARGBA format where A is hard-coded to 0. Each pixel is encoded + // into as 32 bits. This generalizes to num_channels <= 4 and also works for + // non-channels_last tensors. + + const uint8_t* packed = (const uint8_t*)packed_tensor.const_data_ptr(); + auto num_pixels = packed_tensor.size(1) * packed_tensor.size(2); + auto num_channels = packed_tensor.size(0); + + constexpr int rgba_size = 4; + auto unpacked_tensor = at::empty({rgba_size, packed_tensor.size(1), packed_tensor.size(2)}, at::CPU(at::kByte)); + uint8_t* unpacked = (uint8_t*) unpacked_tensor.data_ptr(); + + auto stride_i = packed_tensor.stride(2); + auto stride_j = packed_tensor.stride(0); + + for (const auto i : c10::irange(num_pixels)) { + for (const auto j : c10::irange(rgba_size)) { + unpacked[rgba_size * i + j] = (j < num_channels) ? packed[stride_i * i + stride_j * j] : 0; + } + } + return unpacked_tensor; +} + +void pack_rgb( + const at::Tensor& unpacked_tensor, // IN + const at::Tensor& packed_tensor // OUT +) { + // Convert from unpacked channels last 3-channels or 4-channels tensor into original data layout. + + uint8_t* unpacked = (uint8_t*)unpacked_tensor.data_ptr(); + uint8_t* packed = (uint8_t*)packed_tensor.data_ptr(); + auto num_pixels = packed_tensor.size(1) * packed_tensor.size(2); + auto num_channels = packed_tensor.size(0); + + auto unpacked_increment = unpacked_tensor.size(0); + auto packed_increment = packed_tensor.stride(2); + auto packed_stride = packed_tensor.stride(0); + + TORCH_INTERNAL_ASSERT(unpacked_increment == 3 || unpacked_increment == 4); + + for ([[maybe_unused]] const auto i : c10::irange(num_pixels)) { + for (const auto j : c10::irange(num_channels)) { + packed[j * packed_stride] = unpacked[j]; + } + unpacked += unpacked_increment; + packed += packed_increment; + } +} + +void ImagingResampleHorizontalConvolution8u4x( + uint8_t* C10_RESTRICT lineOut0, + uint8_t* C10_RESTRICT lineOut1, + uint8_t* C10_RESTRICT lineOut2, + uint8_t* C10_RESTRICT lineOut3, + int64_t out_xsize, + const uint8_t* C10_RESTRICT lineIn0, + const uint8_t* C10_RESTRICT lineIn1, + const uint8_t* C10_RESTRICT lineIn2, + const uint8_t* C10_RESTRICT lineIn3, + int64_t in_xsize, + const int64_t* idx_ptr_xmin, + const int64_t* idx_ptr_size, + const int16_t* kk, + int kmax, + unsigned int coefs_precision, + int64_t num_channels, + bool is_last_line); + +void ImagingResampleHorizontalConvolution8u( + uint8_t* C10_RESTRICT lineOut, + int64_t out_xsize, + const uint8_t* C10_RESTRICT lineIn, + int64_t in_xsize, + const int64_t* idx_ptr_xmin, + const int64_t* idx_ptr_size, + const int16_t* kk, + int kmax, + unsigned int coefs_precision, + int64_t num_channels, + bool is_last_line); + +void ImagingResampleVerticalConvolution8u( + uint8_t* C10_RESTRICT lineOut, + const uint8_t* C10_RESTRICT lineIn, + int64_t xsize, + int64_t ids_min, + int64_t ids_size, + const int16_t* k, + unsigned int coefs_precision, + int64_t num_channels); + +template +void ImagingResampleHorizontal( + const at::Tensor & unpacked_output, + const at::Tensor & unpacked_input, + int ksize, + const std::vector& horiz_indices_weights, + unsigned int horiz_weights_precision) { + + // Interpolation horizontal pass: we compute x-axis (image width) interpolation outputs. + + // Input data is stored as + // input = [r[0], g[0], b[0], a[0], r[1], g[1], b[1], a[1], r[2], g[2], b[2], a[2], ...] + // Weights are float values computed for each output pixel and rescaled to uint16: + // weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]] + // We want to compute the output as following: + // output = [oR[0], oG[0], oB[0], oA[0], oR[1], oG[1], oB[1], oA[1], ...] + // where + // oR[yoffset + i] = r[yoffset + xmin[i]] * w[i, 0] + ... + r[yoffset + xmin[i] + K-1] * w[i, K-1] + // oG[yoffset + i] = g[yoffset + xmin[i]] * w[i, 0] + ... + g[yoffset + xmin[i] + K-1] * w[i, K-1] + // oB[yoffset + i] = b[yoffset + xmin[i]] * w[i, 0] + ... + b[yoffset + xmin[i] + K-1] * w[i, K-1] + // + + // TODO: we may want to merge that into the fallback code (currently called + // basic_loop_separable_1d_horizontal) + // Although this may not be needed if / when we port all this code to use + // Vec.h since this would potentially give us another fall-back implem + + const int16_t* kk = (int16_t*)(horiz_indices_weights[3].const_data_ptr()); + + auto xout = unpacked_output.size(2); + auto yout = unpacked_output.size(1); + auto xin = unpacked_input.size(2); + TORCH_INTERNAL_ASSERT(num_channels == unpacked_input.size(0)); + + const int64_t* idx_ptr_xmin = horiz_indices_weights[0].const_data_ptr(); + const int64_t* idx_ptr_size = horiz_indices_weights[1].const_data_ptr(); + + uint8_t* unpacked_output_p = unpacked_output.data_ptr(); + const uint8_t* unpacked_input_p = unpacked_input.const_data_ptr(); + + int64_t yy = 0; + auto xout_stride = xout * num_channels; + auto xin_stride = xin * num_channels; + for (; yy < yout - 3; yy += 4) { + ImagingResampleHorizontalConvolution8u4x( + unpacked_output_p + yy * xout_stride, + unpacked_output_p + (yy + 1) * xout_stride, + unpacked_output_p + (yy + 2) * xout_stride, + unpacked_output_p + (yy + 3) * xout_stride, + xout, + unpacked_input_p + yy * xin_stride, + unpacked_input_p + (yy + 1) * xin_stride, + unpacked_input_p + (yy + 2) * xin_stride, + unpacked_input_p + (yy + 3) * xin_stride, + xin, + idx_ptr_xmin, + idx_ptr_size, + kk, + ksize, + horiz_weights_precision, + num_channels, + yy + 3 == yout - 1); + } + for (; yy < yout; yy++) { + ImagingResampleHorizontalConvolution8u( + unpacked_output_p + yy * xout_stride, + xout, + unpacked_input_p + yy * xin_stride, + xin, + idx_ptr_xmin, + idx_ptr_size, + kk, + ksize, + horiz_weights_precision, + num_channels, + yy == yout - 1); + } +} + +void ImagingResampleVertical( + const at::Tensor & unpacked_output, + const at::Tensor & unpacked_input, + int ksize, + const std::vector& vert_indices_weights, + unsigned int vert_weights_precision) { + + // Interpolation vertical pass: we compute y-axis interpolation outputs. + // Input data is stored as + // input = [r[0], g[0], b[0], a[0], r[1], g[1], b[1], a[1], r[2], g[2], b[2], a[2], ...] + // Weights are float values computed for each output pixel and rescaled to uint16: + // weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]] + // We want to compute the output as following: + // output = [oR[0], oG[0], oB[0], oA[0], oR[1], oG[1], oB[1], oA[1], ...] + // where + // oR[xoffset + i] = r[xoffset + ymin[i]] * w[i, 0] + ... + r[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1] + // oG[xoffset + i] = g[xoffset + ymin[i]] * w[i, 0] + ... + g[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1] + // oB[xoffset + i] = b[xoffset + ymin[i]] * w[i, 0] + ... + b[xoffset + ymin[i] + (K-1) * xsize] * w[i, K-1] + + // TODO: we may want to merge that into the fallback code (currently called + // basic_loop_separable_1d_vertical) + // Although this may not be needed if / when we port all this code to use + // Vec.h since this would potentially give us another fall-back implem + const int16_t* kk = (int16_t*)(vert_indices_weights[3].const_data_ptr()); + + const int64_t* idx_ptr_xmin = vert_indices_weights[0].const_data_ptr(); + const int64_t* idx_ptr_size = vert_indices_weights[1].const_data_ptr(); + + uint8_t* unpacked_output_p = unpacked_output.data_ptr(); + const uint8_t* unpacked_input_p = unpacked_input.const_data_ptr(); + + auto xout = unpacked_output.size(2); + auto yout = unpacked_output.size(1); + const auto num_channels = unpacked_input.size(0); + TORCH_INTERNAL_ASSERT(num_channels == unpacked_output.size(0)); + + auto xout_stride = xout * num_channels; + for (const auto yy : c10::irange(yout)) { + const auto* k = &kk[yy * ksize]; + auto ids_min = idx_ptr_xmin[yy]; + auto ids_size = idx_ptr_size[yy]; + ImagingResampleVerticalConvolution8u( + unpacked_output_p + yy * xout_stride, + unpacked_input_p, + xout, + ids_min, + ids_size, + k, + vert_weights_precision, + num_channels); + } +} + +// This is the only public entry point in this file. It supports bilinear or bicubic +// mode for uint8 dtype when C <= 4, with or without antialias. The +// implem is based on PIL-SIMD. +// Its equivalent implementation (fallback) for when AVX isn't supported or when +// C > 4 is upsample_separable_Nd_kernel_impl() There are a bunch of +// future improvement that can be done: look for the TODOs in this file. +// For details on how the weights are computed and how the multiplications are +// run on int (instead of float weights), see +// [ Weights computation for uint8_t and multiplication trick ] +// For details on how the AVX kernels are implemented, see +// https://gist.github.com/NicolasHug/47c97d731f05eaad5694c173849b86f5 +// See also [ Support for antialias=False as a subcase of antialias=True ] to +// learn more about how the antialias=False case is computed. The same holds +// here: all these kernels are general enough to handle an arbitrary number of +// weights, but when aa=False they could be optimized further. +template +void upsample_avx_bilinear_bicubic_uint8( + const at::Tensor& input_, + const at::Tensor& output, + bool align_corners, + const scale_type& scales, + bool antialias) { + auto batch_size = input_.size(0); + auto num_channels = input_.size(1); + auto xin = input_.size(3); + auto yin = input_.size(2); + auto xout = output.size(3); + auto yout = output.size(2); + + if (xin == xout && yin == yout) { + output.copy_(input_); + return; + } + + at::Tensor input = input_; + if (!(input.is_contiguous() || input.is_contiguous(at::MemoryFormat::ChannelsLast))) { + // If input is not contiguous with memory format channels first or channels last, + // we explicitly convert the input to contiguous channels last memory format. + // This simplifies the rest of the code and let us assume that the format is only contiguous channels first or channels last, + // Most tensors going through this `if` block won't need to go through unpacking, but those having C < 3 may + // have to (this means 2 copies are made). We could avoid the extra copy by handling non-contiguous input + // directly within unpack_rgb() and pack_rgb(), but initial attempts showed that this is fairly complex. + input = input.contiguous(at::MemoryFormat::ChannelsLast); + } + + auto need_horizontal = xout != xin; + auto need_vertical = yout != yin; + + int ksize_horiz, ksize_vert; + std::vector horiz_indices_weights, vert_indices_weights; + unsigned int horiz_weights_precision, vert_weights_precision; + + bool skip_unpacking = (num_channels == 3 || num_channels == 4) && input.is_contiguous(at::MemoryFormat::ChannelsLast); + bool skip_packing = (num_channels == 3 || num_channels == 4) && output.is_contiguous(at::MemoryFormat::ChannelsLast); + + if (need_horizontal) { + int interp_dim = 3; + auto stride = skip_unpacking ? num_channels : 4; + std::tie(horiz_indices_weights, ksize_horiz, horiz_weights_precision) = + F::compute_index_ranges_int16_weights( + /*input_size=*/xin, + /*output_size=*/xout, + /*stride=*/stride, + /*ndims=*/4, + /*reshape_dim=*/interp_dim, + /*align_corners=*/align_corners, + /*opt_scale=*/scales[interp_dim - 2], + /*antialias=*/antialias, + /*align_i32=*/true); + } + + if (need_vertical) { + int interp_dim = 2; + auto stride = skip_unpacking ? num_channels * xout : 4 * xout; + std::tie(vert_indices_weights, ksize_vert, vert_weights_precision) = + F::compute_index_ranges_int16_weights( + /*input_size=*/yin, + /*output_size=*/yout, + /*stride=*/stride, + /*ndims=*/4, + /*reshape_dim=*/interp_dim, + /*align_corners=*/align_corners, + /*opt_scale=*/scales[interp_dim - 2], + /*antialias=*/antialias, + /*align_i32=*/true); + } + + at::Tensor buffer_horiz, buffer_vert; + // Minor optimization: we can avoid allocating an extra buffer if we're performing + // horizontal-only or vertical-only interpolation, and if the tensor doesn't + // need repacking + if (need_horizontal && (need_vertical || !skip_packing)) { + auto c = skip_unpacking ? num_channels : 4; + buffer_horiz = at::empty({c, yin, xout}, input.options()); + } + if (need_vertical && !skip_packing) { + auto c = skip_unpacking ? num_channels : 4; + buffer_vert = at::empty({c, yout, xout}, input.options()); + } + + for (const auto i : c10::irange(batch_size)) { + + at::Tensor unpacked_input = skip_unpacking ? input[i] : unpack_rgb(input[i]); + at::Tensor unpacked_output; + + if (need_horizontal) { + at::Tensor unpacked_output_temp = (need_vertical || !skip_packing) ? buffer_horiz : output[i]; + + if (skip_unpacking && num_channels == 3) { + ImagingResampleHorizontal<3>( + unpacked_output_temp, + unpacked_input, + ksize_horiz, + horiz_indices_weights, + horiz_weights_precision); + } else { + ImagingResampleHorizontal<4>( + unpacked_output_temp, + unpacked_input, + ksize_horiz, + horiz_indices_weights, + horiz_weights_precision); + } + unpacked_output = unpacked_input = unpacked_output_temp; + } + if (need_vertical) { + unpacked_output = skip_packing ? output[i] : buffer_vert; + + ImagingResampleVertical( + unpacked_output, + unpacked_input, + ksize_vert, + vert_indices_weights, + vert_weights_precision + ); + } + + TORCH_INTERNAL_ASSERT(unpacked_output.defined()); + + if (!skip_packing) { + pack_rgb(unpacked_output, output[i]); + } + } +} + +void ImagingResampleHorizontalConvolution8u4x( + uint8_t* C10_RESTRICT lineOut0, + uint8_t* C10_RESTRICT lineOut1, + uint8_t* C10_RESTRICT lineOut2, + uint8_t* C10_RESTRICT lineOut3, + int64_t out_xsize, + const uint8_t* C10_RESTRICT lineIn0, + const uint8_t* C10_RESTRICT lineIn1, + const uint8_t* C10_RESTRICT lineIn2, + const uint8_t* C10_RESTRICT lineIn3, + int64_t in_xsize, + const int64_t* idx_ptr_xmin, + const int64_t* idx_ptr_size, + const int16_t* kk, + int kmax, + unsigned int coefs_precision, + int64_t num_channels, + bool is_last_line) { + + // Interpolation horizontal pass processing together 4 vertical lines. + // - Input data format is RGBA or RGB with R,G,B,A being uint8. In case of RGBA + // we can encode 4 values as a single uint32 value. + // - We split the size of weight vector for a given output index as a sum: + // ids_size = num_blocks_4 * 4 + num_blocks_2 * 2 + num_blocks_1. + // - We load and process 4 weights values in a loop ("block 4") then we process 2 weights values + // in another loop ("block 2") and finally we process 1 weights value in the final loop ("block 1"). + + // Define shuffling masks (low/high) for num_channels 4 and 3 + // Mask low casts lower half of each lane to epi16 and reorder RGBARGBA -> RRGGBBAA: + // [r1 g1 b1 a1 r2 g2 b2 a2 ... | R1 G1 B1 A1 R2 G2 B2 A2 ... ] -> + // [r1 0 r2 0 g1 0 g2 0 b1 0 b2 0 a1 0 a2 0 | R1 0 R2 0 G1 0 G2 0 B1 0 B2 0 A1 0 A2 0] + // Mask high casts upper half of each lane to epi16 and reorder RGBARGBA -> RRGGBBAA:: + // [ ... r3 g3 b3 a3 r4 g4 b4 a4 | ... R3 G3 B3 A3 R4 G4 B4 A4 ] -> + // [r3 0 r4 0 g3 0 g4 0 b3 0 b4 0 a3 0 a4 0 | R3 0 R4 0 G3 0 G4 0 B3 0 B4 0 A3 0 A4 0] + + const auto mask_low_c4 = _mm256_set_epi8( + -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0, + -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0); + const auto mask_high_c4 = _mm256_set_epi8( + -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8, + -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8); + const auto mask_low_c3 = _mm256_set_epi8( + -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0, + -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0); + const auto mask_high_c3 = _mm256_set_epi8( + -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6, + -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6); + + const auto mask_low = (num_channels == 3) ? mask_low_c3 : mask_low_c4; + const auto mask_high = (num_channels == 3) ? mask_high_c3 : mask_high_c4; + + const auto stride = num_channels * sizeof(uint8_t); + + TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4); + + // out_xsize = output width, out_x = output x index + // ids_min is the input offset index corresponding to out_x + // ids_size is the interpolation size for out_x + + // Let's precompute ids_size limits for block 4 and block 2. + // + // In block 4 (4 means we process 4 weight values together), we read input data + // with _mm_loadu_si128, i.e. 16 bytes, per one line: + // lineIn0 + stride * (i + ids_min) + 16 <= lineIn0 + stride * (ids_size + ids_min) + // --> i <= ids_size - 16.0 / stride + // Strict boundary: + // --> i < ids_size + 1 - int(ceil(16.0 / stride)) = ids_size - b4_delta + // Soft boundary for reading inside the buffer except its boundaries: + // --> i < ids_size + 1 - int(16.0 / stride) = ids_size - b4_delta_soft + // RGBA: b4_delta = b4_delta_soft = 3 + // RGB : b4_delta = 5 + // RGB : b4_delta_soft = 4 + const auto b4_delta = (stride == 4) ? 3 : (is_last_line ? 5 : 4); + + // In block 2 (2 means we process 2 weights values together), we read input data + // with _mm_loadl_epi64, i.e. 8 bytes, per one line: + // lineIn0 + stride * (i + ids_min) + 8 <= lineIn0 + stride * (ids_size + ids_min) + // --> i <= ids_size - 8.0 / stride + // Strict boundary: + // --> i < ids_size + 1 - int(ceil(8.0 / stride)) = ids_size - b2_delta + // Soft boundary for reading inside the buffer except its boundaries: + // --> i < ids_size + 1 - int(8.0 / stride) = ids_size - b2_delta_soft + // RGBA: b2_delta = b2_delta_soft = 1 + // RGB : b2_delta = 2 + // RGB : b2_delta_soft = 1 + const auto b2_delta = (stride == 4) ? 1 : (is_last_line ? 2 : 1); + + const auto max_out_x_strided = out_xsize * stride; + const auto max_in_x_strided = in_xsize * stride; + + const auto zero = _mm256_setzero_si256(); + const auto initial = _mm256_set1_epi32(1 << (coefs_precision - 1)); + + for (const auto out_x : c10::irange(out_xsize)) { + const auto ids_min = idx_ptr_xmin[out_x]; + const auto ids_size = idx_ptr_size[out_x]; + const auto * k = &kk[out_x * kmax]; + int64_t i = 0; + + auto sss0 = initial; + auto sss1 = initial; + + const auto * lineIn0_min = lineIn0 + ids_min; + const auto * lineIn1_min = lineIn1 + ids_min; + const auto * lineIn2_min = lineIn2 + ids_min; + const auto * lineIn3_min = lineIn3 + ids_min; + + // block 4 + for (; i < ids_size - b4_delta; i += 4) { + // Load 4 values from weight vector + // mmk0 = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...] + // mmk1 = [wl_2 wh_2 wl_3 wh_3 wl_2 wh_2 wl_3 wh_3 ...] + const auto mmk0 = _mm256_set1_epi32(*(int32_t*)&k[i]); + const auto mmk1 = _mm256_set1_epi32(*(int32_t*)&k[i + 2]); + + // RGBA: Load 8 pixels (4 per line) from input lines 0 and 1: + // source = [ + // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3 + // R0 G0 B0 A0 R1 G1 B1 A1 R2 G2 B2 A2 R3 G3 B3 A3 + // ] + // RGB: Load 10 pixels (5 per line) + // source = [ + // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5 + // R0 G0 B0 R1 G1 B1 R2 G2 B2 R3 G3 B3 R4 G4 B4 R5 + // ] + auto source = _mm256_inserti128_si256(_mm256_castsi128_si256( + _mm_loadu_si128((__m128i *) (lineIn0_min + stride * i))), + _mm_loadu_si128((__m128i *) (lineIn1_min + stride * i)), 1); + + // Apply mask_low: + // RGBA: + // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 A0 0 A1 0] + // RGB: + // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 0 0 0 0] + auto pix1 = _mm256_shuffle_epi8(source, mask_low); + // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk0)); + + // Apply mask_high: + // RGBA: + // [r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 a2 0 a3 0 | R2 0 R3 0 G2 0 G3 0 B2 0 B3 0 A2 0 A3 0] + // RGB: + // [r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 0 0 0 0 | R2 0 R3 0 G2 0 G3 0 B2 0 B3 0 0 0 0 0] + auto pix2 = _mm256_shuffle_epi8(source, mask_high); + // Compute output value as C += w2 * C2 + w3 * C3 for each channel in 32-bit precision + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix2, mmk1)); + + // Same as above to next lines 2 and 3: + auto source2 = _mm256_inserti128_si256(_mm256_castsi128_si256( + _mm_loadu_si128((__m128i *) (lineIn2_min + stride * i))), + _mm_loadu_si128((__m128i *) (lineIn3_min + stride * i)), 1); + auto pix3 = _mm256_shuffle_epi8(source2, mask_low); + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix3, mmk0)); + auto pix4 = _mm256_shuffle_epi8(source2, mask_high); + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix4, mmk1)); + } + + // block 2 + for (; i < ids_size - b2_delta; i += 2) { + // Load 2 values from weight vector + // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...] + const auto mmk = _mm256_set1_epi32(*(int32_t*)&k[i]); + + // Load 4 pixels (2 per line) from input lines 0 and 1: + // RGBA: source1 = [ + // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0 + // R0 G0 B0 A0 R1 G1 B1 A1 0 0 0 0 0 0 0 0 + // ] + // RGB: source1 = [ + // r0 g0 b0 r1 g1 b1 r2 0 0 0 0 0 0 0 0 + // R0 G0 B0 R1 G1 B1 R2 0 0 0 0 0 0 0 0 + // ] + auto source1 = _mm256_inserti128_si256(_mm256_castsi128_si256( + _mm_loadl_epi64((__m128i *) (lineIn0_min + stride * i))), + _mm_loadl_epi64((__m128i *) (lineIn1_min + stride * i)), 1); + // Apply mask_low: + // RGBA: + // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 A0 0 A1 0] + // RGB: + // [r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 | R0 0 R1 0 G0 0 G1 0 B0 0 B1 0 0 0 0 0] + auto pix1 = _mm256_shuffle_epi8(source1, mask_low); + // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk)); + + // Same as above for lines 2 and 3: + auto source2 = _mm256_inserti128_si256(_mm256_castsi128_si256( + _mm_loadl_epi64((__m128i *) (lineIn2_min + stride * i))), + _mm_loadl_epi64((__m128i *) (lineIn3_min + stride * i)), 1); + auto pix2 = _mm256_shuffle_epi8(source2, mask_low); + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk)); + } + + // block 1 + const auto i32_aligned = num_channels == 4; + for (; i < ids_size - 1; i++) { + // Load 1 value from weight vector + // mmk = [wl_0 wh_0 0 0 wl_0 wh_0 0 0 ...] + const auto mmk = _mm256_set1_epi32(k[i]); + + // Load 2 pixels (one per line) from input lines 0 and 1: + // RGBA: pix1 = [ + // r0 0 0 0 g0 0 0 0 b0 0 0 0 a0 0 0 0 + // R0 0 0 0 G0 0 0 0 B0 0 0 0 A0 0 0 0 + // ] + // RGB: pix1 = [ + // r0 0 0 0 g0 0 0 0 b0 0 0 0 r1 0 0 0 + // R0 0 0 0 G0 0 0 0 B0 0 0 0 R1 0 0 0 + // ] + auto pix1 = _mm256_inserti128_si256(_mm256_castsi128_si256( + mm_cvtepu8_epi32(lineIn0_min + stride * i, i32_aligned)), + mm_cvtepu8_epi32(lineIn1_min + stride * i, i32_aligned), 1); + // Compute output value as C += w0 * C0 for each channel in 32-bit precision + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk)); + + // Same as above for lines 2 and 3 + auto pix2 = _mm256_inserti128_si256(_mm256_castsi128_si256( + mm_cvtepu8_epi32(lineIn2_min + stride * i, i32_aligned)), + mm_cvtepu8_epi32(lineIn3_min + stride * i, i32_aligned), 1); + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk)); + } + + if (i == ids_size - 1) { + // last element + auto mmk = _mm256_set1_epi32(k[i]); + // For num_channels == 3 (3 bytes = one pixel) we tolerate to read 4 bytes + // lines 0, 1 and 2 won't go out of allocated memory bounds + auto pix = _mm256_inserti128_si256(_mm256_castsi128_si256( + mm_cvtepu8_epi32(lineIn0_min + stride * i, i32_aligned)), + mm_cvtepu8_epi32(lineIn1_min + stride * i, i32_aligned), 1); + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix, mmk)); + + auto p0 = mm_cvtepu8_epi32(lineIn2_min + stride * i, i32_aligned); + __m128i p1; + if (num_channels == 3 && C10_UNLIKELY(is_last_line && ids_min + stride * i + 4 >= max_in_x_strided)) { + uint8_t input[4]; + std::memcpy(input, lineIn3_min + stride * i, 3); + p1 = mm_cvtepu8_epi32(input, true); + } else { + p1 = mm_cvtepu8_epi32(lineIn3_min + stride * i, i32_aligned); + } + auto pix2 = _mm256_inserti128_si256(_mm256_castsi128_si256(p0), p1, 1); + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk)); + } + + // Convert fixed point values back to integers (truncating) + sss0 = _mm256_srai_epi32(sss0, coefs_precision); + sss1 = _mm256_srai_epi32(sss1, coefs_precision); + // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation + // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d 0 0 0 0 0 0 0 0) + sss0 = _mm256_packs_epi32(sss0, zero); + sss1 = _mm256_packs_epi32(sss1, zero); + // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation + // (a a b b c c d d) -> (a b c d 0 0 0 0) + sss0 = _mm256_packus_epi16(sss0, zero); + sss1 = _mm256_packus_epi16(sss1, zero); + + // Write the output into single uint32 + // (a b c d) -> x_uint32 + auto o0 = _mm_cvtsi128_si32(_mm256_castsi256_si128(sss0)); + auto o1 = _mm_cvtsi128_si32(_mm256_extracti128_si256(sss0, 1)); + auto o2 = _mm_cvtsi128_si32(_mm256_castsi256_si128(sss1)); + auto o3 = _mm_cvtsi128_si32(_mm256_extracti128_si256(sss1, 1)); + + const auto out_x_strided = stride * out_x; + + if (num_channels == 3 && C10_UNLIKELY(out_x_strided + 4 >= max_out_x_strided)) { + // Memcpy 4-bytes is faster than 3-bytes and this is a boundary case when we want to write + // 4 bytes (R G B | X) to the output buffer (X1 X2 X3 | R1). + // The 4th byte in the register (X) has a garbage value and 4th byte in the output buffer (R1) has a correct + // value which was previously computed by another line. In other words, it means that we can not overwrite + // it by simply writing 4 bytes from the register to the output. We'll do the following: + // v----------| + // Output = [... X1 X2 X3 | R1 G1 B1 R2 ...] + // First, we write R1 value to the 4th byte of (R G B | X) -> (R G B | R1) + // Second, we write 4 bytes from the register to the output: (X1 X2 X3 | R1) -> (R G B | R1) + // Output = [... R G B | R1 G1 B1 R2 ...] + + _write_endline_rgb_as_uint32(lineOut0 + out_x_strided, o0); + _write_endline_rgb_as_uint32(lineOut1 + out_x_strided, o1); + _write_endline_rgb_as_uint32(lineOut2 + out_x_strided, o2); + + if (C10_UNLIKELY(is_last_line)) { + // When we handle the last line, we can not access the next 4 bytes + // as they are out of memory bounds. + std::memcpy(lineOut3 + out_x_strided, (uint8_t *) &o3, num_channels); + } else { + _write_endline_rgb_as_uint32(lineOut3 + out_x_strided, o3); + } + } else if (num_channels == 3) { + // Memcpy 4-bytes is faster than 3-bytes and here + // we simply write 4 bytes (... R G B X 0 0 0 0 0 ...) where X is a garbage value + // that we will overwrite on the next iteration: (... R G B R G B X 0 0 ...) + std::memcpy(lineOut0 + out_x_strided, (uint8_t *) &o0, 4); + std::memcpy(lineOut1 + out_x_strided, (uint8_t *) &o1, 4); + std::memcpy(lineOut2 + out_x_strided, (uint8_t *) &o2, 4); + std::memcpy(lineOut3 + out_x_strided, (uint8_t *) &o3, 4); + } else { + // num_channels = 4 -> lineOutX + out_x_strided should be uint32 aligned + *(uint32_t *)(lineOut0 + out_x_strided) = o0; + *(uint32_t *)(lineOut1 + out_x_strided) = o1; + *(uint32_t *)(lineOut2 + out_x_strided) = o2; + *(uint32_t *)(lineOut3 + out_x_strided) = o3; + } + } +} + +void ImagingResampleHorizontalConvolution8u( + uint8_t* C10_RESTRICT lineOut, + int64_t out_xsize, + const uint8_t* C10_RESTRICT lineIn, + int64_t in_xsize, + const int64_t* idx_ptr_xmin, + const int64_t* idx_ptr_size, + const int16_t* kk, + int kmax, + unsigned int coefs_precision, + int64_t num_channels, + bool is_last_line) { + + // Interpolation horizontal pass processing only one vertical line. + // - Input data format is RGBA or RGB with R,G,B,A being uint8. In case of RGBA + // we can encode 4 values as a single uint32 value. + // - We split the size of weight vector for a given output index as a sum: + // ids_size = num_blocks_8 * 8 + num_blocks_4 * 4 + num_blocks_2 * 2 + num_blocks_1 + // - We load and process 8 weights values in a loop ("block 8") then 4 weights and 2 weights values in + // in another loops ("block 4" and "block 2") and finally we process 1 weight value in the final loop ("block 1"). + + // Define various shuffling masks + const auto kmask_low = _mm256_set_epi8( + 11, 10, 9, 8, 11, 10, 9, 8, 11, 10, 9, 8, 11, 10, 9, 8, + 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0); + const auto kmask_high = _mm256_set_epi8( + 15, 14, 13, 12, 15, 14, 13, 12, 15, 14, 13, 12, 15, 14, 13, 12, + 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4); + const auto kmask_hl = _mm256_set_epi8( + 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, 7, 6, 5, 4, + 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0); + + const auto mask_low_c4 = _mm256_set_epi8( + -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0, + -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0); + const auto mask_high_c4 = _mm256_set_epi8( + -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8, + -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8); + const auto mask_low_c3 = _mm256_set_epi8( + -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0, + -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0); + const auto mask_high_c3 = _mm256_set_epi8( + -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6, + -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6); + const auto mask_hl_c3 = _mm256_set_epi8( + -1, -1, -1, -1, -1, 11, -1, 8, -1, 10, -1, 7, -1, 9, -1, 6, + -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0); + const auto mask_hl_c4 = _mm256_set_epi8( + -1, 15, -1, 11, -1, 14, -1, 10, -1, 13, -1, 9, -1, 12, -1, 8, + -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0); + + const auto mask_low128_c3 = _mm_set_epi8( + -1, -1, -1, -1, -1, 5, -1, 2, -1, 4, -1, 1, -1, 3, -1, 0); + const auto mask_low128_c4 = _mm_set_epi8( + -1, 7, -1, 3, -1, 6, -1, 2, -1, 5, -1, 1, -1, 4, -1, 0); + + const auto mask_low = (num_channels == 3) ? mask_low_c3 : mask_low_c4; + const auto mask_high = (num_channels == 3) ? mask_high_c3 : mask_high_c4; + const auto mask_hl = (num_channels == 3) ? mask_hl_c3 : mask_hl_c4; + const auto mask_low128 = (num_channels == 3) ? mask_low128_c3 : mask_low128_c4; + + // out_xsize = output width, out_x = output x index + // ids_min is the input offset index corresponding to out_x + // ids_size is the interpolation size for out_x + + const auto stride = num_channels * sizeof(uint8_t); + const auto zero = _mm_setzero_si128(); + + TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4); + + // Let's precompute ids_size limits for block 8, block 4 and block 2 + // + // In block 8 (8 means we process 8 weight values together), we read at + // most 32 bytes input data (16 + 16 bytes for RGBA and 12 + 16 bytes for RGB) + // lineIn + stride * (i + ids_min) + 32 <= lineIn + stride * (ids_size + ids_min) + // --> i <= ids_size - 32.0 / stride + // Strict boundary: + // --> i < ids_size + 1 - int(ceil(32.0 / stride)) = ids_size - b8_delta + // Soft boundary for reading inside the buffer except its boundaries: + // --> i < ids_size + 1 - int(32.0 / stride) = ids_size - b8_delta_soft + // RGBA: b8_delta = b8_delta_soft = 7 + // RGB : b8_delta = 10 + // RGB : b8_delta_soft = 9 + const auto b8_delta = (stride == 4) ? 7 : (is_last_line ? 10 : 9); + + // In block 4 (4 means we process 4 weight values together), we read + // 16 bytes of input data. + // lineIn + stride * (i + ids_min) + 16 <= lineIn0 + stride * (ids_size + ids_min) + // --> i <= ids_size - 16.0 / stride + // Strict boundary: + // --> i < ids_size + 1 - int(ceil(16.0 / stride)) = ids_size - b4_delta + // Soft boundary for reading inside the buffer except its boundaries: + // --> i < ids_size + 1 - int(16.0 / stride) = ids_size - b4_delta_soft + // RGBA: b4_delta = b4_delta_soft = 3 + // RGB : b4_delta = 5 + // RGB : b4_delta_soft = 4 + const auto b4_delta = (stride == 4) ? 3 : (is_last_line ? 5 : 4); + + // In block 2 (2 means we process 2 weight values together), we read + // 8 bytes of input data. + // lineIn0 + stride * (i + ids_min) + 8 <= lineIn0 + stride * (ids_size + ids_min) + // --> i <= ids_size - 8.0 / stride + // Strict boundary: + // --> i < ids_size + 1 - int(ceil(8.0 / stride)) = ids_size - b2_delta + // Soft boundary for reading inside the buffer except its boundaries: + // --> i < ids_size + 1 - int(8.0 / stride) = ids_size - b2_delta_soft + // RGBA: b2_delta = b2_delta_soft = 1 + // RGB : b2_delta = 2 + // RGB : b2_delta_soft = 1 + const auto b2_delta = (stride == 4) ? 1 : (is_last_line ? 2 : 1); + + const auto max_out_x_strided = out_xsize * stride; + const auto max_in_x_strided = in_xsize * stride; + + for (const auto out_x : c10::irange(out_xsize)) { + __m128i sss; + const auto ids_min = idx_ptr_xmin[out_x]; + const auto ids_size = idx_ptr_size[out_x]; + const auto * k = &kk[out_x * kmax]; + int64_t i = 0; + + const auto * lineIn_min = lineIn + ids_min; + + if (ids_size < 8) { + sss = _mm_set1_epi32(1 << (coefs_precision - 1)); + } else { + // Lower part will be added to higher, use only half of the error + auto sss256 = _mm256_set1_epi32(1 << (coefs_precision - 2)); + + // block 8 + for (; i < ids_size - b8_delta; i += 8) { + // Load 8 values from weight vector + auto tmp = _mm_loadu_si128((__m128i*)&k[i]); + // ksource = [ + // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 wl_4 wh_4 wl_5 wh_5 wl_6 wh_6 wl_7 wh_7 + // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 wl_4 wh_4 wl_5 wh_5 wl_6 wh_6 wl_7 wh_7 + // ] + auto ksource = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1); + + // RGBA: Load 8 pixels from input: + // source = [ + // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3 + // r4 g4 b4 a4 r5 g5 b5 a5 r6 g6 b6 a6 r7 g7 b7 a7 + // ] + // RGB: Load 10 pixels from input (however we can process only 8 pixels): + // source = [ + // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5 + // r4 g4 b4 r5 g5 b5 r6 g6 b6 r7 g7 b7 r8 g8 b8 r9 + // ] + auto source = _mm256_inserti128_si256(_mm256_castsi128_si256( + _mm_loadu_si128((__m128i *) (lineIn_min + stride * i))), + _mm_loadu_si128((__m128i *) (lineIn_min + stride * (i + 4))), 1); + + // Extract lower part of each lane, cast to epi16 and reorder RGBARGBA -> RRGGBBAA + // RGBA: pix1 = [ + // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 + // r4 0 r5 0 g4 0 g5 0 b4 0 b5 0 a4 0 a5 0 + // ] + // RGB: pix1 = [ + // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 + // r4 0 r5 0 g4 0 g5 0 b4 0 b5 0 0 0 0 0 + // ] + auto pix1 = _mm256_shuffle_epi8(source, mask_low); + // mmk1 = [ + // wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ... + // wl_4 wh_4 wl_5 wh_5 wl_4 wh_4 wl_5 wh_5 ... ... + // ] + auto mmk1 = _mm256_shuffle_epi8(ksource, kmask_low); + // Compute output value as + // C += w0 * C0 + w1 * C1 + // C += w4 * C4 + w5 * C5 for each channel in 32-bit precision + sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix1, mmk1)); + + // Same as above for higher part of each lane + auto pix2 = _mm256_shuffle_epi8(source, mask_high); + auto mmk2 = _mm256_shuffle_epi8(ksource, kmask_high); + // Compute output value as + // C += w2 * C2 + w3 * C3 + // C += w6 * C6 + w7 * C7 for each channel in 32-bit precision + sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix2, mmk2)); + } + + // block 4 + for (; i < ids_size - b4_delta; i += 4) { + // Load 4 values from weight vector + auto tmp = _mm_loadl_epi64((__m128i *) &k[i]); + // ksource = [ + // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 0 0 0 0 0 0 0 0 + // wl_0 wh_0 wl_1 wh_1 wl_2 wh_2 wl_3 wh_3 0 0 0 0 0 0 0 0 + // ] + auto ksource = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1); + + // Load pixels from input line + tmp = _mm_loadu_si128((__m128i *) (lineIn_min + stride * i)); + // RGBA: source = [ + // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3 + // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3 + // ] + // RGB: source = [ + // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5 + // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5 + // ] + auto source = _mm256_insertf128_si256(_mm256_castsi128_si256(tmp), tmp, 1); + + // Cast source to epi16 and reorder RGBARGBA -> RRGGBBAA + // RGBA: pix = [ + // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 a0 0 a1 0 + // r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 a2 0 a3 0 + // ] + // RGB: pix = [ + // r0 0 r1 0 g0 0 g1 0 b0 0 b1 0 0 0 0 0 + // r2 0 r3 0 g2 0 g3 0 b2 0 b3 0 0 0 0 0 + // ] + auto pix = _mm256_shuffle_epi8(source, mask_hl); + // mmk = [ + // wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ... + // wl_2 wh_2 wl_3 wh_3 wl_2 wh_2 wl_3 wh_3 ... ... + // ] + auto mmk = _mm256_shuffle_epi8(ksource, kmask_hl); + // Compute output value as + // C += w0 * C0 + w1 * C1 + // C += w2 * C2 + w3 * C3 for each channel in 32-bit precision + sss256 = _mm256_add_epi32(sss256, _mm256_madd_epi16(pix, mmk)); + } + + // Sum results between the lanes + sss = _mm_add_epi32( + _mm256_extracti128_si256(sss256, 0), + _mm256_extracti128_si256(sss256, 1)); + } + + // block 2 + for (; i < ids_size - b2_delta; i += 2) { + // Load 2 values from weight vector + // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ...] + auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]); + // Load pixels from input line + // RGBA: source = [ + // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0 + // ] + // RGB: source = [ + // r0 g0 b0 r1 g1 b1 r2 g2 0 0 0 0 0 0 0 0 + // ] + auto source = _mm_loadl_epi64((__m128i *) (lineIn_min + stride * i)); + // Cast source to epi16 and reorder RGBARGBA -> RRGGBBAA + auto pix = _mm_shuffle_epi8(source, mask_low128); + // Compute output value as C += w0 * C0 + w1 * C1 for each channel in 32-bit precision + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + + // block 1 + const auto i32_aligned = num_channels == 4; + for (; i < ids_size - 1; i++) { + // Load 1 value from weight vector + // mmk = [wl_0 wh_0 0 0 wl_0 wh_0 0 0 ...] + auto mmk = _mm_set1_epi32(k[i]); + // Load one pixel from input line + // RGBA: pix = [ + // r0 0 0 0 g0 0 0 0 b0 0 0 0 a0 0 0 0 + // ] + // RGB: pix = [ + // r0 0 0 0 g0 0 0 0 b0 0 0 0 r1 0 0 0 + // ] + auto pix = mm_cvtepu8_epi32(lineIn_min + stride * i, i32_aligned); + // Compute output value as C += w0 * C0 for each channel in 32-bit precision + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + + if (i == ids_size - 1) { + // last element + auto mmk = _mm_set1_epi32(k[i]); + __m128i pix; + auto p = lineIn_min + stride * i; + if (num_channels == 3 && C10_UNLIKELY(is_last_line && ids_min + stride * i + 4 >= max_in_x_strided)) { + uint8_t input[4]; + std::memcpy(input, p, 3); + pix = mm_cvtepu8_epi32(input, true); + } else { + pix = mm_cvtepu8_epi32(p, i32_aligned); + } + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + + // Convert fixed point values back to integers (truncating) + sss = _mm_srai_epi32(sss, coefs_precision); + // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation + // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d 0 0 0 0 0 0 0 0) + sss = _mm_packs_epi32(sss, zero); + // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation + // (a a b b c c d d) -> (a b c d 0 0 0 0) + sss = _mm_packus_epi16(sss, zero); + // Write the output into single uint32 + // (a b c d) -> x_uint32 + auto o = _mm_cvtsi128_si32(sss); + const auto out_x_strided = stride * out_x; + if (num_channels == 3 && C10_UNLIKELY(out_x_strided + 4 >= max_out_x_strided)) { + if (C10_UNLIKELY(is_last_line)) { + // When we handle the last line, we can not access the next 4 bytes + // as they are out of memory bounds. + std::memcpy(lineOut + out_x_strided, (uint8_t *) &o, 3); + } else { + // Memcpy 4-bytes is faster than 3-bytes and this is a boundary case when we want to write + // 4 bytes (R G B | X) to the output buffer (X1 X2 X3 | R1). + // The 4th byte in the register (X) has a garbage value and 4th byte in the output buffer (R1) has a correct + // value which was previously computed by another line. In other words, it means that we can not overwrite + // it by simply writing 4 bytes from the register to the output. We'll do the following: + // v----------| + // Output = [... X1 X2 X3 | R1 G1 B1 R2 ...] + // First, we write R1 value to the 4th byte of (R G B | X) -> (R G B | R1) + // Second, we write 4 bytes from the register to the output: (X1 X2 X3 | R1) -> (R G B | R1) + // Output = [... R G B | R1 G1 B1 R2 ...] + _write_endline_rgb_as_uint32(lineOut + out_x_strided, o); + } + } else if (num_channels == 3) { + // Memcpy 4-bytes is faster than 3-bytes and here + // we simply write 4 bytes (... R G B X 0 0 0 0 0 ...) where X is a garbage value + // that we will overwrite on the next iteration: (... R G B R G B X 0 0 ...) + std::memcpy(lineOut + out_x_strided, (uint8_t *) &o, 4); + } else { + // num_channels = 4 -> lineOut + out_x_strided should be uint32 aligned + *(uint32_t *)(lineOut + out_x_strided) = o; + } + } +} + +void ImagingResampleVerticalConvolution8u( + uint8_t* C10_RESTRICT lineOut, + const uint8_t* C10_RESTRICT lineIn, + int64_t xsize, + int64_t ids_min, + int64_t ids_size, + const int16_t* k, + unsigned int coefs_precision, + int64_t num_channels) { + + // Interpolation vertical pass processing one line. + // - We process x-axis data with blocks of 8, 2 and 1 + // - We split the size of weight vector for a given output index as a sum: K = n * 2 + m. + + // xsize = output width, also equals to input width + // ids_size = interpolation size + // ids_min = input y start index + const auto stride = num_channels * sizeof(uint8_t); + + TORCH_INTERNAL_ASSERT(stride == 3 || stride == 4); + + const int64_t data_size = xsize * stride; + const int64_t data_stride = stride; + constexpr auto vec_size = 256 / 8; + + const auto initial = _mm_set1_epi32(1 << (coefs_precision - 1)); + const auto initial_256 = _mm256_set1_epi32(1 << (coefs_precision - 1)); + const auto zero = _mm_setzero_si128(); + const auto zero_256 = _mm256_setzero_si256(); + + int64_t j = 0; + // block 8 + const auto b8_usable_vec_stride = (vec_size / data_stride) * data_stride; + for (; j < data_size - vec_size; j += b8_usable_vec_stride) { + auto sss0 = initial_256; + auto sss1 = initial_256; + auto sss2 = initial_256; + auto sss3 = initial_256; + int64_t i = 0; + const auto * lineIn_min = lineIn + j + ids_min; + + for (; i < ids_size - 1; i += 2) { + // Load 2 values from weight vector + auto mmk = _mm256_set1_epi32(*(int32_t*)&k[i]); + + // RGBA: Load 8 pixels per line + // source1 = [ + // r0 g0 b0 a0 r1 g1 b1 a1 r2 g2 b2 a2 r3 g3 b3 a3 + // r4 g4 b4 a4 r5 g5 b5 a5 r6 g6 b6 a6 r7 g7 b7 a7 + // ] + // RGB: Load 10 pixels per line (however we can process only 8 pixels): + // source1 = [ + // r0 g0 b0 r1 g1 b1 r2 g2 b2 r3 g3 b3 r4 g4 b4 r5 + // r4 g4 b4 r5 g5 b5 r6 g6 b6 r7 g7 b7 r8 g8 b8 r9 + // ] + auto source1 = + _mm256_loadu_si256((__m256i*)(lineIn_min + data_size * i)); + auto source2 = + _mm256_loadu_si256((__m256i*)(lineIn_min + data_size * (i + 1))); + + // Interleave source1 and source2 from the low half of each 128-bit lane + // and cast the result to epi16 + // RGBA: pix1 = [ + // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0 + // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 a1 0 A1 0 + // ] + // RGB: pix1 = [ + // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0 + // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 0 0 0 0 + // ] + auto source_lo = _mm256_unpacklo_epi8(source1, source2); + auto pix1 = _mm256_unpacklo_epi8(source_lo, zero_256); + // Compute output value as + // C += w0 * c0 + w1 * C0 + // C += w0 * c1 + w1 * C1 for each channel in 32-bit precision + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk)); + + // RGBA: pix2 = [ + // r2 0 R2 0 g2 0 G2 0 b2 0 B2 0 a2 0 A2 0 + // r3 0 R3 0 g3 0 G3 0 b3 0 B3 0 a3 0 A3 0 + // ] + // RGB: pix2 = [ + // r2 0 R2 0 g2 0 G2 0 b2 0 B2 0 0 0 0 0 + // r3 0 R3 0 g3 0 G3 0 b3 0 B3 0 0 0 0 0 + // ] + auto pix2 = _mm256_unpackhi_epi8(source_lo, zero_256); + // Compute output value as + // C += w0 * c2 + w1 * C2 + // C += w0 * c3 + w1 * C3 for each channel in 32-bit precision + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk)); + + // Same as above for the high half of each 128-bit lane + auto source_hi = _mm256_unpackhi_epi8(source1, source2); + auto pix3 = _mm256_unpacklo_epi8(source_hi, zero_256); + sss2 = _mm256_add_epi32(sss2, _mm256_madd_epi16(pix3, mmk)); + auto pix4 = _mm256_unpackhi_epi8(source_hi, zero_256); + sss3 = _mm256_add_epi32(sss3, _mm256_madd_epi16(pix4, mmk)); + } + // Same processing as above but with a single weight value + for (; i < ids_size; i += 1) { + auto mmk = _mm256_set1_epi32(k[i]); + + auto source1 = _mm256_loadu_si256((__m256i*)(lineIn_min + i * data_size)); + + auto source_lo = _mm256_unpacklo_epi8(source1, zero_256); + auto pix1 = _mm256_unpacklo_epi8(source_lo, zero_256); + sss0 = _mm256_add_epi32(sss0, _mm256_madd_epi16(pix1, mmk)); + auto pix2 = _mm256_unpackhi_epi8(source_lo, zero_256); + sss1 = _mm256_add_epi32(sss1, _mm256_madd_epi16(pix2, mmk)); + + auto source_hi = _mm256_unpackhi_epi8(source1, zero_256); + auto pix3 = _mm256_unpacklo_epi8(source_hi, _mm256_setzero_si256()); + sss2 = _mm256_add_epi32(sss2, _mm256_madd_epi16(pix3, mmk)); + auto pix4 = _mm256_unpackhi_epi8(source_hi, _mm256_setzero_si256()); + sss3 = _mm256_add_epi32(sss3, _mm256_madd_epi16(pix4, mmk)); + } + // Convert fixed point values back to integers (truncating) + sss0 = _mm256_srai_epi32(sss0, coefs_precision); + sss1 = _mm256_srai_epi32(sss1, coefs_precision); + sss2 = _mm256_srai_epi32(sss2, coefs_precision); + sss3 = _mm256_srai_epi32(sss3, coefs_precision); + // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation + // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d) + sss0 = _mm256_packs_epi32(sss0, sss1); + sss2 = _mm256_packs_epi32(sss2, sss3); + // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation + // (a a b b c c d d) -> (a b c d) + sss0 = _mm256_packus_epi16(sss0, sss2); + + // Stores 32 bytes + _mm256_storeu_si256((__m256i*)(lineOut + j), sss0); + } + + // TODO: Do we also need block 4 ??? + // block 2 + const auto b2_usable_vec_stride = (8 / data_stride) * data_stride; + for (; j < data_size - vec_size / 4; j += b2_usable_vec_stride) { + auto sss0 = initial; + auto sss1 = initial; + int64_t i = 0; + const auto * lineIn_min = lineIn + j + ids_min; + + for (; i < ids_size - 1; i += 2) { + // Load 2 values from weight vector + // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ] + auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]); + + // Load 2 pixels per line + // RGBA: source1 = [ + // r0 g0 b0 a0 r1 g1 b1 a1 0 0 0 0 0 0 0 0 + // ] + // RGB: source1 = [ + // r0 g0 b0 r1 g1 b1 r2 g2 0 0 0 0 0 0 0 0 + // ] + auto source1 = _mm_loadl_epi64((__m128i *) (lineIn_min + i * data_size)); + auto source2 = _mm_loadl_epi64((__m128i *) (lineIn_min + (i + 1) * data_size)); + // Interleave source1 and source2 and cast the result to epi16 + // RGBA: pix = [ + // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0 + // ] + // RGB: pix = [ + // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0 + // ] + auto source = _mm_unpacklo_epi8(source1, source2); + auto pix = _mm_unpacklo_epi8(source, zero); + // Compute output value as C += w0 * c0 + w1 * C0 for each channel in 32-bit precision + sss0 = _mm_add_epi32(sss0, _mm_madd_epi16(pix, mmk)); + // RGBA: pix = [ + // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 a1 0 A1 0 + // ] + // RGB: pix = [ + // r1 0 R1 0 g1 0 G1 0 b1 0 B1 0 0 0 0 0 + // ] + pix = _mm_unpackhi_epi8(source, zero); + // Compute output value as C += w0 * c1 + w1 * C1 for each channel in 32-bit precision + sss1 = _mm_add_epi32(sss1, _mm_madd_epi16(pix, mmk)); + } + // Same processing as above but with a single weight value + for (; i < ids_size; i += 1) { + auto mmk = _mm_set1_epi32(k[i]); + + auto source1 = _mm_loadl_epi64((__m128i*) (lineIn_min + i * data_size)); + + auto source = _mm_unpacklo_epi8(source1, zero); + auto pix1 = _mm_unpacklo_epi8(source, zero); + sss0 = _mm_add_epi32(sss0, _mm_madd_epi16(pix1, mmk)); + auto pix2 = _mm_unpackhi_epi8(source, zero); + sss1 = _mm_add_epi32(sss1, _mm_madd_epi16(pix2, mmk)); + } + // Convert fixed point values back to integers (truncating) + sss0 = _mm_srai_epi32(sss0, coefs_precision); + sss1 = _mm_srai_epi32(sss1, coefs_precision); + // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation + // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d) + sss0 = _mm_packs_epi32(sss0, sss1); + // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation + // (a a b b c c d d) -> (a b c d) + sss0 = _mm_packus_epi16(sss0, sss0); + // Store 2 pixels to the output + _mm_storel_epi64((__m128i*)(lineOut + j), sss0); + } + + // block 1 + const auto b1_usable_vec_stride = (4 / data_stride) * data_stride; + const auto i32_aligned = num_channels == 4; + for (; j < data_size - 4; j += b1_usable_vec_stride) { + auto sss = initial; + int64_t i = 0; + const auto * lineIn_min = lineIn + j + ids_min; + + for (; i < ids_size - 1; i += 2) { + // Load 2 values from weight vector + // mmk = [wl_0 wh_0 wl_1 wh_1 wl_0 wh_0 wl_1 wh_1 ... ] + auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]); + + // Load one pixel per line + // RGBA: source1 = [ + // r0 g0 b0 a0 0 0 0 0 0 0 0 0 0 0 0 0 + // ] + // RGB: source1 = [ + // r0 g0 b0 r1 0 0 0 0 0 0 0 0 0 0 0 0 + // ] + auto source1 = mm_cvtsi32_si128(lineIn_min + i * data_size, i32_aligned); + auto source2 = mm_cvtsi32_si128(lineIn_min + (i + 1) * data_size, i32_aligned); + + // Interleave source1 and source2 and cast the result to epi16 + // RGBA: pix = [ + // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 a0 0 A0 0 + // ] + // RGB: pix = [ + // r0 0 R0 0 g0 0 G0 0 b0 0 B0 0 0 0 0 0 + // ] + auto source = _mm_unpacklo_epi8(source1, source2); + auto pix = _mm_unpacklo_epi8(source, zero); + // Compute output value as C += w0 * c0 + w1 * C0 for each channel in 32-bit precision + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + + for (; i < ids_size; i++) { + auto mmk = _mm_set1_epi32(k[i]); + auto pix = mm_cvtepu8_epi32(lineIn_min + i * data_size, i32_aligned); + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + sss = _mm_srai_epi32(sss, coefs_precision); + sss = _mm_packs_epi32(sss, zero); + sss = _mm_packus_epi16(sss, zero); + + auto o = _mm_cvtsi128_si32(sss); + + // Here we write 4 bytes to the output even if num_channels < 4, e.g o = {r,g,b,X} for num_channels=3 + // It is OK to write 4th byte (e.g. X) as on the next step we will overwrite it with new data. + // We also won't go out of bounds of lineOut memory allocation + std::memcpy(lineOut + j, (uint8_t *) &o, 4); + } + + for (; j < data_size; j += data_stride) { + auto sss = initial; + int64_t i = 0; + const auto * lineIn_min = lineIn + j + ids_min; + // For RGBA we can use (ids_size - 1) as tighter limit but for RGB we can read outside memory boundary + // for the last remaining line + for (; i < ids_size - 2; i += 2) { + // Load two coefficients at once + auto mmk = _mm_set1_epi32(*(int32_t*)&k[i]); + + // Load 2 lines + auto source1 = mm_cvtsi32_si128(lineIn_min + i * data_size, i32_aligned); + auto source2 = mm_cvtsi32_si128(lineIn_min + (i + 1) * data_size, i32_aligned); + + auto source = _mm_unpacklo_epi8(source1, source2); + auto pix = _mm_unpacklo_epi8(source, zero); + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + + // Same processing as above but with a single weight value + for (; i < ids_size; i++) { + auto mmk = _mm_set1_epi32(k[i]); + + const uint8_t * p = lineIn_min + i * data_size; + __m128i pix; + // There is no much perf gain using more detailed condition like + // num_channels == 3 && ids_min + j + data_size * i + 4 >= in_max_size + // const int64_t in_max_size = data_size * in_ysize; + if (num_channels == 3) { + uint8_t input[4]; + std::memcpy(input, p, 3); + pix = mm_cvtepu8_epi32(input, true); + } else { + pix = mm_cvtepu8_epi32(p, true); + } + sss = _mm_add_epi32(sss, _mm_madd_epi16(pix, mmk)); + } + + // Convert fixed point values back to integers (truncating) + sss = _mm_srai_epi32(sss, coefs_precision); + // Convert packed signed 32-bit integers to packed 16-bit integers using signed saturation + // (a a a a b b b b c c c c d d d d) -> (a a b b c c d d) + sss = _mm_packs_epi32(sss, zero); + // Convert packed signed 16-bit integers to packed 8-bit integers using unsigned saturation + // (a a b b c c d d) -> (a b c d) + sss = _mm_packus_epi16(sss, zero); + // Store one pixel to the output + auto o = _mm_cvtsi128_si32(sss); + if (num_channels == 3 && C10_UNLIKELY(j + 4 >= data_size)) { + std::memcpy(lineOut + j, (uint8_t *) &o, 3); + } else { + std::memcpy(lineOut + j, (uint8_t *) &o, 4); + } + } +} + +} // anonymous namespace +#endif // CPU_CAPABILITY_AVX2 diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernelNEONAntialias.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernelNEONAntialias.h new file mode 100644 index 0000000000000000000000000000000000000000..e306bf4c0f6d325eac5a693f52b531345f3de959 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleKernelNEONAntialias.h @@ -0,0 +1,381 @@ +// NEON-optimized uint8 bilinear resize with antialiasing for aarch64. +// +// This is the NEON counterpart of UpSampleKernelAVXAntialias.h. +// It only supports num_channels == 3 with channels-last input. + +#pragma once +#if defined(__aarch64__) + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace { + +// Emulate SSE _mm_madd_epi16: multiply 8 int16 pairs element-wise, then add +// adjacent 32-bit products pairwise, producing 4 int32 results. +// [a0*b0+a1*b1, a2*b2+a3*b3, a4*b4+a5*b5, a6*b6+a7*b7] +inline int32x4_t neon_madd_s16(int16x8_t a, int16x8_t b) { + int32x4_t prod_low = vmull_s16(vget_low_s16(a), vget_low_s16(b)); + int32x4_t prod_high = vmull_s16(vget_high_s16(a), vget_high_s16(b)); + return vpaddq_s32(prod_low, prod_high); +} + +// Interpolation horizontal pass: compute x-axis interpolation outputs. +// +// Input data is interleaved RGB: +// input = [r0, g0, b0, r1, g1, b1, r2, g2, b2, ...] +// Weights are float values rescaled to int16: +// weights[i] = [w[i, 0], w[i, 1], ..., w[i, K-1]] +// For each output pixel i, we compute: +// oR[i] = r[xmin[i]] * w[i,0] + ... + r[xmin[i]+K-1] * w[i,K-1] +// oG[i] = g[xmin[i]] * w[i,0] + ... + g[xmin[i]+K-1] * w[i,K-1] +// oB[i] = b[xmin[i]] * w[i,0] + ... + b[xmin[i]+K-1] * w[i,K-1] +// +// Processes one row at a time. +void NeonResampleHorizontal(const at::Tensor& unpacked_output, + const at::Tensor& unpacked_input, + int ksize, + const std::vector& horiz_indices_weights, + unsigned int horiz_weights_precision) { + const auto* kk = (const int16_t*)(horiz_indices_weights[3].const_data_ptr()); + + auto xout = unpacked_output.size(2); + auto yin = unpacked_output.size(1); + auto xin = unpacked_input.size(2); + const auto num_channels = unpacked_input.size(0); + TORCH_INTERNAL_ASSERT(num_channels == 3); + + const int64_t* idx_ptr_xmin = horiz_indices_weights[0].const_data_ptr(); + const int64_t* idx_ptr_size = horiz_indices_weights[1].const_data_ptr(); + + uint8_t* output_p = unpacked_output.data_ptr(); + const uint8_t* input_p = unpacked_input.const_data_ptr(); + + auto xout_stride = xout * num_channels; + auto xin_stride = xin * num_channels; + + for (int64_t yy = 0; yy < yin; yy++) { + uint8_t* C10_RESTRICT lineOut = output_p + yy * xout_stride; + const uint8_t* C10_RESTRICT lineIn = input_p + yy * xin_stride; + const int32_t initial_val = 1 << (horiz_weights_precision - 1); + + // Horizontal convolution for a single row. + // + // For each output pixel out_x, computes the weighted sum of ids_size input + // pixels using the weight vector k[]. Uses vld3_u8 to load 8 interleaved RGB + // pixels and deinterleave them into separate R, G, B vectors. This avoids + // the shuffle masks needed by the AVX2 path. + // + // The weight vector is split as: ids_size = num_blocks_8 * 8 + remainder. + // We process 8 weights in a vectorized loop, then handle remaining weights + // in a scalar cleanup loop. Accumulators are kept per-channel in int32 to + // avoid overflow. + for (int64_t out_x = 0; out_x < xout; out_x++) { + // ids_min is a byte offset (pre-multiplied by num_channels) + const int64_t ids_min = idx_ptr_xmin[out_x]; + const int64_t ids_size = idx_ptr_size[out_x]; + const int16_t* k = &kk[out_x * ksize]; + const uint8_t* lineIn_min = lineIn + ids_min; + + int32x4_t acc_r = vdupq_n_s32(0); + int32x4_t acc_g = vdupq_n_s32(0); + int32x4_t acc_b = vdupq_n_s32(0); + + int64_t i = 0; + + // Block 8: load 8 RGB pixels with vld3, deinterleave, widen to int16, + // multiply-accumulate with 8 weights per channel. + // Each vmlal_s16 accumulates 4 products; calling it on the low and high + // halves puts all 8 products into 4 int32 lanes, reduced later by + // vaddvq_s32. + for (; i + 8 <= ids_size; i += 8) { + uint8x8x3_t rgb = vld3_u8(lineIn_min + num_channels * i); + int16x8_t weights = vld1q_s16(&k[i]); + + int16x8_t r16 = vreinterpretq_s16_u16(vmovl_u8(rgb.val[0])); + int16x8_t g16 = vreinterpretq_s16_u16(vmovl_u8(rgb.val[1])); + int16x8_t b16 = vreinterpretq_s16_u16(vmovl_u8(rgb.val[2])); + + acc_r = vmlal_s16(acc_r, vget_low_s16(r16), vget_low_s16(weights)); + acc_r = vmlal_s16(acc_r, vget_high_s16(r16), vget_high_s16(weights)); + acc_g = vmlal_s16(acc_g, vget_low_s16(g16), vget_low_s16(weights)); + acc_g = vmlal_s16(acc_g, vget_high_s16(g16), vget_high_s16(weights)); + acc_b = vmlal_s16(acc_b, vget_low_s16(b16), vget_low_s16(weights)); + acc_b = vmlal_s16(acc_b, vget_high_s16(b16), vget_high_s16(weights)); + } + + // Block 4: handle 4 pixels that didn't fit in a block of 8 + // We also use vld3_u8 here, which still loads 8 pixels, but we only use + // the lower half - so the computation is correct. + // On all rows except the last one, reading 8 pixels is safe (the tensors + // are channels-last). But on the last row, we have to be careful not to + // read past the buffer, hence the extra boundary check. + const uint8_t* block_of_4_safe_load_end = input_p + yin * xin_stride - 24; + for (; i + 4 <= ids_size && lineIn_min + num_channels * i <= block_of_4_safe_load_end; i += 4) { + uint8x8x3_t rgb = vld3_u8(lineIn_min + num_channels * i); + int16x4_t weights4 = vld1_s16(&k[i]); + + int16x4_t r16 = vget_low_s16(vreinterpretq_s16_u16(vmovl_u8(rgb.val[0]))); + int16x4_t g16 = vget_low_s16(vreinterpretq_s16_u16(vmovl_u8(rgb.val[1]))); + int16x4_t b16 = vget_low_s16(vreinterpretq_s16_u16(vmovl_u8(rgb.val[2]))); + + acc_r = vmlal_s16(acc_r, r16, weights4); + acc_g = vmlal_s16(acc_g, g16, weights4); + acc_b = vmlal_s16(acc_b, b16, weights4); + } + + // Horizontal reduction + rounding bias + int32_t sum_r = vaddvq_s32(acc_r) + initial_val; + int32_t sum_g = vaddvq_s32(acc_g) + initial_val; + int32_t sum_b = vaddvq_s32(acc_b) + initial_val; + + // Scalar cleanup for remaining pixels + for (; i < ids_size; i++) { + int16_t w = k[i]; + const uint8_t* p = lineIn_min + num_channels * i; + sum_r += w * p[0]; + sum_g += w * p[1]; + sum_b += w * p[2]; + } + + // Right-shift and clamp to [0, 255] + uint8_t* out = lineOut + num_channels * out_x; + out[0] = static_cast(std::clamp(sum_r >> horiz_weights_precision, 0, 255)); + out[1] = static_cast(std::clamp(sum_g >> horiz_weights_precision, 0, 255)); + out[2] = static_cast(std::clamp(sum_b >> horiz_weights_precision, 0, 255)); + } + } +} + +// Interpolation vertical pass: compute y-axis interpolation outputs. +// +// Input data is interleaved RGB: +// input = [r0, g0, b0, r1, g1, b1, ...] +// For each output row yy, we compute a weighted sum of ids_size input rows: +// oC[x] = C[ymin[yy] * xstride + x] * w[yy,0] + ... + C[(ymin[yy]+K-1) * xstride + x] * w[yy,K-1] +// for each channel C in {R, G, B} and each horizontal position x. +void NeonResampleVertical(const at::Tensor& unpacked_output, + const at::Tensor& unpacked_input, + int ksize, + const std::vector& vert_indices_weights, + unsigned int vert_weights_precision) { + const auto* kk = (const int16_t*)(vert_indices_weights[3].const_data_ptr()); + + const int64_t* idx_ptr_xmin = vert_indices_weights[0].const_data_ptr(); + const int64_t* idx_ptr_size = vert_indices_weights[1].const_data_ptr(); + + uint8_t* output_p = unpacked_output.data_ptr(); + const uint8_t* input_p = unpacked_input.const_data_ptr(); + + auto xout = unpacked_output.size(2); + auto yout = unpacked_output.size(1); + const auto num_channels = unpacked_input.size(0); + TORCH_INTERNAL_ASSERT(num_channels == unpacked_output.size(0)); + + const int64_t data_size = xout * num_channels; + + for (const auto yy : c10::irange(yout)) { + const auto* k = &kk[yy * ksize]; + auto ids_min = idx_ptr_xmin[yy]; + auto ids_size = idx_ptr_size[yy]; + + uint8_t* C10_RESTRICT lineOut = output_p + yy * data_size; + const int32_t initial_val = 1 << (vert_weights_precision - 1); + const int32x4_t initial = vdupq_n_s32(initial_val); + + // Vertical convolution for one output row. + // Computes a weighted sum of ids_size input rows for all x positions. + // + // The data is treated as a flat byte array of size xout * num_channels. + // We process 16 bytes at a time in the NEON path, then fall back to scalar + // for the remainder. The vertical pass doesn't need channel deinterleaving + // because the same weight applies to all channels at a given (x, y) position. + // + // To process 2 weights at a time, we interleave pixels from two input rows + // using vzipq_u8, then use neon_madd_s16 (which pairs adjacent int16 values, + // multiplies, and adds) so that each pair [pixel_row_i, pixel_row_i+1] is + // multiplied by [w_i, w_i+1] and summed in one operation. + int64_t j = 0; + + // Process 16 bytes at a time using 4 accumulators (sss0..sss3), + // each holding 4 int32 partial sums. + for (; j + 16 <= data_size; j += 16) { + int32x4_t sss0 = initial; + int32x4_t sss1 = initial; + int32x4_t sss2 = initial; + int32x4_t sss3 = initial; + + const uint8_t* lineIn_min = input_p + j + ids_min; + + // Process 2 weights at a time by interleaving rows. + // For weights w0, w1 and pixel bytes from row_i and row_{i+1}: + // mmk = [w0, w1, w0, w1, w0, w1, w0, w1] + // vzipq interleaves: [r0_0, r1_0, r0_1, r1_1, ...] (from 2 rows) + // neon_madd_s16 computes: r0_0*w0 + r1_0*w1, r0_1*w0 + r1_1*w1, ... + int64_t i = 0; + for (; i + 1 < ids_size; i += 2) { + int16_t w0 = k[i]; + int16_t w1 = k[i + 1]; + int16x8_t mmk = {w0, w1, w0, w1, w0, w1, w0, w1}; + + uint8x16_t src1 = vld1q_u8(lineIn_min + i * data_size); + uint8x16_t src2 = vld1q_u8(lineIn_min + (i + 1) * data_size); + + uint8x16x2_t interleaved = vzipq_u8(src1, src2); + + int16x8_t pix0 = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(interleaved.val[0]))); + int16x8_t pix1 = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(interleaved.val[0]))); + int16x8_t pix2 = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(interleaved.val[1]))); + int16x8_t pix3 = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(interleaved.val[1]))); + + sss0 = vaddq_s32(sss0, neon_madd_s16(pix0, mmk)); + sss1 = vaddq_s32(sss1, neon_madd_s16(pix1, mmk)); + sss2 = vaddq_s32(sss2, neon_madd_s16(pix2, mmk)); + sss3 = vaddq_s32(sss3, neon_madd_s16(pix3, mmk)); + } + + // Handle remaining single weight (when ids_size is odd) + for (; i < ids_size; i++) { + int16x8_t mmk = vdupq_n_s16(k[i]); + + uint8x16_t src = vld1q_u8(lineIn_min + i * data_size); + + int16x8_t pix_lo = vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(src))); + int16x8_t pix_hi = vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(src))); + + sss0 = vaddq_s32(sss0, vmull_s16(vget_low_s16(pix_lo), vget_low_s16(mmk))); + sss1 = vaddq_s32(sss1, vmull_s16(vget_high_s16(pix_lo), vget_high_s16(mmk))); + sss2 = vaddq_s32(sss2, vmull_s16(vget_low_s16(pix_hi), vget_low_s16(mmk))); + sss3 = vaddq_s32(sss3, vmull_s16(vget_high_s16(pix_hi), vget_high_s16(mmk))); + } + + // Right-shift accumulators by coefs_precision to convert fixed-point -> int + int32x4_t shift = vdupq_n_s32(-static_cast(vert_weights_precision)); + sss0 = vshlq_s32(sss0, shift); + sss1 = vshlq_s32(sss1, shift); + sss2 = vshlq_s32(sss2, shift); + sss3 = vshlq_s32(sss3, shift); + + // Narrow int32 -> int16 (with saturation), then int16 -> uint8 (with + // saturation), clamping to [0, 255] + int16x8_t narrow_lo = vcombine_s16(vqmovn_s32(sss0), vqmovn_s32(sss1)); + int16x8_t narrow_hi = vcombine_s16(vqmovn_s32(sss2), vqmovn_s32(sss3)); + + // Store 16 output bytes + vst1_u8(lineOut + j, vqmovun_s16(narrow_lo)); + vst1_u8(lineOut + j + 8, vqmovun_s16(narrow_hi)); + } + + // Scalar fallback for remaining bytes + for (; j < data_size; j++) { + int32_t sss = initial_val; + const uint8_t* lineIn_min = input_p + j + ids_min; + + for (int64_t i = 0; i < ids_size; i++) { + sss += k[i] * static_cast(lineIn_min[i * data_size]); + } + + sss >>= vert_weights_precision; + lineOut[j] = static_cast(std::clamp(sss, 0, 255)); + } + } +} + +// Main entry point for NEON-accelerated uint8 bilinear resize. +// +// Only supports num_channels == 3 with channels-last memory format. +// Mirrors upsample_avx_bilinear_bicubic_uint8 but uses NEON intrinsics and +// works directly on interleaved RGB data (no unpack/pack step needed). +// +// Weights are computed as int16 values by compute_index_ranges_int16_weights +// with align_i32=false (no int32 alignment padding needed, unlike AVX2 which +// processes pixels as 4-byte RGBA units). +template +void upsample_neon_bilinear_bicubic_uint8(const at::Tensor& input_, + const at::Tensor& output, + bool align_corners, + const scale_type& scales, + bool antialias) { + auto batch_size = input_.size(0); + auto num_channels = input_.size(1); + auto xin = input_.size(3); + auto yin = input_.size(2); + auto xout = output.size(3); + auto yout = output.size(2); + + if (xin == xout && yin == yout) { + output.copy_(input_); + return; + } + + TORCH_INTERNAL_ASSERT(num_channels == 3); + TORCH_INTERNAL_ASSERT(output.is_contiguous(at::MemoryFormat::ChannelsLast)); + + auto input = input_.contiguous(at::MemoryFormat::ChannelsLast); + + auto need_horizontal = xout != xin; + auto need_vertical = yout != yin; + + int ksize_horiz = 0, ksize_vert = 0; + std::vector horiz_indices_weights, vert_indices_weights; + unsigned int horiz_weights_precision = 0, vert_weights_precision = 0; + + if (need_horizontal) { + int interp_dim = 3; + std::tie(horiz_indices_weights, ksize_horiz, horiz_weights_precision) = F::compute_index_ranges_int16_weights( + /*input_size=*/xin, + /*output_size=*/xout, + /*stride=*/num_channels, + /*ndims=*/4, + /*reshape_dim=*/interp_dim, + /*align_corners=*/align_corners, + /*opt_scale=*/scales[interp_dim - 2], + /*antialias=*/antialias, + /*align_i32=*/false); + } + + if (need_vertical) { + int interp_dim = 2; + std::tie(vert_indices_weights, ksize_vert, vert_weights_precision) = F::compute_index_ranges_int16_weights( + /*input_size=*/yin, + /*output_size=*/yout, + /*stride=*/num_channels * xout, + /*ndims=*/4, + /*reshape_dim=*/interp_dim, + /*align_corners=*/align_corners, + /*opt_scale=*/scales[interp_dim - 2], + /*antialias=*/antialias, + /*align_i32=*/false); + } + + at::Tensor buffer_horiz; + if (need_horizontal && need_vertical) { + buffer_horiz = at::empty({num_channels, yin, xout}, input.options()); + } + + for (const auto i : c10::irange(batch_size)) { + at::Tensor input_slice = input[i]; + + if (need_horizontal) { + at::Tensor horiz_output = need_vertical ? buffer_horiz : output[i]; + NeonResampleHorizontal(horiz_output, input_slice, ksize_horiz, horiz_indices_weights, horiz_weights_precision); + if (need_vertical) { + input_slice = horiz_output; + } + } + if (need_vertical) { + NeonResampleVertical(output[i], input_slice, ksize_vert, vert_indices_weights, vert_weights_precision); + } + } +} + +} // anonymous namespace + +#endif // __aarch64__ diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleMoreKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleMoreKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a05d7149789903b78d5a2fedf370a3b70d320f77 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/UpSampleMoreKernel.cpp @@ -0,0 +1,797 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +using scale_t = std::vector>; + +template , + typename std::enable_if_t || !std::is_same_v, int> = 0> +void inline nearest_channels_last_acc(acc_t* gin, scalar_t* gout, int64_t size) { + static_assert(std::is_same_v, + "acc data type of Upsample backward should be same as scalar_t for float or double on CPU."); + using Vec = Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec gin_vec = Vec::loadu(gin + d) + Vec::loadu(gout + d); + gin_vec.store(gin + d); + } + for (; d < size; d++) { + gin[d] += gout[d]; + } +} + +template , + typename std::enable_if_t && std::is_same_v, int> = 0> +void inline nearest_channels_last_acc(acc_t* gin, scalar_t* gout, int64_t size) { + using bVec = Vectorized; + using fVec = Vectorized; + int64_t d = 0; + for (; d < size - (size % bVec::size()); d += bVec::size()) { + bVec gout_bvec = bVec::loadu(gout + d); + auto [gout_fvec0, gout_fvec1] = convert_to_float(gout_bvec); + fVec gin_fvec0 = fVec::loadu(gin + d) + gout_fvec0; + fVec gin_fvec1 = fVec::loadu(gin + d + fVec::size()) + gout_fvec1; + gin_fvec0.store(gin + d); + gin_fvec1.store(gin + d + fVec::size()); + } + for (; d < size; d++) { + gin[d] += gout[d]; + } +} + +template , + typename std::enable_if_t || !std::is_same_v, int> = 0> +void inline linear_channels_last_acc(acc_t* gin, const scalar_t* gout, acc_t w, int64_t size) { + static_assert(std::is_same_v, + "acc data type of Upsample backward should be same as scalar_t for float or double on CPU."); + using Vec = Vectorized; + int64_t d = 0; + for (; d < size - (size % Vec::size()); d += Vec::size()) { + Vec gin_vec = Vec::loadu(gin + d) + Vec(w) * Vec::loadu(gout + d); + gin_vec.store(gin + d); + } + for (; d < size; d++) { + gin[d] += w * gout[d]; + } +} + +template , + typename std::enable_if_t && std::is_same_v, int> = 0> +void inline linear_channels_last_acc(acc_t* gin, const scalar_t* gout, acc_t w, int64_t size) { + using bVec = Vectorized; + using fVec = Vectorized; + int64_t d = 0; + for (; d < size - (size % bVec::size()); d += bVec::size()) { + bVec gout_bvec = bVec::loadu(gout + d); + auto [gout_fvec0, gout_fvec1] = convert_to_float(gout_bvec); + fVec gin_fvec0 = fVec::loadu(gin + d) + fVec(w) * gout_fvec0; + fVec gin_fvec1 = fVec::loadu(gin + d + fVec::size()) + fVec(w) * gout_fvec1; + gin_fvec0.store(gin + d); + gin_fvec1.store(gin + d + fVec::size()); + } + for (; d < size; d++) { + gin[d] += w * gout[d]; + } +} + +template +void cpu_upsample_nearest_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + const scale_type& scales) { + TORCH_CHECK(grad_input_.dtype() == grad_output_.dtype(), "expected dtype ", grad_output_.dtype(), + " for `grad_input` but got dtype ", grad_input_.dtype()); + + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + auto input_sizes = grad_input.sizes().vec(); + auto output_sizes = grad_output.sizes().vec(); + auto ndim = input_sizes.size(); + + // treat nbatch and channels as one dimension + int64_t channels = input_sizes[0] * input_sizes[1]; + int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = (ndim >= 4) ? input_sizes[ndim - 2] : 1; + int64_t output_height = (ndim >= 4) ? output_sizes[ndim - 2] : 1; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + + int64_t output_slice_size = output_depth * output_height * output_width; + int64_t input_slice_size = input_depth * input_height * input_width; + + using opmath_t = at::opmath_type; + auto loop1d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + for (const auto c : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? c * input_slice_size : 0; + for (const auto ow : c10::irange(output_width)) { + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[0]); + int64_t output_offset = c * output_slice_size + ow; + acc_data_ptr[input_offset + iw] += grad_output_data[output_offset]; + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + c * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + auto loop2d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + for (const auto c : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? c * input_slice_size : 0; + for (const auto oh : c10::irange(output_height)) { + int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[0]); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[1]); + int64_t output_offset = c * output_slice_size + oh * output_width + ow; + acc_data_ptr[input_offset + ih * input_width + iw] += grad_output_data[output_offset]; + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + c * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + auto loop3d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + for (const auto c : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? c * input_slice_size : 0; + for (const auto od : c10::irange(output_depth)) { + int64_t id = nearest_idx_fn(od, input_depth, output_depth, scales[0]); + for (const auto oh : c10::irange(output_height)) { + int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[1]); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[2]); + int64_t output_offset = c * output_slice_size + + od * output_height * output_width + oh * output_width + ow; + acc_data_ptr[input_offset + id * input_height * input_width + ih * input_width + iw] += + grad_output_data[output_offset]; + } + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + c * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + if (ndim == 3) { + // upsample nearest 1d + at::parallel_for(0, channels, at::internal::GRAIN_SIZE / output_slice_size, loop1d); + } else if (ndim == 4) { + // upsample nearest 2d + at::parallel_for(0, channels, at::internal::GRAIN_SIZE / output_slice_size , loop2d); + } else { + // upsample nearest 3d + TORCH_INTERNAL_ASSERT(ndim == 5); + at::parallel_for(0, channels, at::internal::GRAIN_SIZE / output_slice_size, loop3d); + } + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_upsample_nearest_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + const scale_type& scales) { + TORCH_CHECK(grad_input_.dtype() == grad_output_.dtype(), "expected dtype ", grad_output_.dtype(), + " for `grad_input` but got dtype ", grad_input_.dtype()); + + auto ndim = grad_output_.ndimension(); + TORCH_CHECK(ndim >=4 && ndim <= 5, "Upsample with NHWC format supports tensors with 4 or 5 dims.") + + auto channels_last_memory_format = ndim == 4 ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::ChannelsLast3d; + auto grad_output = grad_output_.contiguous(channels_last_memory_format); + auto grad_input = grad_input_.contiguous(channels_last_memory_format); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + auto input_sizes = grad_input.sizes().vec(); + auto output_sizes = grad_output.sizes().vec(); + + int64_t num_batches = input_sizes[0]; + int64_t channels = input_sizes[1]; + int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = input_sizes[ndim - 2]; + int64_t output_height = output_sizes[ndim - 2]; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + int64_t input_slice_size = input_depth * input_height * input_width * channels; + + using opmath_t = at::opmath_type; + auto loop2d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + for (const auto n : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? n * input_slice_size : 0; + for (const auto oh : c10::irange(output_height)) { + int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[0]); + for (const auto ow : c10::irange(output_width)) { + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[1]); + const scalar_t* grad_output_ptr = grad_output_data + + (n * output_height * output_width + oh * output_width + ow) * channels; + opmath_t* buffer_ptr = acc_data_ptr + input_offset + (ih * input_width + iw) * channels; + nearest_channels_last_acc(buffer_ptr, grad_output_ptr, channels); + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + n * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + + }; + + auto loop3d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + for (const auto n : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? n * input_slice_size : 0; + for (int64_t od = 0; od < output_depth; od++) { + int64_t id = nearest_idx_fn(od, input_depth, output_depth, scales[0]); + for (int64_t oh = 0; oh < output_height; oh++) { + int64_t ih = nearest_idx_fn(oh, input_height, output_height, scales[1]); + for (int64_t ow = 0; ow < output_width; ow++) { + int64_t iw = nearest_idx_fn(ow, input_width, output_width, scales[2]); + const scalar_t* grad_output_ptr = grad_output_data + + (n * output_depth * output_height * output_width + + od * output_height * output_width + oh * output_width + ow) * channels; + + opmath_t* buffer_ptr = acc_data_ptr + input_offset + (id * input_height * input_width + ih * input_width + iw) * channels; + nearest_channels_last_acc(buffer_ptr, grad_output_ptr, channels); + } + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + n * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + + }; + + if (ndim == 4) { + // upsample nearest 2d + at::parallel_for(0, num_batches, 0, loop2d); + } else { + // upsample nearest 3d + TORCH_INTERNAL_ASSERT(ndim == 5); + at::parallel_for(0, num_batches, 0, loop3d); + } + + if (!grad_input_.is_contiguous(channels_last_memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void upsample_nearest1d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + std::optional scales_w) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_nearest1d_backward", [&] { + cpu_upsample_nearest_backward(grad_input, grad_output, {scales_w}); + }); +} + +void _upsample_nearest_exact1d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + std::optional scales_w) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "_upsample_nearest_exact1d_backward", [&] { + cpu_upsample_nearest_backward(grad_input, grad_output, {scales_w}); + }); +} + +void upsample_nearest2d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + std::optional scales_h, + std::optional scales_w) { + if (grad_output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_nearest2d_backward_cl", [&] { + cpu_upsample_nearest_backward_channels_last(grad_input, grad_output, {scales_h, scales_w}); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_nearest2d_backward", [&] { + cpu_upsample_nearest_backward(grad_input, grad_output, {scales_h, scales_w}); + }); + } +} + +void _upsample_nearest_exact2d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + std::optional scales_h, + std::optional scales_w) { + if (grad_output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "_upsample_nearest_exact2d_backward_cl", [&] { + cpu_upsample_nearest_backward_channels_last(grad_input, grad_output, {scales_h, scales_w}); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "_upsample_nearest_exact2d_backward", [&] { + cpu_upsample_nearest_backward(grad_input, grad_output, {scales_h, scales_w}); + }); + } +} + +void upsample_nearest3d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + std::optional scales_d, + std::optional scales_h, + std::optional scales_w) { + if (grad_output.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "_upsample_nearest3d_backward_cl", [&] { + cpu_upsample_nearest_backward_channels_last(grad_input, grad_output, {scales_d, scales_h, scales_w}); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_nearest3d_backward", [&] { + cpu_upsample_nearest_backward(grad_input, grad_output, {scales_d, scales_h, scales_w}); + }); + } +} + +void _upsample_nearest_exact3d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + std::optional scales_d, + std::optional scales_h, + std::optional scales_w) { + if (grad_output.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "_upsample_nearest_exact3d_backward_cl", [&] { + cpu_upsample_nearest_backward_channels_last(grad_input, grad_output, {scales_d, scales_h, scales_w}); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "_upsample_nearest_exact3d_backward", [&] { + cpu_upsample_nearest_backward(grad_input, grad_output, {scales_d, scales_h, scales_w}); + }); + } +} + +template +void cpu_upsample_linear_backward( + const Tensor& grad_input_, + const Tensor& grad_output_, + bool align_corners, + const scale_type& scales) { + TORCH_CHECK(grad_input_.dtype() == grad_output_.dtype(), "expected dtype ", grad_output_.dtype(), + " for `grad_input` but got dtype ", grad_input_.dtype()); + + auto grad_output = grad_output_.contiguous(); + auto grad_input = grad_input_.contiguous(); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + auto input_sizes = grad_input.sizes().vec(); + auto output_sizes = grad_output.sizes().vec(); + auto ndim = input_sizes.size(); + + // treat nbatch and channels as one dimension + int64_t channels = input_sizes[0] * input_sizes[1]; + int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = (ndim >= 4) ? input_sizes[ndim - 2] : 1; + int64_t output_height = (ndim >= 4) ? output_sizes[ndim - 2] : 1; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + + int64_t input_slice_size = input_depth * input_height * input_width; + int64_t output_slice_size = output_depth * output_height * output_width; + using opmath_t = at::opmath_type; + auto loop1d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + const opmath_t width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[0]); + + opmath_t w0lambda, w1lambda; + for (const auto c : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? c * input_slice_size : 0; + for (const auto ow : c10::irange(output_width)) { + int64_t iw0 = 0, iw1 = 0; + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + opmath_t grad_output_value = grad_output_data[c * output_slice_size + ow]; + acc_data_ptr[input_offset + iw0] += w0lambda * grad_output_value; /* i0 */ + acc_data_ptr[input_offset + iw1] += w1lambda * grad_output_value; /* i1*/ + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + c * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + auto loop2d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + const opmath_t height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[0]); + const opmath_t width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[1]); + + opmath_t h0lambda, h1lambda, w0lambda, w1lambda; + for (const auto c : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? c * input_slice_size : 0; + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = 0, ih1 = 0, iw0 = 0, iw1 = 0; + compute_source_index_and_lambda( + ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners); + for (const auto ow : c10::irange(output_width)) { + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + opmath_t grad_output_value = grad_output_data[c * output_slice_size + oh * output_width + ow]; + acc_data_ptr[input_offset + ih0 * input_width + iw0] += h0lambda * w0lambda * grad_output_value; /* i00 */ + acc_data_ptr[input_offset + ih0 * input_width + iw1] += h0lambda * w1lambda * grad_output_value; /* i01 */ + acc_data_ptr[input_offset + ih1 * input_width + iw0] += h1lambda * w0lambda * grad_output_value; /* i10 */ + acc_data_ptr[input_offset + ih1 * input_width + iw1] += h1lambda * w1lambda * grad_output_value; /* i11 */ + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + c * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + auto loop3d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + const opmath_t depth_scale = area_pixel_compute_scale( + input_depth, output_depth, align_corners, scales[0]); + const opmath_t height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[1]); + const opmath_t width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[2]); + + opmath_t d0lambda, d1lambda, h0lambda, h1lambda, w0lambda, w1lambda; + for (const auto c : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? c * input_slice_size : 0; + for (const auto od : c10::irange(output_depth)) { + int64_t id0 = 0, id1 = 0, ih0 = 0, ih1 = 0, iw0 = 0, iw1 = 0; + compute_source_index_and_lambda( + id0, id1, d0lambda, d1lambda, depth_scale, od, input_depth, output_depth, align_corners); + for (const auto oh : c10::irange(output_height)) { + compute_source_index_and_lambda( + ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners); + for (const auto ow : c10::irange(output_width)) { + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + opmath_t grad_output_value = grad_output_data[c * output_slice_size + + od * output_height * output_width + oh * output_width + ow]; + acc_data_ptr[input_offset + id0 * input_height * input_width + ih0 * input_width + iw0] += d0lambda * h0lambda * w0lambda * grad_output_value; /* i000 */ + acc_data_ptr[input_offset + id0 * input_height * input_width + ih0 * input_width + iw1] += d0lambda * h0lambda * w1lambda * grad_output_value; /* i001 */ + acc_data_ptr[input_offset + id0 * input_height * input_width + ih1 * input_width + iw0] += d0lambda * h1lambda * w0lambda * grad_output_value; /* i010 */ + acc_data_ptr[input_offset + id0 * input_height * input_width + ih1 * input_width + iw1] += d0lambda * h1lambda * w1lambda * grad_output_value; /* i011 */ + acc_data_ptr[input_offset + id1 * input_height * input_width + ih0 * input_width + iw0] += d1lambda * h0lambda * w0lambda * grad_output_value; /* i100 */ + acc_data_ptr[input_offset + id1 * input_height * input_width + ih0 * input_width + iw1] += d1lambda * h0lambda * w1lambda * grad_output_value; /* i101 */ + acc_data_ptr[input_offset + id1 * input_height * input_width + ih1 * input_width + iw0] += d1lambda * h1lambda * w0lambda * grad_output_value; /* i110 */ + acc_data_ptr[input_offset + id1 * input_height * input_width + ih1 * input_width + iw1] += d1lambda * h1lambda * w1lambda * grad_output_value; /* i111 */ + } + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + c * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + if (ndim == 3) { + // upsample linear 1d + at::parallel_for(0, channels, at::internal::GRAIN_SIZE / output_slice_size / 2, loop1d); + } else if (ndim == 4) { + // upsample bilinear 2d + at::parallel_for(0, channels, at::internal::GRAIN_SIZE / output_slice_size / 4, loop2d); + } else { + // upsample trilinear 3d + TORCH_INTERNAL_ASSERT(ndim == 5); + at::parallel_for(0, channels, at::internal::GRAIN_SIZE / output_slice_size / 8, loop3d); + } + + if (!grad_input_.is_contiguous()) { + grad_input_.copy_(grad_input); + } +} + +template +void cpu_upsample_linear_backward_channels_last( + const Tensor& grad_input_, + const Tensor& grad_output_, + bool align_corners, + const scale_type& scales) { + TORCH_CHECK(grad_input_.dtype() == grad_output_.dtype(), "expected dtype ", grad_output_.dtype(), + " for `grad_input` but got dtype ", grad_input_.dtype()); + + auto ndim = grad_output_.ndimension(); + TORCH_CHECK(ndim >=4 && ndim <= 5, "Upsample with NHWC format supports tensors with 4 or 5 dims.") + + auto channels_last_memory_format = ndim == 4 ? at::MemoryFormat::ChannelsLast : at::MemoryFormat::ChannelsLast3d; + auto grad_output = grad_output_.contiguous(channels_last_memory_format); + auto grad_input = grad_input_.contiguous(channels_last_memory_format); + + auto grad_output_data = grad_output.const_data_ptr(); + auto grad_input_data = grad_input.mutable_data_ptr(); + + auto input_sizes = grad_input.sizes().vec(); + auto output_sizes = grad_output.sizes().vec(); + + int64_t num_batches = input_sizes[0]; + int64_t channels = input_sizes[1]; + int64_t input_depth = (ndim == 5) ? input_sizes[2] : 1; + int64_t output_depth = (ndim == 5) ? output_sizes[2] : 1; + int64_t input_height = input_sizes[ndim - 2]; + int64_t output_height = output_sizes[ndim - 2]; + int64_t input_width = input_sizes[ndim - 1]; + int64_t output_width = output_sizes[ndim - 1]; + int64_t input_slice_size = input_depth * input_height * input_width * channels; + using opmath_t = at::opmath_type; + + auto loop2d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + const opmath_t height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[0]); + const opmath_t width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[1]); + + auto input_indexr = [=](int64_t n, int64_t h, int64_t w, int64_t offset){ + return acc_data_ptr + offset + (h * input_width + w) * channels; + }; + + opmath_t h0lambda, h1lambda, w0lambda, w1lambda; + for (const auto n : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? n * input_slice_size : 0; + for (const auto oh : c10::irange(output_height)) { + int64_t ih0 = 0, ih1 = 0, iw0 = 0, iw1 = 0; + compute_source_index_and_lambda( + ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners); + for (const auto ow : c10::irange(output_width)) { + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + const scalar_t* grad_output_ptr = grad_output_data + + (n * output_height * output_width + oh * output_width + ow) * channels; + linear_channels_last_acc(input_indexr(n, ih0, iw0, input_offset), grad_output_ptr, h0lambda * w0lambda, channels); /* i00 */ + linear_channels_last_acc(input_indexr(n, ih0, iw1, input_offset), grad_output_ptr, h0lambda * w1lambda, channels); /* i01 */ + linear_channels_last_acc(input_indexr(n, ih1, iw0, input_offset), grad_output_ptr, h1lambda * w0lambda, channels); /* i10 */ + linear_channels_last_acc(input_indexr(n, ih1, iw1, input_offset), grad_output_ptr, h1lambda * w1lambda, channels); /* i11 */ + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + n * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + + } + }; + + auto loop3d = [&](int64_t begin, int64_t end) { + opmath_t* acc_data_ptr = nullptr; + std::unique_ptr buffer_data; + if constexpr (!std::is_same_v) { + buffer_data = std::make_unique(input_slice_size); + acc_data_ptr = buffer_data.get(); + memset(acc_data_ptr, 0, sizeof(opmath_t) * input_slice_size); + } else { + acc_data_ptr = reinterpret_cast(grad_input_data); + } + + const opmath_t depth_scale = area_pixel_compute_scale( + input_depth, output_depth, align_corners, scales[0]); + const opmath_t height_scale = area_pixel_compute_scale( + input_height, output_height, align_corners, scales[1]); + const opmath_t width_scale = area_pixel_compute_scale( + input_width, output_width, align_corners, scales[2]); + + auto input_indexr = [=](int64_t n, int64_t d, int64_t h, int64_t w, int64_t offset) { + return acc_data_ptr + offset + (d * input_height * input_width + h * input_width + w) * channels; + }; + + opmath_t d0lambda, d1lambda, h0lambda, h1lambda, w0lambda, w1lambda; + for (const auto n : c10::irange(begin, end)) { + int64_t input_offset = buffer_data.get() == nullptr ? n * input_slice_size : 0; + for (const auto od : c10::irange(output_depth)) { + int64_t id0 = 0, id1 = 0, ih0 = 0, ih1 = 0, iw0 = 0, iw1 = 0; + compute_source_index_and_lambda( + id0, id1, d0lambda, d1lambda, depth_scale, od, input_depth, output_depth, align_corners); + for (const auto oh : c10::irange(output_height)) { + compute_source_index_and_lambda( + ih0, ih1, h0lambda, h1lambda, height_scale, oh, input_height, output_height, align_corners); + for (const auto ow : c10::irange(output_width)) { + compute_source_index_and_lambda( + iw0, iw1, w0lambda, w1lambda, width_scale, ow, input_width, output_width, align_corners); + const scalar_t* grad_output_ptr = grad_output_data + (n * output_depth * output_height * output_width + + od * output_height * output_width + oh * output_width + ow) * channels; + linear_channels_last_acc(input_indexr(n, id0, ih0, iw0, input_offset), grad_output_ptr, d0lambda * h0lambda * w0lambda, channels); /* i000 */ + linear_channels_last_acc(input_indexr(n, id0, ih0, iw1, input_offset), grad_output_ptr, d0lambda * h0lambda * w1lambda, channels); /* i001 */ + linear_channels_last_acc(input_indexr(n, id0, ih1, iw0, input_offset), grad_output_ptr, d0lambda * h1lambda * w0lambda, channels); /* i010 */ + linear_channels_last_acc(input_indexr(n, id0, ih1, iw1, input_offset), grad_output_ptr, d0lambda * h1lambda * w1lambda, channels); /* i011 */ + linear_channels_last_acc(input_indexr(n, id1, ih0, iw0, input_offset), grad_output_ptr, d1lambda * h0lambda * w0lambda, channels); /* i100 */ + linear_channels_last_acc(input_indexr(n, id1, ih0, iw1, input_offset), grad_output_ptr, d1lambda * h0lambda * w1lambda, channels); /* i101 */ + linear_channels_last_acc(input_indexr(n, id1, ih1, iw0, input_offset), grad_output_ptr, d1lambda * h1lambda * w0lambda, channels); /* i110 */ + linear_channels_last_acc(input_indexr(n, id1, ih1, iw1, input_offset), grad_output_ptr, d1lambda * h1lambda * w1lambda, channels); /* i111 */ + } + } + } + if constexpr (!std::is_same_v) { + auto gin = grad_input_data + n * input_slice_size; + apply_grad_input(acc_data_ptr, gin, input_slice_size); + } + } + }; + + if (ndim == 4) { + // upsample bilinear 2d + at::parallel_for(0, num_batches, 0, loop2d); + } else { + // upsample trilinear 3d + TORCH_INTERNAL_ASSERT(ndim == 5); + at::parallel_for(0, num_batches, 0, loop3d); + } + + if (!grad_input_.is_contiguous(channels_last_memory_format)) { + grad_input_.copy_(grad_input); + } +} + +void upsample_linear1d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + bool align_corners, + std::optional scales_w) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_linear1d_backward", [&] { + cpu_upsample_linear_backward(grad_input, grad_output, align_corners, {scales_w}); + }); +} + +void upsample_bilinear2d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + bool align_corners, + std::optional scales_h, + std::optional scales_w) { + if (grad_output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_bilinear2d_backward_channels_last", [&] { + cpu_upsample_linear_backward_channels_last(grad_input, grad_output, align_corners, {scales_h, scales_w}); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_bilinear2d_backward", [&] { + cpu_upsample_linear_backward(grad_input, grad_output, align_corners, {scales_h, scales_w}); + }); + } +} + +void upsample_trilinear3d_backward_kernel_impl( + const Tensor& grad_input, + const Tensor& grad_output, + bool align_corners, + std::optional scales_d, + std::optional scales_h, + std::optional scales_w) { + if (grad_output.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_trilinear3d_backward_channels_last", [&] { + cpu_upsample_linear_backward_channels_last(grad_input, grad_output, align_corners, {scales_d, scales_h, scales_w}); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, grad_output.scalar_type(), "upsample_trilinear3d_backward", [&] { + cpu_upsample_linear_backward(grad_input, grad_output, align_corners, {scales_d, scales_h, scales_w}); + }); + } +} + +} // anonymous namespace + +REGISTER_DISPATCH(upsample_nearest1d_backward_kernel, &upsample_nearest1d_backward_kernel_impl) +REGISTER_DISPATCH(_upsample_nearest_exact1d_backward_kernel, &_upsample_nearest_exact1d_backward_kernel_impl) +REGISTER_DISPATCH(upsample_nearest2d_backward_kernel, &upsample_nearest2d_backward_kernel_impl) +REGISTER_DISPATCH(_upsample_nearest_exact2d_backward_kernel, &_upsample_nearest_exact2d_backward_kernel_impl) +REGISTER_DISPATCH(upsample_nearest3d_backward_kernel, &upsample_nearest3d_backward_kernel_impl) +REGISTER_DISPATCH(_upsample_nearest_exact3d_backward_kernel, &_upsample_nearest_exact3d_backward_kernel_impl) + +REGISTER_DISPATCH(upsample_linear1d_backward_kernel, &upsample_linear1d_backward_kernel_impl) +REGISTER_DISPATCH(upsample_bilinear2d_backward_kernel, &upsample_bilinear2d_backward_kernel_impl) +REGISTER_DISPATCH(upsample_trilinear3d_backward_kernel, &upsample_trilinear3d_backward_kernel_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/WeightNormKernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/WeightNormKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd3df4929b2bf42c95b0f73a0e81e50e87839d3a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/WeightNormKernel.cpp @@ -0,0 +1,455 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +void weight_norm_first_dim_kernel( + TensorBase& w, + TensorBase& norm, + const TensorBase& v, + const TensorBase& g, + int64_t M, int64_t N) { + const auto v_data = v.const_data_ptr(); + const auto g_data = g.const_data_ptr(); + auto w_data = w.data_ptr(); + auto norm_data = norm.data_ptr(); + + using Vec = vec::Vectorized; + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + accscalar_t norm_val = vec::map_reduce_all( + [](Vec x) { return x * x; }, + [](Vec x, Vec y) { return x + y; }, + v_data + i * N, + N); + norm_val = std::sqrt(norm_val); + norm_data[i] = norm_val; + + accscalar_t a = g_data[i] / norm_val; + vec::map( + [a](Vec x) { return x * Vec(a); }, + w_data + i * N, + v_data + i * N, + N); + } + }); +} + +template +inline std::enable_if_t, void> +sum_norm_per_row( + scalar_t* out_ptr, + const scalar_t* v_ptr, + int64_t size) { + using Vec = vec::Vectorized; + vec::map2( + [](Vec out, Vec v) { return out + v * v; }, + out_ptr, + out_ptr, + v_ptr, + size); +} + +template +inline std::enable_if_t, void> +sum_norm_per_row( + float* out_ptr, + const scalar_t* v_ptr, + int64_t size) { + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % bVec::size()); d += bVec::size()) { + bVec v_bvec = bVec::loadu(v_ptr + d); + auto [v_fvec0, v_fvec1] = vec::convert_to_float(v_bvec); + + fVec out_fvec0 = fVec::loadu(out_ptr + d) + v_fvec0 * v_fvec0; + fVec out_fvec1 = fVec::loadu(out_ptr + d + fVec::size()) + v_fvec1 * v_fvec1; + out_fvec0.store(out_ptr + d); + out_fvec1.store(out_ptr + d + fVec::size()); + } + for(; d < size; ++d) { + float v_val = float(v_ptr[d]); + out_ptr[d] += v_val * v_val; + } +} + +template +inline std::enable_if_t, void> +apply_norm_per_row( + scalar_t* w_ptr, + const scalar_t* v_ptr, + const scalar_t* a_ptr, + int64_t size) { + using Vec = vec::Vectorized; + vec::map2( + [](Vec v, Vec a) { return v * a; }, + w_ptr, + v_ptr, + a_ptr, + size); +} + +template +inline std::enable_if_t, void> +apply_norm_per_row( + scalar_t* w_ptr, + const scalar_t* v_ptr, + const float* a_ptr, + int64_t size) { + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % bVec::size()); d += bVec::size()) { + bVec v_bvec = bVec::loadu(v_ptr + d); + auto [v_fvec0, v_fvec1] = vec::convert_to_float(v_bvec); + + fVec w_fvec0 = fVec::loadu(a_ptr + d) * v_fvec0; + fVec w_fvec1 = fVec::loadu(a_ptr + d + fVec::size()) * v_fvec1; + bVec w_bvec = vec::convert_from_float(w_fvec0, w_fvec1); + w_bvec.store(w_ptr + d); + } + for(; d < size; ++d) { + w_ptr[d] = float(v_ptr[d]) * a_ptr[d]; + } +} + +template +void weight_norm_last_dim_kernel( + TensorBase& w, + TensorBase& norm, + const TensorBase& v, + const TensorBase& g, + int64_t M, int64_t N) { + const auto v_data = v.const_data_ptr(); + const auto g_data = g.const_data_ptr(); + auto w_data = w.data_ptr(); + auto norm_data = norm.data_ptr(); + + int num_threads = at::get_num_threads(); + TensorBase buffer = at::detail::empty_cpu({num_threads, N}, norm.options()).zero_(); + auto buffer_data = buffer.data_ptr(); + + // vertical parallel reduction + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + auto buffer_ptr = buffer_data + tid * N; + for (const auto i : c10::irange(begin, end)) { + sum_norm_per_row(buffer_ptr, v_data + i * N, N); + } + }); + + for (const auto j : c10::irange(N)) { + accscalar_t sum = 0; + for (const auto t : c10::irange(num_threads)) { + sum += buffer_data[t * N + j]; + } + norm_data[j] = std::sqrt(sum); + } + + // reuse the first row of buffer to store g / norm + vec::convert(g_data, buffer_data, N); + using Vec = vec::Vectorized; + vec::map2( + [](Vec g, Vec norm) { return g / norm; }, + buffer_data, + buffer_data, + norm_data, + N); + + // apply w = v * (g/norm) + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + apply_norm_per_row(w_data + i * N, v_data + i * N, buffer_data, N); + } + }); +} + +template +void weight_norm_backward_first_dim_kernel( + TensorBase& grad_v, + TensorBase& grad_g, + const TensorBase& grad_w, + const TensorBase& saved_v, + const TensorBase& saved_g, + const TensorBase& saved_norm, + int64_t M, int64_t N) { + const auto grad_w_data = grad_w.const_data_ptr(); + const auto saved_v_data = saved_v.const_data_ptr(); + const auto saved_g_data = saved_g.const_data_ptr(); + const auto saved_norm_data = saved_norm.const_data_ptr(); + auto grad_v_data = grad_v.data_ptr(); + auto grad_g_data = grad_g.data_ptr(); + + using Vec = vec::Vectorized; + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + accscalar_t per_dim_sum_val = vec::map2_reduce_all( + [](Vec grad_w, Vec saved_v) { return grad_w * saved_v; }, + [](Vec x, Vec y) { return x + y; }, + grad_w_data + i * N, + saved_v_data + i * N, + N); + + accscalar_t saved_norm_val = saved_norm_data[i]; + accscalar_t saved_g_val = accscalar_t(saved_g_data[i]); + accscalar_t grad_g_val = per_dim_sum_val / saved_norm_val; + + // grad_g = sum / norm + // grad_v = (g / norm) * (grad_w - v * (sum / norm^2)) + // let a = g /norm + // b = a * grad_g / norm + // grad_v = a * grad_w - b * v + grad_g_data[i] = scalar_t(grad_g_val); + accscalar_t a = saved_g_val / saved_norm_val; + accscalar_t b = a * grad_g_val / saved_norm_val; + + vec::map2( + [a, b](Vec grad_w, Vec v) { return Vec(a) * grad_w - Vec(b) * v; }, + grad_v_data + i * N, + grad_w_data + i * N, + saved_v_data + i * N, + N); + } + }); +} + +template +inline std::enable_if_t, void> +sum_product_per_row( + scalar_t* out_ptr, + const scalar_t* grad_w_ptr, + const scalar_t* v_ptr, + int64_t size) { + using Vec = vec::Vectorized; + vec::map3( + [](Vec out, Vec grad_w, Vec v) { return out + grad_w * v; }, + out_ptr, + out_ptr, + grad_w_ptr, + v_ptr, + size); +} + +template +inline std::enable_if_t, void> +sum_product_per_row( + float* out_ptr, + const scalar_t* grad_w_ptr, + const scalar_t* v_ptr, + int64_t size) { + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % bVec::size()); d += bVec::size()) { + bVec grad_w_bvec = bVec::loadu(grad_w_ptr + d); + auto [grad_w_fvec0, grad_w_fvec1] = vec::convert_to_float(grad_w_bvec); + bVec v_bvec = bVec::loadu(v_ptr + d); + auto [v_fvec0, v_fvec1] = vec::convert_to_float(v_bvec); + + fVec out_fvec0 = fVec::loadu(out_ptr + d) + grad_w_fvec0 * v_fvec0; + fVec out_fvec1 = fVec::loadu(out_ptr + d + fVec::size()) + grad_w_fvec1 * v_fvec1; + out_fvec0.store(out_ptr + d); + out_fvec1.store(out_ptr + d + fVec::size()); + } + for(; d < size; ++d) { + float grad_w_val = float(grad_w_ptr[d]); + float v_val = float(v_ptr[d]); + out_ptr[d] += grad_w_val * v_val; + } +} + +template +inline std::enable_if_t, void> +apply_per_row_backward( + scalar_t* grad_v_ptr, + const scalar_t* grad_w_ptr, + const scalar_t* v_ptr, + const scalar_t* a_ptr, + const scalar_t* b_ptr, + int64_t size) { + using Vec = vec::Vectorized; + vec::map4( + [](Vec grad_w, Vec v, Vec a, Vec b) { return a * grad_w - b * v; }, + grad_v_ptr, + grad_w_ptr, + v_ptr, + a_ptr, + b_ptr, + size); +} + +template +inline std::enable_if_t, void> +apply_per_row_backward( + scalar_t* grad_v_ptr, + const scalar_t* grad_w_ptr, + const scalar_t* v_ptr, + const float* a_ptr, + const float* b_ptr, + int64_t size) { + using bVec = vec::Vectorized; + using fVec = vec::Vectorized; + int64_t d = 0; + for (; d < size - (size % bVec::size()); d += bVec::size()) { + bVec grad_w_bvec = bVec::loadu(grad_w_ptr + d); + auto [grad_w_fvec0, grad_w_fvec1] = vec::convert_to_float(grad_w_bvec); + bVec v_bvec = bVec::loadu(v_ptr + d); + auto [v_fvec0, v_fvec1] = vec::convert_to_float(v_bvec); + + fVec grad_v_fvec0 = fVec::loadu(a_ptr + d) * grad_w_fvec0 - fVec::loadu(b_ptr + d) * v_fvec0; + fVec grad_v_fvec1 = fVec::loadu(a_ptr + d + fVec::size()) * grad_w_fvec1 + - fVec::loadu(b_ptr + d + fVec::size()) * v_fvec1; + bVec grad_v_bvec = vec::convert_from_float(grad_v_fvec0, grad_v_fvec1); + grad_v_bvec.store(grad_v_ptr + d); + } + for(; d < size; ++d) { + grad_v_ptr[d] = float(grad_w_ptr[d]) * a_ptr[d] - float(v_ptr[d]) * b_ptr[d]; + } +} + +template +void weight_norm_backward_last_dim_kernel( + TensorBase& grad_v, + TensorBase& grad_g, + const TensorBase& grad_w, + const TensorBase& saved_v, + const TensorBase& saved_g, + const TensorBase& saved_norm, + int64_t M, int64_t N) { + const auto grad_w_data = grad_w.const_data_ptr(); + const auto saved_v_data = saved_v.const_data_ptr(); + const auto saved_g_data = saved_g.const_data_ptr(); + const auto saved_norm_data = saved_norm.const_data_ptr(); + auto grad_v_data = grad_v.data_ptr(); + auto grad_g_data = grad_g.data_ptr(); + + // the temp buffer will be used twice: + // 1. vertical reduction from [M, N] to [T, N] + // 2. store the intermediate data of `sum`, `a` and `b`, + // so need to make sure it has at least 3 rows + // + int num_threads = at::get_num_threads(); + int K = std::max(3, num_threads); + TensorBase buffer = at::detail::empty_cpu({K, N}, saved_norm.options()).zero_(); + auto buffer_data = buffer.data_ptr(); + + // vertical parallel reduction + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + auto buffer_ptr = buffer_data + tid * N; + for (const auto i : c10::irange(begin, end)) { + sum_product_per_row(buffer_ptr, grad_w_data + i * N, saved_v_data + i * N, N); + } + }); + + // store result on the first row of buffer + for (const auto j : c10::irange(N)) { + accscalar_t sum = 0; + for (const auto t : c10::irange(num_threads)) { + sum += buffer_data[t * N + j]; + } + buffer_data[j] = sum; + } + + // reuse the 1st row of buffer to store the sum + // 2nd row to store coefficient a + // 3rd row to store coefficient b + accscalar_t* per_dim_sum = buffer_data; + accscalar_t* a = buffer_data + N; + accscalar_t* b = buffer_data + 2 * N; + + // a = g /norm + // b = a * grad_g / norm + for (const auto j : c10::irange(N)) { + accscalar_t saved_norm_val = saved_norm_data[j]; + accscalar_t saved_g_val = accscalar_t(saved_g_data[j]); + accscalar_t grad_g_val = per_dim_sum[j] / saved_norm_val; + grad_g_data[j] = scalar_t(grad_g_val); + + a[j] = saved_g_val / saved_norm_val; + b[j] = a[j] * grad_g_val / saved_norm_val; + } + + // apply grad_v = a * grad_w - b * v + at::parallel_for(0, M, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + apply_per_row_backward( + grad_v_data + i * N, + grad_w_data + i * N, + saved_v_data + i * N, + a, + b, + N); + } + }); +} + +void weight_norm_kernel( + TensorBase& w, + TensorBase& norm, + const TensorBase& v, + const TensorBase& g, + int64_t dim) { + TORCH_INTERNAL_ASSERT(dim == 0 || dim == v.dim() - 1, + "fused kernels can only be applied for first or last dim"); + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, v.scalar_type(), + "weight_norm_kernel", [&]() { + using accscalar_t = at::opmath_type; + if (dim == 0) { + int64_t M = v.size(0); + int64_t N = v.numel() / M; + weight_norm_first_dim_kernel(w, norm, v, g, M, N); + } else { + int64_t N = v.size(-1); + int64_t M = v.numel() / N; + weight_norm_last_dim_kernel(w, norm, v, g, M, N); + } + }); +} + +void weight_norm_backward_kernel( + TensorBase& grad_v, + TensorBase& grad_g, + const TensorBase& grad_w, + const TensorBase& saved_v, + const TensorBase& saved_g, + const TensorBase& saved_norm, + int64_t dim) { + TORCH_INTERNAL_ASSERT(dim == 0 || dim == saved_v.dim() - 1, + "fused kernels can only be applied for first or last dim"); + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, saved_v.scalar_type(), + "weight_norm_backward_kernel", [&]() { + using accscalar_t = at::opmath_type; + if (dim == 0) { + int64_t M = saved_v.size(0); + int64_t N = saved_v.numel() / M; + weight_norm_backward_first_dim_kernel(grad_v, grad_g, grad_w, saved_v, saved_g, saved_norm, M, N); + } else { + int64_t N = saved_v.size(-1); + int64_t M = saved_v.numel() / N; + weight_norm_backward_last_dim_kernel(grad_v, grad_g, grad_w, saved_v, saved_g, saved_norm, M, N); + } + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(weight_norm_stub, &weight_norm_kernel) +REGISTER_DISPATCH(weight_norm_backward_stub, &weight_norm_backward_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/WeightNormKernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/WeightNormKernel.h new file mode 100644 index 0000000000000000000000000000000000000000..2fc0e15e5201df6d5f88689c70cb7f84b59fd99e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/WeightNormKernel.h @@ -0,0 +1,20 @@ +#pragma once +#include +#include + +namespace at { +class TensorBase; +} + +namespace at::native { + +using weight_norm_fn = void(*)( + TensorBase&, TensorBase&, const TensorBase&, const TensorBase&, int64_t); +using weight_norm_backward_fn = void(*)( + TensorBase&, TensorBase&, const TensorBase&, const TensorBase&, + const TensorBase&, const TensorBase&, int64_t); + +DECLARE_DISPATCH(weight_norm_fn, weight_norm_stub) +DECLARE_DISPATCH(weight_norm_backward_fn, weight_norm_backward_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/airy_ai.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/airy_ai.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f084702196302302177126dabbc0775b206a37d6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/airy_ai.cpp @@ -0,0 +1,24 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include + +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { +static void airy_ai_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "airy_ai_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return airy_ai_forward(x); + }); + }); +} // airy_ai_kernel(TensorIteratorBase& iterator) +} // namespace CPU_CAPABILITY + +REGISTER_DISPATCH(special_airy_ai_stub, &CPU_CAPABILITY::airy_ai_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/avx_mathfun.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/avx_mathfun.h new file mode 100644 index 0000000000000000000000000000000000000000..dbd0e9a5f65c66923dd1376ad1971c3a7a90aacb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/avx_mathfun.h @@ -0,0 +1,522 @@ +#pragma once +/* + AVX implementation of sin, cos, sincos, exp and log + + Based on "sse_mathfun.h", by Julien Pommier + http://gruntthepeon.free.fr/ssemath/ + + Copyright (C) 2012 Giovanni Garberoglio + Interdisciplinary Laboratory for Computational Science (LISC) + Fondazione Bruno Kessler and University of Trento + via Sommarive, 18 + I-38123 Trento (Italy) + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + (this is the zlib license) +*/ + +#include + +/* The original source of this file has been modified. */ +#if defined(CPU_CAPABILITY_AVX2) + +#if defined(__GNUC__) +# define ALIGN32_BEG __attribute__((aligned(32))) +#elif defined(_WIN32) +# define ALIGN32_BEG __declspec(align(32)) +#endif + +typedef __m256 v8sf; // vector of 8 float (avx2) +typedef __m256i v8si; // vector of 8 int (avx2) + +/* declare some AVX constants -- why can't I figure a better way to do that? */ +#define _PS256_CONST(Name, Val) \ + static const ALIGN32_BEG float _ps256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val } +#define _PI32_CONST256(Name, Val) \ + static const ALIGN32_BEG int _pi32_256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val } +#define _PS256_CONST_TYPE(Name, Type, Val) \ + static const ALIGN32_BEG Type _ps256_##Name[8] = { Val, Val, Val, Val, Val, Val, Val, Val } + +_PS256_CONST(1 , 1.0f); +_PS256_CONST(0p5, 0.5f); +/* the smallest non denormalized float number */ +_PS256_CONST_TYPE(min_norm_pos, int, 0x00800000); +_PS256_CONST_TYPE(mant_mask, int, 0x7f800000); +_PS256_CONST_TYPE(inv_mant_mask, int, ~0x7f800000); + +_PS256_CONST_TYPE(sign_mask, int, (int)0x80000000); +_PS256_CONST_TYPE(inv_sign_mask, int, ~0x80000000); + +_PI32_CONST256(0, 0); +_PI32_CONST256(1, 1); +_PI32_CONST256(inv1, ~1); +_PI32_CONST256(2, 2); +_PI32_CONST256(4, 4); +_PI32_CONST256(0x7f, 0x7f); + +_PS256_CONST(cephes_SQRTHF, 0.707106781186547524); +_PS256_CONST(cephes_log_p0, 7.0376836292E-2); +_PS256_CONST(cephes_log_p1, - 1.1514610310E-1); +_PS256_CONST(cephes_log_p2, 1.1676998740E-1); +_PS256_CONST(cephes_log_p3, - 1.2420140846E-1); +_PS256_CONST(cephes_log_p4, + 1.4249322787E-1); +_PS256_CONST(cephes_log_p5, - 1.6668057665E-1); +_PS256_CONST(cephes_log_p6, + 2.0000714765E-1); +_PS256_CONST(cephes_log_p7, - 2.4999993993E-1); +_PS256_CONST(cephes_log_p8, + 3.3333331174E-1); +_PS256_CONST(cephes_log_q1, -2.12194440e-4); +_PS256_CONST(cephes_log_q2, 0.693359375); + + +/* natural logarithm computed for 8 simultaneous float + return NaN for x <= 0 +*/ +inline v8sf log256_ps(v8sf x) { + v8si imm0; + v8sf one = *(v8sf*)_ps256_1; + + //v8sf invalid_mask = _mm256_cmple_ps(x, _mm256_setzero_ps()); + v8sf invalid_mask = _mm256_cmp_ps(x, _mm256_setzero_ps(), _CMP_LE_OS); + + x = _mm256_max_ps(x, *(v8sf*)_ps256_min_norm_pos); /* cut off denormalized stuff */ + + // can be done with AVX2 + imm0 = _mm256_srli_epi32(_mm256_castps_si256(x), 23); + + /* keep only the fractional part */ + x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_mant_mask); + x = _mm256_or_ps(x, *(v8sf*)_ps256_0p5); + + // this is again another AVX2 instruction + imm0 = _mm256_sub_epi32(imm0, *(v8si*)_pi32_256_0x7f); + v8sf e = _mm256_cvtepi32_ps(imm0); + + e = _mm256_add_ps(e, one); + + /* part2: + if( x < SQRTHF ) { + e -= 1; + x = x + x - 1.0; + } else { x = x - 1.0; } + */ + //v8sf mask = _mm256_cmplt_ps(x, *(v8sf*)_ps256_cephes_SQRTHF); + v8sf mask = _mm256_cmp_ps(x, *(v8sf*)_ps256_cephes_SQRTHF, _CMP_LT_OS); + v8sf tmp = _mm256_and_ps(x, mask); + x = _mm256_sub_ps(x, one); + e = _mm256_sub_ps(e, _mm256_and_ps(one, mask)); + x = _mm256_add_ps(x, tmp); + + v8sf z = _mm256_mul_ps(x,x); + + v8sf y = *(v8sf*)_ps256_cephes_log_p0; + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p1); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p2); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p3); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p4); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p5); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p6); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p7); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_log_p8); + y = _mm256_mul_ps(y, x); + + y = _mm256_mul_ps(y, z); + + tmp = _mm256_mul_ps(e, *(v8sf*)_ps256_cephes_log_q1); + y = _mm256_add_ps(y, tmp); + + + tmp = _mm256_mul_ps(z, *(v8sf*)_ps256_0p5); + y = _mm256_sub_ps(y, tmp); + + tmp = _mm256_mul_ps(e, *(v8sf*)_ps256_cephes_log_q2); + x = _mm256_add_ps(x, y); + x = _mm256_add_ps(x, tmp); + x = _mm256_or_ps(x, invalid_mask); // negative arg will be NAN + return x; +} + +_PS256_CONST(exp_hi, 88.3762626647949f); +_PS256_CONST(exp_lo, -88.3762626647949f); + +_PS256_CONST(cephes_LOG2EF, 1.44269504088896341); +_PS256_CONST(cephes_exp_C1, 0.693359375); +_PS256_CONST(cephes_exp_C2, -2.12194440e-4); + +_PS256_CONST(cephes_exp_p0, 1.9875691500E-4); +_PS256_CONST(cephes_exp_p1, 1.3981999507E-3); +_PS256_CONST(cephes_exp_p2, 8.3334519073E-3); +_PS256_CONST(cephes_exp_p3, 4.1665795894E-2); +_PS256_CONST(cephes_exp_p4, 1.6666665459E-1); +_PS256_CONST(cephes_exp_p5, 5.0000001201E-1); + +inline v8sf exp256_ps(v8sf x) { + v8sf tmp = _mm256_setzero_ps(), fx; + v8si imm0; + v8sf one = *(v8sf*)_ps256_1; + + x = _mm256_min_ps(x, *(v8sf*)_ps256_exp_hi); + x = _mm256_max_ps(x, *(v8sf*)_ps256_exp_lo); + + /* express exp(x) as exp(g + n*log(2)) */ + fx = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_LOG2EF); + fx = _mm256_add_ps(fx, *(v8sf*)_ps256_0p5); + + /* how to perform a floorf with SSE: just below */ + //imm0 = _mm256_cvttps_epi32(fx); + //tmp = _mm256_cvtepi32_ps(imm0); + + tmp = _mm256_floor_ps(fx); + + /* if greater, subtract 1 */ + //v8sf mask = _mm256_cmpgt_ps(tmp, fx); + v8sf mask = _mm256_cmp_ps(tmp, fx, _CMP_GT_OS); + mask = _mm256_and_ps(mask, one); + fx = _mm256_sub_ps(tmp, mask); + + tmp = _mm256_mul_ps(fx, *(v8sf*)_ps256_cephes_exp_C1); + v8sf z = _mm256_mul_ps(fx, *(v8sf*)_ps256_cephes_exp_C2); + x = _mm256_sub_ps(x, tmp); + x = _mm256_sub_ps(x, z); + + z = _mm256_mul_ps(x,x); + + v8sf y = *(v8sf*)_ps256_cephes_exp_p0; + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p1); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p2); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p3); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p4); + y = _mm256_mul_ps(y, x); + y = _mm256_add_ps(y, *(v8sf*)_ps256_cephes_exp_p5); + y = _mm256_mul_ps(y, z); + y = _mm256_add_ps(y, x); + y = _mm256_add_ps(y, one); + + /* build 2^n */ + imm0 = _mm256_cvttps_epi32(fx); + // another two AVX2 instructions + imm0 = _mm256_add_epi32(imm0, *(v8si*)_pi32_256_0x7f); + imm0 = _mm256_slli_epi32(imm0, 23); + v8sf pow2n = _mm256_castsi256_ps(imm0); + y = _mm256_mul_ps(y, pow2n); + return y; +} + +_PS256_CONST(minus_cephes_DP1, -0.78515625); +_PS256_CONST(minus_cephes_DP2, -2.4187564849853515625e-4); +_PS256_CONST(minus_cephes_DP3, -3.77489497744594108e-8); +_PS256_CONST(sincof_p0, -1.9515295891E-4); +_PS256_CONST(sincof_p1, 8.3321608736E-3); +_PS256_CONST(sincof_p2, -1.6666654611E-1); +_PS256_CONST(coscof_p0, 2.443315711809948E-005); +_PS256_CONST(coscof_p1, -1.388731625493765E-003); +_PS256_CONST(coscof_p2, 4.166664568298827E-002); +_PS256_CONST(cephes_FOPI, 1.27323954473516); // 4 / M_PI + + +/* evaluation of 8 sines at once using AVX intrinsics + + The code is the exact rewriting of the cephes sinf function. + Precision is excellent as long as x < 8192 (I did not bother to + take into account the special handling they have for greater values + -- it does not return garbage for arguments over 8192, though, but + the extra precision is missing). + + Note that it is such that sinf((float)M_PI) = 8.74e-8, which is the + surprising but correct result. + +*/ +inline v8sf sin256_ps(v8sf x) { // any x + v8sf xmm1, xmm2 = _mm256_setzero_ps(), xmm3, sign_bit, y; + v8si imm0, imm2; + + sign_bit = x; + /* take the absolute value */ + x = _mm256_and_ps(x, *(v8sf*)_ps256_inv_sign_mask); + /* extract the sign bit (upper one) */ + sign_bit = _mm256_and_ps(sign_bit, *(v8sf*)_ps256_sign_mask); + + /* scale by 4/Pi */ + y = _mm256_mul_ps(x, *(v8sf*)_ps256_cephes_FOPI); + + /* + Here we start a series of integer operations, which are in the + realm of AVX2. + If we don't have AVX, let's perform them using SSE2 directives + */ + + /* store the integer part of y in mm0 */ + imm2 = _mm256_cvttps_epi32(y); + /* j=(j+1) & (~1) (see the cephes sources) */ + // another two AVX2 instruction + imm2 = _mm256_add_epi32(imm2, *(v8si*)_pi32_256_1); + imm2 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_inv1); + y = _mm256_cvtepi32_ps(imm2); + + /* get the swap sign flag */ + imm0 = _mm256_and_si256(imm2, *(v8si*)_pi32_256_4); + imm0 = _mm256_slli_epi32(imm0, 29); + /* get the polynom selection mask + there is one polynom for 0 <= x <= Pi/4 + and another one for Pi/4 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#endif + +namespace at::native { +namespace { + +using namespace vec; + +template +void batch_norm_cpu_collect_linear_and_constant_terms( + opmath_t* alpha, opmath_t* beta, int64_t n_channel, + const Tensor& weight /* optional */, const Tensor& bias /* optional */, + const Tensor& save_mean, const Tensor& save_invstd, + const Tensor& running_mean, const Tensor& running_var, bool train, double eps) { + + const param_t* weight_data = weight.defined() ? weight.const_data_ptr() : nullptr; + const param_t* bias_data = bias.defined() ? bias.const_data_ptr() : nullptr; + + auto save_mean_a = conditional_accessor_1d(save_mean); + auto save_invstd_a = conditional_accessor_1d(save_invstd); + auto running_mean_a = conditional_accessor_1d(running_mean); + auto running_var_a = conditional_accessor_1d(running_var); + + /// Collect the linear and constant terms regarding the input. + /// output(n, c, h, w) + /// = (input(n, c, h, w) - mean(c)) / sqrt(var(c) + eps) * weight(c) + /// + bias(c) + /// = input(n, c, h, w) * inv_var(c) * weight(c) + /// - mean(c) * inv_var(c) * weight(c) + bias(c), + /// where inv_var(c) = 1 / sqrt(var(c) + eps). + /// So the linear term, alpha(c) = inv_var(c) * weight(c), + /// the constant term beta(c) = bias(c) - mean(c) * inv_var(c) * weight(c) + /// Note that this is only a good idea if (input_size >> c), in degenerate + /// cases where image_size == 1 && batch_size == 1, it is slow. + for (const auto c : c10::irange(n_channel)) { + opmath_t mean, invstd; + if (train) { + mean = save_mean_a[c]; + invstd = save_invstd_a[c]; + } else { + mean = running_mean_a[c]; + invstd = 1 / std::sqrt(running_var_a[c] + static_cast(eps)); + } + param_t weight_v = weight_data ? weight_data[c] : param_t(1); + param_t bias_v = bias_data ? bias_data[c] : param_t(0); + alpha[c] = invstd * weight_v; + beta[c] = bias_v - mean * alpha[c]; + } +} + +/// A fast path for CPU inference and training forward when all tensors are contiguous. +template +typename std::enable_if_t>, void> +batch_norm_cpu_contiguous_impl(Tensor& output, const Tensor& input, + const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd, + const Tensor& running_mean, const Tensor& running_var, bool train, double eps) { + + using Vec = Vectorized; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + + Tensor alpha = at::empty({n_channel}, input.options()); + Tensor beta = at::empty({n_channel}, input.options()); + scalar_t* alpha_data = alpha.mutable_data_ptr(); + scalar_t* beta_data = beta.data_ptr(); + + batch_norm_cpu_collect_linear_and_constant_terms( + alpha_data, beta_data, n_channel, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + + scalar_t* output_data = output.data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + // Apply the linear terms to the input, + // output(n, c, h, w) = input(n, c, h, w) * alpha(c) + beta(c) + const int64_t loop_size = image_size - (image_size % Vec::size()); + at::parallel_for(0, n_batch * n_channel, 1, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t c = 0; + data_index_init(begin, n, n_batch, c, n_channel); + + for (const auto i : c10::irange(begin, end)) { + const Vec alpha_vec(alpha_data[c]); + const Vec beta_vec(beta_data[c]); + int64_t offset = i * image_size; + int64_t d = 0; + for (; d < loop_size; d += Vec::size()) { + Vec data_vec = Vec::loadu(input_data + offset + d); + Vec output_vec = data_vec * alpha_vec + beta_vec; + output_vec.store(output_data + offset + d); + } + if (image_size - d > 0) { + Vec data_vec = Vec::loadu(input_data + offset + d, image_size - d); + Vec output_vec = data_vec * alpha_vec + beta_vec; + output_vec.store(output_data + offset + d, image_size - d); + } + // move on to next index + data_index_step(n, n_batch, c, n_channel); + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_channels_last_impl(Tensor& output, const Tensor& input, + const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd, + const Tensor& running_mean, const Tensor& running_var, bool train, double eps) { + + using Vec = Vectorized; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + + Tensor alpha = at::empty({n_channel}, input.options()); + Tensor beta = at::empty({n_channel}, input.options()); + scalar_t* alpha_data = alpha.mutable_data_ptr(); + scalar_t* beta_data = beta.data_ptr(); + + batch_norm_cpu_collect_linear_and_constant_terms( + alpha_data, beta_data, n_channel, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + + scalar_t* output_data = output.data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + // Apply the linear terms to the input, + // output(n, c, h, w) = input(n, c, h, w) * alpha(c) + beta(c) + const int64_t loop_size = n_channel - (n_channel % Vec::size()); + at::parallel_for(0, n_batch * image_size, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + int64_t offset = i * n_channel; + int64_t d = 0; + // vectorize on channel dimension, for normal batch_norm input size, + // alpha/beta should fit in L1 cache, otherwise consider blocking. + for (; d < loop_size; d += Vec::size()) { + Vec alpha_vec = Vec::loadu(alpha_data + d); + Vec beta_vec = Vec::loadu(beta_data + d); + Vec data_vec = Vec::loadu(input_data + offset + d); + Vec output_vec = data_vec * alpha_vec + beta_vec; + output_vec.store(output_data + offset + d); + } + if (n_channel - d > 0) { + Vec alpha_vec = Vec::loadu(alpha_data + d, n_channel - d); + Vec beta_vec = Vec::loadu(beta_data + d, n_channel - d); + Vec data_vec = Vec::loadu(input_data + offset + d, n_channel - d); + Vec output_vec = data_vec * alpha_vec + beta_vec; + output_vec.store(output_data + offset + d, n_channel - d); + } + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_collect_stats_contiguous_impl( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + + // keep acc_type as opmath_type will use float type when scalar_t==float + // while acc_type uses double for float. + using accscalar_t = at::acc_type; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + int64_t N = input.numel() / n_channel; + + const scalar_t* input_data = input.const_data_ptr(); + scalar_t* mean_data = mean.data_ptr(); + scalar_t* var_sum_data = var_sum.data_ptr(); + + // parallel dim reduce on 'channel' + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + // compute mean per input + accscalar_t sum = 0; + for (const auto n : c10::irange(n_batch)) { + for (const auto i : c10::irange(image_size)) { + auto offset = n * n_channel * image_size + c * image_size + i; + sum += input_data[offset]; + } + } + scalar_t mean = sum / N; + mean_data[c] = mean; + + // compute variance per input + accscalar_t _var_sum = 0; + for (const auto n : c10::irange(n_batch)) { + for (const auto i : c10::irange(image_size)) { + auto offset = n * n_channel * image_size + c * image_size + i; + auto x = input_data[offset]; + _var_sum += (x - mean) * (x - mean); + } + } + var_sum_data[c] = _var_sum; + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_collect_stats_channels_last_impl( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + + using Vec = Vectorized; + // keep acc_type as opmath_type will use float type when scalar_t==float + // while acc_type uses double for float. + using accscalar_t = at::acc_type; + int64_t n_channel = input.size(1); + int64_t N = input.numel() / n_channel; + + const scalar_t* input_data = input.const_data_ptr(); + scalar_t* mean_data = mean.data_ptr(); + scalar_t* var_sum_data = var_sum.data_ptr(); + + // Typical vertical reduce from shape of {NHW, C} to {C}. + // Apply two path parallel reduction when NHW > max_threads: + // First path: allocate an immediate buffer of size {max_threads, C}, parallel along dim0, + // {NHW, C} => {max_threads, C} + // + // Second path: parallel along dim1 of the immediate buffer, + // {max_threads, C} => {C} + // + // Normal size of C should fit in L1, otherwise consider blocking on C. + // + int num_threads = at::get_num_threads(); + + if (N > num_threads) { + Tensor buffer = at::zeros({num_threads, n_channel}, input.options()); + scalar_t* buffer_data = buffer.data_ptr(); + + // compute mean per input + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, + "expect thread id smaller than ", num_threads, ", got thread id ", tid); + scalar_t* buffer_ptr = buffer_data + tid * n_channel; + for (const auto i : c10::irange(begin, end)) { + const scalar_t* x_ptr = input_data + i * n_channel; + vec::map2( + [](Vec x, Vec y) { return x + y; }, + buffer_ptr, + x_ptr, + buffer_ptr, + n_channel); + } + }); + + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + accscalar_t sum = 0; + for (const auto t : c10::irange(num_threads)) { + sum += buffer_data[t * n_channel + c]; + } + scalar_t mean = sum / N; + mean_data[c] = mean; + } + }); + + // compute variance per input, reuse the immediate buffer + buffer.zero_(); + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + scalar_t* buffer_ptr = buffer_data + tid * n_channel; + for (const auto i : c10::irange(begin, end)) { + const scalar_t* x_ptr = input_data + i * n_channel; + vec::map3( + [](Vec x, Vec y, Vec mean) { return y + (x - mean) * (x - mean); }, + buffer_ptr, + x_ptr, + buffer_ptr, + mean_data, + n_channel); + } + }); + + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + accscalar_t _var_sum = 0; + for (const auto t : c10::irange(num_threads)) { + _var_sum += buffer_data[t * n_channel + c]; + } + var_sum_data[c] = _var_sum; + } + }); + } else { + // Vertical reduce from shape of {NHW, C} to {C} when NHW <= max_threads. + // We'll use two methods, Method 1 and Method 2. + // + // Method 1: when TILE_SIZE < C <= THRESHOLD, parallel on C + // {NHW, C} => {C} + // + // Method 2: when C <= TILE_SIZE or C > THRESHOLD, tile and vectorize on C, C is tiled as: + // C: {TILE_SIZE, TILE_SIZE, ..., Remainder} + // parallel on tiles, vectorized vertical reduce on each tile + // {NHW, TILE_SIZE} => {TILE_SIZE} + // + // The optimal THRESHOLD to tile was found empirically. + // When C > THRESHOLD, C is large enough that the benefit from tiling and vectorization outweigh the synchronization overhead. + // When C <= TILE_SIZE, the problem size is small enough (C <= TILE_SIZE && NHW <= max_threads) that it's better to launch single thread with vectorization than C threads without vectorization. + // + // When num_threads == 1, always use Method 2 as there is no synchronization overhead. + // + int64_t TILE_SIZE = 16; + int64_t THRESHOLD = 2048; + + // Method 2: parallel on tiles of C, vectorized vertical reduce on each tile + if (num_threads == 1 || (n_channel <= TILE_SIZE || n_channel > THRESHOLD)) { + // compute mean per input + mean.zero_(); + at::parallel_for(0, (n_channel + TILE_SIZE - 1) / TILE_SIZE, 1, [&](int64_t tile_idx_begin, int64_t tile_idx_end) { + for (int64_t tile_idx = tile_idx_begin; tile_idx < tile_idx_end; tile_idx++) { + int64_t jj_begin = tile_idx * TILE_SIZE; + int64_t jj_end = std::min(jj_begin + TILE_SIZE, n_channel); + scalar_t* mean_ptr = mean_data + jj_begin; + for (const auto i : c10::irange(N)) { + const scalar_t* x_ptr = input_data + (i * n_channel + jj_begin); + vec::map2( + [](Vec x, Vec y) { return x + y; }, + mean_ptr, + x_ptr, + mean_ptr, + jj_end - jj_begin); + } + vec::map( + [N](Vec x) { return x / Vec(N); }, + mean_ptr, + mean_ptr, + jj_end - jj_begin); + } + }); + + // compute variance per input + var_sum.zero_(); + at::parallel_for(0, (n_channel + TILE_SIZE - 1) / TILE_SIZE, 1, [&](int64_t tile_idx_begin, int64_t tile_idx_end) { + for (int64_t tile_idx = tile_idx_begin; tile_idx < tile_idx_end; tile_idx++) { + int64_t jj_begin = tile_idx * TILE_SIZE; + int64_t jj_end = std::min(jj_begin + TILE_SIZE, n_channel); + scalar_t* var_sum_ptr = var_sum_data + jj_begin; + scalar_t* mean_ptr = mean_data + jj_begin; + for (const auto i : c10::irange(N)) { + const scalar_t* x_ptr = input_data + (i * n_channel + jj_begin); + vec::map3( + [](Vec x, Vec y, Vec mean) { return y + (x - mean) * (x - mean); }, + var_sum_ptr, + x_ptr, + var_sum_ptr, + mean_ptr, + jj_end - jj_begin); + } + } + }); + } + // Method 1: parallel on C, vertical reduce + else { + // compute mean per input + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + accscalar_t sum = 0; + for (const auto t : c10::irange(N)) { + sum += input_data[t * n_channel + c]; + } + scalar_t mean = sum / N; + mean_data[c] = mean; + } + }); + + // compute variance per input + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + accscalar_t _var_sum = 0; + for (const auto t : c10::irange(N)) { + _var_sum += (input_data[t * n_channel + c] - mean_data[c]) * (input_data[t * n_channel + c] - mean_data[c]); + } + var_sum_data[c] = _var_sum; + } + }); + } + } +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_backward_contiguous_impl(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + + using Vec = Vectorized; + // keep acc_type as opmath_type will use float type when scalar_t==float + // while acc_type uses double for float. + using accscalar_t = at::acc_type; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + int64_t N = input.numel() / n_channel; + + const scalar_t* grad_output_data = grad_output.const_data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + scalar_t* grad_input_data = grad_input.defined() ? grad_input.mutable_data_ptr() : nullptr; + scalar_t* grad_weight_data = grad_weight.defined() ? grad_weight.data_ptr() : nullptr; + scalar_t* grad_bias_data = grad_bias.defined() ? grad_bias.data_ptr() : nullptr; + const bool grad_input_null = grad_input_data == nullptr; + const bool grad_weight_null = grad_weight_data == nullptr; + const bool grad_bias_null = grad_bias_data == nullptr; + + auto weight_a = conditional_accessor_1d(weight); + auto save_mean_a = conditional_accessor_1d(save_mean); + auto save_invstd_a = conditional_accessor_1d(save_invstd); + auto running_mean_a = conditional_accessor_1d(running_mean); + auto running_var_a = conditional_accessor_1d(running_var); + + // parallel dim reduce on 'channel' + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + scalar_t w = weight.defined() ? weight_a[c] : 1; + + scalar_t mean, invstd; + if (train) { + mean = save_mean_a[c]; + invstd = save_invstd_a[c]; + } else { + mean = running_mean_a[c]; + invstd = 1 / std::sqrt(running_var_a[c] + eps); + } + + // reduce over grad_output in feature plane + // compute 1) sum; 2) dot product of Q(X) and dY. + // fuse into a single loop to reuse dY + // + accscalar_t sum = 0; + accscalar_t dotp = 0; + for (const auto n : c10::irange(n_batch)) { + const scalar_t* x_ptr = input_data + n * n_channel * image_size + c * image_size; + const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size; + + sum += vec::reduce_all( + [](Vec& x, Vec& y) { return x + y; }, + dy_ptr, + image_size); + + dotp += vec::map2_reduce_all( + [mean](Vec x, Vec dy) { return (x - Vec(mean)) * dy; }, + [](Vec x, Vec y) { return x + y; }, + x_ptr, + dy_ptr, + image_size); + } + + if (!grad_input_null) { + if (train) { + scalar_t k = (scalar_t) dotp * invstd * invstd / N; + scalar_t grad_mean = sum / N; + + for (const auto n : c10::irange(n_batch)) { + const scalar_t* x_ptr = input_data + n * n_channel * image_size + c * image_size; + scalar_t* dx_ptr = grad_input_data + n * n_channel * image_size + c * image_size; + const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size; + + // Scalar math: + // for (const auto j : c10::irange(image_size)) { + // scalar_t dx = (x_ptr[j] - mean) * k; + // dx_ptr[j] = (dy_ptr[j] - grad_mean - dx) * invstd * w; + // } + vec::map2( + [=](Vec x, Vec dy) { + Vec dx = (x - Vec(mean)) * Vec(k); + return (dy - Vec(grad_mean) - dx) * Vec(invstd) * Vec(w); + }, + dx_ptr, + x_ptr, + dy_ptr, + image_size); + } + } else { // evaluation mode + for (const auto n : c10::irange(n_batch)) { + scalar_t* dx_ptr = grad_input_data + n * n_channel * image_size + c * image_size; + const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size; + + // Scalar math: + // for (const auto j : c10::irange(image_size)) { + // dx_ptr[j] = dy_ptr[j] * invstd * w; + // } + vec::map( + [=](Vec dy) { return dy * Vec(invstd) * Vec(w); }, + dx_ptr, + dy_ptr, + image_size); + } + } + } + + if (!grad_weight_null) { + grad_weight_data[c] = dotp * invstd; + } + + if (!grad_bias_null) { + grad_bias_data[c] = sum; + } + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_backward_channels_last_impl(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + + using Vec = Vectorized; + // keep acc_type as opmath_type will use float type when scalar_t==float + // while acc_type uses double for float. + using accscalar_t = at::acc_type; + int64_t n_channel = input.size(1); + int64_t N = input.numel() / n_channel; + + const scalar_t* grad_output_data = grad_output.const_data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + scalar_t* grad_input_data = grad_input.defined() ? grad_input.mutable_data_ptr() : nullptr; + scalar_t* grad_weight_data = grad_weight.defined() ? grad_weight.data_ptr() : nullptr; + scalar_t* grad_bias_data = grad_bias.defined() ? grad_bias.data_ptr() : nullptr; + + const scalar_t* save_mean_data = conditional_data_ptr(save_mean); + scalar_t* save_invstd_data = conditional_data_ptr(save_invstd); + const scalar_t* running_mean_data = conditional_data_ptr(running_mean); + const scalar_t* running_var_data = conditional_data_ptr(running_var); + + Tensor weight_ = weight.defined() ? weight : at::ones({n_channel}, input.options()); + const scalar_t* weight_data = weight_.const_data_ptr(); + + const scalar_t* mean_ptr = nullptr; + scalar_t* invstd_ptr = nullptr; + Tensor invstd = at::empty({0}, input.options()); + if (train) { + mean_ptr = save_mean_data; + invstd_ptr = save_invstd_data; + } else { + mean_ptr = running_mean_data; + + invstd.resize_({n_channel}); + invstd_ptr = invstd.data_ptr(); + for (const auto c : c10::irange(n_channel)) { + invstd_ptr[c] = 1 / std::sqrt(running_var_data[c] + eps); + } + } + + // Typical vertical reduce from shape of {NHW, C} to {C}. + // Apply two path parallel reduction: + // First path: allocate an immediate buffer of size {2, max_threads, C}, parallel along dim0, + // sum = buffer[0], dotp = buffer[2] + // + // Second path: parallel along dim1 of the immediate buffer. + // + int num_threads = at::get_num_threads(); + Tensor buffer = at::zeros({2, num_threads, n_channel}, input.options()); + scalar_t* sum_data = buffer.data_ptr(); + scalar_t* dotp_data = sum_data + num_threads * n_channel; + + // compute sum and dotp per feature plain, + // fuse into a single loop to reuse grad_output in L1. + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + scalar_t* sum_ptr = sum_data + tid * n_channel; + scalar_t* dotp_ptr = dotp_data + tid * n_channel; + for (const auto i : c10::irange(begin, end)) { + const scalar_t* x_ptr = input_data + i * n_channel; + const scalar_t* dy_ptr = grad_output_data + i * n_channel; + + vec::map2( + [](Vec sum, Vec dy) { return sum + dy; }, + sum_ptr, + sum_ptr, + dy_ptr, + n_channel); + + vec::map4( + [](Vec dotp, Vec x, Vec mean, Vec dy) { return dotp + (x - mean) * dy; }, + dotp_ptr, + dotp_ptr, + x_ptr, + mean_ptr, + dy_ptr, + n_channel); + } + }); + + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + // store the final result of sum and dotp in the 1st lane of immediate buffer, + // so that we won't need to allocate anther buffer to store the temp values. + accscalar_t _sum = 0; + for (const auto t : c10::irange(num_threads)) { + _sum += sum_data[t * n_channel + c]; + } + sum_data[/* 0 * n_channel + */c] = _sum; + + accscalar_t _dotp = 0; + for (const auto t : c10::irange(num_threads)) { + _dotp += dotp_data[t * n_channel + c]; + } + dotp_data[/* 0 * n_channel + */c] = _dotp; + } + }); + + // compute grad_input + const int64_t loop_size = n_channel - (n_channel % Vec::size()); + if (grad_input.defined()) { + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + scalar_t* dx_ptr = grad_input_data + i * n_channel; + const scalar_t* x_ptr = input_data + i * n_channel; + const scalar_t* dy_ptr = grad_output_data + i * n_channel; + if (train) { + int64_t d = 0; + for (; d < loop_size; d += Vec::size()) { + Vec x = Vec::loadu(x_ptr + d); + Vec mean = Vec::loadu(mean_ptr + d); + Vec dotp = Vec::loadu(dotp_data + d); + Vec invstd = Vec::loadu(invstd_ptr + d); + Vec k = dotp * invstd * invstd / Vec(N); + Vec dx = (x - mean) * k; + Vec dy = Vec::loadu(dy_ptr + d); + Vec grad_mean = Vec::loadu(sum_data + d) / Vec(N); + Vec w = Vec::loadu(weight_data + d); + dx = (dy - grad_mean - dx) * invstd * w; + dx.store(dx_ptr + d); + } + if (n_channel - d > 0) { + Vec x = Vec::loadu(x_ptr + d, n_channel - d); + Vec mean = Vec::loadu(mean_ptr + d, n_channel - d); + Vec dotp = Vec::loadu(dotp_data + d, n_channel - d); + Vec invstd = Vec::loadu(invstd_ptr + d, n_channel - d); + Vec k = dotp * invstd * invstd / Vec(N); + Vec dx = (x - mean) * k; + Vec dy = Vec::loadu(dy_ptr + d, n_channel - d); + Vec grad_mean = Vec::loadu(sum_data + d, n_channel - d) / Vec(N); + Vec w = Vec::loadu(weight_data + d, n_channel - d); + dx = (dy - grad_mean - dx) * invstd * w; + dx.store(dx_ptr + d, n_channel - d); + } + } else { // evaluation mode + int64_t d = 0; + for (; d < loop_size; d += Vec::size()) { + Vec dy = Vec::loadu(dy_ptr + d); + Vec invstd = Vec::loadu(invstd_ptr + d); + Vec w = Vec::loadu(weight_data + d); + Vec dx = dy * invstd * w; + dx.store(dx_ptr + d); + } + if (n_channel - d > 0) { + Vec dy = Vec::loadu(dy_ptr + d, n_channel - d); + Vec invstd = Vec::loadu(invstd_ptr + d, n_channel - d); + Vec w = Vec::loadu(weight_data + d, n_channel - d); + Vec dx = dy * invstd * w; + dx.store(dx_ptr + d, n_channel - d); + } + } + } + }); + } + + if (grad_weight.defined()) { + // grad_weight = dotp * invstd + vec::map2( + [](Vec dotp, Vec invstd) { return dotp * invstd; }, + grad_weight_data, + dotp_data, + invstd_ptr, + n_channel); + } + + // grad_bias = sum + if (grad_bias.defined()) { + vec::map( + [](Vec sum) { return sum; }, + grad_bias_data, + sum_data, + n_channel); + } +} + +/// bfloat16/Half kernels +template +typename std::enable_if_t>, void> +batch_norm_cpu_contiguous_impl(Tensor& output, const Tensor& input, + const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd, + const Tensor& running_mean, const Tensor& running_var, bool train, double eps) { + using opmath_t = at::opmath_type; + using bVec = Vectorized; + using fVec = Vectorized; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + + // use float as acc type + Tensor alpha = at::empty({n_channel}, input.options().dtype(kFloat)); + Tensor beta = at::empty({n_channel}, input.options().dtype(kFloat)); + opmath_t* alpha_data = alpha.mutable_data_ptr(); + opmath_t* beta_data = beta.data_ptr(); + + const bool mixed_type = is_mixed_type(input, weight, bias, save_mean, save_invstd, running_mean, running_var); + if (mixed_type) { + batch_norm_cpu_collect_linear_and_constant_terms( + alpha_data, beta_data, n_channel, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + } else { + batch_norm_cpu_collect_linear_and_constant_terms( + alpha_data, beta_data, n_channel, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + } + + scalar_t* output_data = output.data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + const int64_t loop_size = image_size - (image_size % bVec::size()); + at::parallel_for(0, n_batch * n_channel, 1, [&](int64_t begin, int64_t end) { + int64_t n = 0; + int64_t c = 0; + data_index_init(begin, n, n_batch, c, n_channel); + + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + i * image_size; + scalar_t* output_ptr = output_data + i * image_size; + const opmath_t alpha_val = alpha_data[c]; + const opmath_t beta_val = beta_data[c]; + const fVec alpha_fvec(alpha_val); + const fVec beta_fvec(beta_val); + int64_t d = 0; + for (; d < loop_size; d += bVec::size()) { + bVec data_bvec = bVec::loadu(input_ptr + d); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + + fVec out_fvec0 = data_fvec0 * alpha_fvec + beta_fvec; + fVec out_fvec1 = data_fvec1 * alpha_fvec + beta_fvec; + bVec out_bvec = convert_from_float(out_fvec0, out_fvec1); + out_bvec.store(output_ptr + d); + } + for (; d < image_size; d++) { + output_ptr[d] = scalar_t(opmath_t(input_ptr[d]) * alpha_val + beta_val); + } + // move on to next index + data_index_step(n, n_batch, c, n_channel); + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_channels_last_impl(Tensor& output, const Tensor& input, + const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd, + const Tensor& running_mean, const Tensor& running_var, bool train, double eps) { + using opmath_t = at::opmath_type; + using bVec = Vectorized; + using fVec = Vectorized; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + + Tensor alpha = at::empty({n_channel}, input.options().dtype(kFloat)); + Tensor beta = at::empty({n_channel}, input.options().dtype(kFloat)); + opmath_t* alpha_data = alpha.mutable_data_ptr(); + opmath_t* beta_data = beta.data_ptr(); + + const bool mixed_type = is_mixed_type(input, weight, bias, save_mean, save_invstd, running_mean, running_var); + if (mixed_type) { + batch_norm_cpu_collect_linear_and_constant_terms( + alpha_data, beta_data, n_channel, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + } else { + batch_norm_cpu_collect_linear_and_constant_terms( + alpha_data, beta_data, n_channel, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + } + + scalar_t* output_data = output.data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + const int64_t loop_size = n_channel - (n_channel % bVec::size()); + at::parallel_for(0, n_batch * image_size, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + i * n_channel; + scalar_t* output_ptr = output_data + i * n_channel; + int64_t d = 0; + for (; d < loop_size; d += bVec::size()) { + fVec alpha_fvec0 = fVec::loadu(alpha_data + d); + fVec alpha_fvec1 = fVec::loadu(alpha_data + d + fVec::size()); + fVec beta_fvec0 = fVec::loadu(beta_data + d); + fVec beta_fvec1 = fVec::loadu(beta_data + d + fVec::size()); + bVec data_bvec = bVec::loadu(input_ptr + d); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + + fVec out_fvec0 = data_fvec0 * alpha_fvec0 + beta_fvec0; + fVec out_fvec1 = data_fvec1 * alpha_fvec1 + beta_fvec1; + bVec out_bvec = convert_from_float(out_fvec0, out_fvec1); + out_bvec.store(output_ptr + d); + } + for (; d < n_channel; d++) { + output_ptr[d] = scalar_t(opmath_t(input_ptr[d]) * alpha_data[d] + beta_data[d]); + } + } + }); +} + +template +inline void batch_norm_cpu_collect_stats_contiguous_internal( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + using opmath_t = at::opmath_type; + using bVec = Vectorized; + using fVec = Vectorized; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + int64_t N = input.numel() / n_channel; + + const scalar_t* input_data = input.const_data_ptr(); + param_t* mean_data = mean.data_ptr(); + param_t* var_sum_data = var_sum.data_ptr(); + + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + opmath_t sum_val = opmath_t(0); + fVec sum_fvec = fVec(opmath_t(0)); + for (int64_t n = 0; n < n_batch; n++) { + const scalar_t* input_ptr = input_data + n * n_channel * image_size + c * image_size; + int64_t d = 0; + for (; d < image_size - (image_size % bVec::size()); d += bVec::size()) { + bVec data_bvec = bVec::loadu(input_ptr + d); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + sum_fvec += data_fvec0; + sum_fvec += data_fvec1; + } + for (; d < image_size; d++) { + sum_val += opmath_t(input_ptr[d]); + } + } + // TODO: use fast version + sum_val += vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, sum_fvec, fVec::size()); + opmath_t mean_val = sum_val / N; + mean_data[c] = param_t(mean_val); + + opmath_t var_val = opmath_t(0); + fVec var_fvec = fVec(opmath_t(0)); + fVec mean_fvec = fVec(mean_val); + for (int64_t n = 0; n < n_batch; n++) { + const scalar_t* input_ptr = input_data + n * n_channel * image_size + c * image_size; + int64_t d = 0; + for (; d < image_size - (image_size % bVec::size()); d += bVec::size()) { + bVec data_bvec = bVec::loadu(input_ptr + d); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + var_fvec += (data_fvec0 - mean_fvec) * (data_fvec0 - mean_fvec); + var_fvec += (data_fvec1 - mean_fvec) * (data_fvec1 - mean_fvec); + } + for (; d < image_size; d++) { + opmath_t data_val = input_ptr[d]; + var_val += (data_val - mean_val) * (data_val - mean_val); + } + } + // TODO: use fast version + var_val += vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, var_fvec, fVec::size()); + var_sum_data[c] = param_t(var_val); + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_collect_stats_contiguous_impl( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + const bool mixed_type = is_mixed_type(input, mean, var_sum); + if (mixed_type) { + batch_norm_cpu_collect_stats_contiguous_internal>(mean, var_sum, input); + } else { + batch_norm_cpu_collect_stats_contiguous_internal(mean, var_sum, input); + } +} + +template +inline void batch_norm_cpu_collect_stats_channels_last_internal( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + using opmath_t = at::opmath_type; + using bVec = Vectorized; + using fVec = Vectorized; + int64_t n_channel = input.size(1); + int64_t N = input.numel() / n_channel; + + const scalar_t* input_data = input.const_data_ptr(); + param_t* mean_data = mean.data_ptr(); + param_t* var_sum_data = var_sum.data_ptr(); + + int num_threads = at::get_num_threads(); + Tensor buffer = at::zeros({num_threads, n_channel}, input.options().dtype(kFloat)); + opmath_t* buffer_data = buffer.data_ptr(); + + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + opmath_t* buffer_ptr = buffer_data + tid * n_channel; + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + i * n_channel; + int64_t d = 0; + for (; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) { + bVec data_bvec = bVec::loadu(input_ptr + d); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + fVec sum_fvec0 = fVec::loadu(buffer_ptr + d) + data_fvec0; + fVec sum_fvec1 = fVec::loadu(buffer_ptr + d + fVec::size()) + data_fvec1; + sum_fvec0.store(buffer_ptr + d); + sum_fvec1.store(buffer_ptr + d + fVec::size()); + } + for (; d < n_channel; d++) { + buffer_ptr[d] += input_ptr[d]; + } + } + }); + + for (const auto c : c10::irange(n_channel)) { + opmath_t sum = 0; + for (const auto t : c10::irange(num_threads)) { + sum += buffer_data[t * n_channel + c]; + } + mean_data[c] = param_t(sum / N); + } + + buffer.zero_(); + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + opmath_t* buffer_ptr = buffer_data + tid * n_channel; + for (const auto i : c10::irange(begin, end)) { + const scalar_t* input_ptr = input_data + i * n_channel; + int64_t d = 0; + for (; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) { + bVec data_bvec = bVec::loadu(input_ptr + d); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + auto [mean_fvec0, mean_fvec1] = load2f(mean_data + d); + fVec var_fvec0 = fVec::loadu(buffer_ptr + d); + fVec var_fvec1 = fVec::loadu(buffer_ptr + d + fVec::size()); + var_fvec0 += (data_fvec0 - mean_fvec0) * (data_fvec0 - mean_fvec0); + var_fvec1 += (data_fvec1 - mean_fvec1) * (data_fvec1 - mean_fvec1); + var_fvec0.store(buffer_ptr + d); + var_fvec1.store(buffer_ptr + d + fVec::size()); + } + for (; d < n_channel; d++) { + opmath_t data_val = opmath_t(input_ptr[d]); + opmath_t mean_val = opmath_t(mean_data[d]); + buffer_ptr[d] += (data_val - mean_val) * (data_val - mean_val); + } + } + }); + + for (const auto c : c10::irange(n_channel)) { + opmath_t _var_sum = 0; + for (const auto t : c10::irange(num_threads)) { + _var_sum += buffer_data[t * n_channel + c]; + } + var_sum_data[c] = param_t(_var_sum); + } +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_collect_stats_channels_last_impl( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + const bool mixed_type = is_mixed_type(input, mean, var_sum); + if (mixed_type) { + batch_norm_cpu_collect_stats_channels_last_internal>(mean, var_sum, input); + } else { + batch_norm_cpu_collect_stats_channels_last_internal(mean, var_sum, input); + } +} + +template +void batch_norm_cpu_backward_contiguous_internal(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + using opmath_t = at::opmath_type; + using bVec = Vectorized; + using fVec = Vectorized; + int64_t n_batch = input.size(0); + int64_t n_channel = input.size(1); + int64_t image_size = input.numel() / n_batch / n_channel; + int64_t N = input.numel() / n_channel; + + const scalar_t* grad_output_data = grad_output.const_data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + scalar_t* grad_input_data = grad_input.defined() ? grad_input.mutable_data_ptr() : nullptr; + param_t* grad_weight_data = grad_weight.defined() ? grad_weight.data_ptr() : nullptr; + param_t* grad_bias_data = grad_bias.defined() ? grad_bias.data_ptr() : nullptr; + const bool grad_input_null = grad_input_data == nullptr; + const bool grad_weight_null = grad_weight_data == nullptr; + const bool grad_bias_null = grad_bias_data == nullptr; + + auto weight_a = conditional_accessor_1d(weight); + auto save_mean_a = conditional_accessor_1d(save_mean); + auto save_invstd_a = conditional_accessor_1d(save_invstd); + auto running_mean_a = conditional_accessor_1d(running_mean); + auto running_var_a = conditional_accessor_1d(running_var); + + // parallel dim reduce on 'channel' + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + opmath_t w = weight.defined() ? opmath_t(weight_a[c]) : 1; + + opmath_t mean, invstd; + if (train) { + mean = save_mean_a[c]; + invstd = save_invstd_a[c]; + } else { + mean = running_mean_a[c]; + invstd = 1 / std::sqrt(running_var_a[c] + eps); + } + + // compute 1) sum; 2) dot product of Q(X) and dY. + opmath_t sum{0}, dotp{0}; + fVec sum_fvec{0}, dotp_fvec{0}; + for (const auto n : c10::irange(n_batch)) { + const scalar_t* x_ptr = input_data + n * n_channel * image_size + c * image_size; + const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size; + + int64_t d = 0; + for (; d < image_size - (image_size % bVec::size()); d += bVec::size()) { + bVec dy_bvec = bVec::loadu(dy_ptr + d); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + sum_fvec += dy_fvec0; + sum_fvec += dy_fvec1; + + bVec x_bvec = bVec::loadu(x_ptr + d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + dotp_fvec += (x_fvec0 - fVec(mean)) * dy_fvec0; + dotp_fvec += (x_fvec1 - fVec(mean)) * dy_fvec1; + } + for (; d < image_size; d++) { + sum += opmath_t(dy_ptr[d]); + dotp += (opmath_t(x_ptr[d]) - mean) * opmath_t(dy_ptr[d]); + } + } + // TODO: use fast version + sum += vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, sum_fvec, fVec::size()); + dotp += vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, dotp_fvec, fVec::size()); + + if (!grad_input_null) { + if (train) { + opmath_t k = dotp * invstd * invstd / N; + opmath_t grad_mean = sum / N; + for (const auto n : c10::irange(n_batch)) { + const scalar_t* x_ptr = input_data + n * n_channel * image_size + c * image_size; + scalar_t* dx_ptr = grad_input_data + n * n_channel * image_size + c * image_size; + const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size; + vec::map2( + [=](fVec x, fVec dy) { + fVec dx = (x - fVec(mean)) * fVec(k); + return (dy - fVec(grad_mean) - dx) * fVec(invstd) * fVec(w); + }, + dx_ptr, x_ptr, dy_ptr, image_size); + } + } else { // evaluation mode + for (const auto n : c10::irange(n_batch)) { + scalar_t* dx_ptr = grad_input_data + n * n_channel * image_size + c * image_size; + const scalar_t* dy_ptr = grad_output_data + n * n_channel * image_size + c * image_size; + vec::map( + [=](fVec dy) { return dy * fVec(invstd) * fVec(w); }, + dx_ptr, dy_ptr, image_size); + } + } + } + + if (!grad_weight_null) { + grad_weight_data[c] = param_t(dotp * invstd); + } + + if (!grad_bias_null) { + grad_bias_data[c] = param_t(sum); + } + } + }); +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_backward_contiguous_impl(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + const bool mixed_type = is_mixed_type(input, weight, running_mean, running_var, save_mean, save_invstd); + if (mixed_type) { + batch_norm_cpu_backward_contiguous_internal>(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + } else { + batch_norm_cpu_backward_contiguous_internal(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + } +} + +template +void batch_norm_cpu_backward_channels_last_internal(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + using opmath_t = at::opmath_type; + using bVec = Vectorized; + using fVec = Vectorized; + int64_t n_channel = input.size(1); + int64_t N = input.numel() / n_channel; + + const scalar_t* grad_output_data = grad_output.const_data_ptr(); + const scalar_t* input_data = input.const_data_ptr(); + + scalar_t* grad_input_data = grad_input.defined() ? grad_input.mutable_data_ptr() : nullptr; + param_t* grad_weight_data = grad_weight.defined() ? grad_weight.data_ptr() : nullptr; + param_t* grad_bias_data = grad_bias.defined() ? grad_bias.data_ptr() : nullptr; + + auto weight_a = conditional_accessor_1d(weight); + auto save_mean_a = conditional_accessor_1d(save_mean); + auto save_invstd_a = conditional_accessor_1d(save_invstd); + auto running_mean_a = conditional_accessor_1d(running_mean); + auto running_var_a = conditional_accessor_1d(running_var); + + // use float as acc type + bool weight_defined = weight.defined(); + Tensor weight_f = at::empty({n_channel}, input.options().dtype(kFloat)); + Tensor mean = at::empty({n_channel}, input.options().dtype(kFloat)); + Tensor invstd = at::empty({n_channel}, input.options().dtype(kFloat)); + opmath_t* weight_data = weight_f.data_ptr(); + opmath_t* mean_data = mean.data_ptr(); + opmath_t* invstd_data = invstd.data_ptr(); + + for (const auto c : c10::irange(n_channel)) { + weight_data[c] = weight_defined ? opmath_t(weight_a[c]) : 1; + + if (train) { + mean_data[c] = save_mean_a[c]; + invstd_data[c] = save_invstd_a[c]; + } else { + mean_data[c] = running_mean_a[c]; + invstd_data[c] = 1 / std::sqrt(running_var_a[c] + eps); + } + } + + int num_threads = at::get_num_threads(); + Tensor buffer = at::zeros({2, num_threads, n_channel}, input.options().dtype(kFloat)); + opmath_t* sum_data = buffer.data_ptr(); + opmath_t* dotp_data = sum_data + num_threads * n_channel; + + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK(tid < num_threads, "expect thread id smaller than ", num_threads, ", got thread id ", tid); + opmath_t* sum_ptr = sum_data + tid * n_channel; + opmath_t* dotp_ptr = dotp_data + tid * n_channel; + for (const auto i : c10::irange(begin, end)) { + const scalar_t* x_ptr = input_data + i * n_channel; + const scalar_t* dy_ptr = grad_output_data + i * n_channel; + + int64_t d = 0; + for(; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) { + bVec dy_bvec = bVec::loadu(dy_ptr + d); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + fVec sum_fvec0 = dy_fvec0 + fVec::loadu(sum_ptr + d); + fVec sum_fvec1 = dy_fvec1 + fVec::loadu(sum_ptr + d + fVec::size()); + sum_fvec0.store(sum_ptr + d); + sum_fvec1.store(sum_ptr + d + fVec::size()); + + bVec x_bvec = bVec::loadu(x_ptr + d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + fVec mean_fvec0 = fVec::loadu(mean_data + d); + fVec mean_fvec1 = fVec::loadu(mean_data + d + fVec::size()); + fVec dotp_fvec0 = fVec::loadu(dotp_ptr + d); + fVec dotp_fvec1 = fVec::loadu(dotp_ptr + d + fVec::size()); + dotp_fvec0 += (x_fvec0 - mean_fvec0) * dy_fvec0; + dotp_fvec1 += (x_fvec1 - mean_fvec1) * dy_fvec1; + dotp_fvec0.store(dotp_ptr + d); + dotp_fvec1.store(dotp_ptr + d + fVec::size()); + } + for (; d < n_channel; d++) { + opmath_t dy_val = dy_ptr[d]; + opmath_t x_val = x_ptr[d]; + opmath_t mean_val = mean_data[d]; + sum_ptr[d] += dy_val; + dotp_ptr[d] += (x_val - mean_val) * dy_val; + } + } + }); + + at::parallel_for(0, n_channel, 1, [&](int64_t begin, int64_t end) { + for (const auto c : c10::irange(begin, end)) { + // store the final result of sum and dotp in the 1st lane of immediate buffer, + // so that we won't need to allocate anther buffer to store the temp values. + opmath_t _sum = 0; + for (const auto t : c10::irange(num_threads)) { + _sum += sum_data[t * n_channel + c]; + } + sum_data[/* 0 * n_channel + */c] = _sum; + + opmath_t _dotp = 0; + for (const auto t : c10::irange(num_threads)) { + _dotp += dotp_data[t * n_channel + c]; + } + dotp_data[/* 0 * n_channel + */c] = _dotp; + } + }); + + // compute grad_input + if (grad_input.defined()) { + at::parallel_for(0, N, 1, [&](int64_t begin, int64_t end) { + for (const auto i : c10::irange(begin, end)) { + scalar_t* dx_ptr = grad_input_data + i * n_channel; + const scalar_t* x_ptr = input_data + i * n_channel; + const scalar_t* dy_ptr = grad_output_data + i * n_channel; + if (train) { + int64_t d = 0; + for (; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) { + bVec x_bvec = bVec::loadu(x_ptr + d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + fVec mean_fvec0 = fVec::loadu(mean_data + d); + fVec mean_fvec1 = fVec::loadu(mean_data + d + fVec::size()); + fVec dotp_fvec0 = fVec::loadu(dotp_data + d); + fVec dotp_fvec1 = fVec::loadu(dotp_data + d + fVec::size()); + fVec invstd_fvec0 = fVec::loadu(invstd_data + d); + fVec invstd_fvec1 = fVec::loadu(invstd_data + d + fVec::size()); + fVec k_fvec0 = dotp_fvec0 * invstd_fvec0 * invstd_fvec0 / fVec(N); + fVec k_fvec1 = dotp_fvec1 * invstd_fvec1 * invstd_fvec1 / fVec(N); + fVec dx_fvec0 = (x_fvec0 - mean_fvec0) * k_fvec0; + fVec dx_fvec1 = (x_fvec1 - mean_fvec1) * k_fvec1; + bVec dy_bvec = bVec::loadu(dy_ptr + d); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + fVec grad_mean_fvec0 = fVec::loadu(sum_data + d) / fVec(N); + fVec grad_mean_fvec1 = fVec::loadu(sum_data + d + fVec::size()) / fVec(N); + fVec w_fvec0 = fVec::loadu(weight_data + d); + fVec w_fvec1 = fVec::loadu(weight_data + d + fVec::size()); + dx_fvec0 = (dy_fvec0 - grad_mean_fvec0 - dx_fvec0) * invstd_fvec0 * w_fvec0; + dx_fvec1 = (dy_fvec1 - grad_mean_fvec1 - dx_fvec1) * invstd_fvec1 * w_fvec1; + bVec dx_bvec = convert_from_float(dx_fvec0, dx_fvec1); + dx_bvec.store(dx_ptr + d); + } + for (; d < n_channel; d++) { + opmath_t x_val = x_ptr[d]; + opmath_t mean_val = mean_data[d]; + opmath_t dotp_val = dotp_data[d]; + opmath_t invstd_val = invstd_data[d]; + opmath_t k_val = dotp_val * invstd_val * invstd_val / N; + opmath_t dx_val = (x_val - mean_val) * k_val; + opmath_t dy_val = dy_ptr[d]; + opmath_t grad_mean_val = sum_data[d] / N; + opmath_t w_val = weight_data[d]; + dx_val = (dy_val - grad_mean_val - dx_val) * invstd_val * w_val; + dx_ptr[d] = scalar_t(dx_val); + } + } else { // evaluation mode + int64_t d = 0; + for (; d < n_channel - (n_channel % bVec::size()); d += bVec::size()) { + bVec dy_bvec = bVec::loadu(dy_ptr + d); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + fVec invstd_fvec0 = fVec::loadu(invstd_data + d); + fVec invstd_fvec1 = fVec::loadu(invstd_data + d + fVec::size()); + fVec w_fvec0 = fVec::loadu(weight_data + d); + fVec w_fvec1 = fVec::loadu(weight_data + d + fVec::size()); + fVec dx_fvec0 = dy_fvec0 * invstd_fvec0 * w_fvec0; + fVec dx_fvec1 = dy_fvec1 * invstd_fvec1 * w_fvec1; + bVec dx_bvec = convert_from_float(dx_fvec0, dx_fvec1); + dx_bvec.store(dx_ptr + d); + } + for (; d < n_channel; d++) { + opmath_t dy_val = dy_ptr[d]; + opmath_t invstd_val = invstd_data[d]; + opmath_t w_val = weight_data[d]; + opmath_t dx_val = dy_val * invstd_val * w_val; + dx_ptr[d] = scalar_t(dx_val); + } + } + } + }); + } + + if (grad_weight.defined()) { + for (const auto c : c10::irange(n_channel)) { + grad_weight_data[c] = param_t(dotp_data[c] * invstd_data[c]); + } + } + + if (grad_bias.defined()) { + for (const auto c : c10::irange(n_channel)) { + grad_bias_data[c] = param_t(sum_data[c]); + } + } +} + +template +typename std::enable_if_t>, void> +batch_norm_cpu_backward_channels_last_impl(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + const bool mixed_type = is_mixed_type(input, weight, running_mean, running_var, save_mean, save_invstd); + if (mixed_type) { + batch_norm_cpu_backward_channels_last_internal>(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + } else { + batch_norm_cpu_backward_channels_last_internal(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + } +} + +void batch_norm_cpu_kernel(Tensor& output, const Tensor& input, + const Tensor& weight, const Tensor& bias, const Tensor& save_mean, const Tensor& save_invstd, + const Tensor& running_mean, const Tensor& running_var, bool train, double eps) { + int64_t image_size = input.numel() / input.size(0) / input.size(1); + if (input.is_contiguous()) { // NC11 is also channels last + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "batch_norm_cpu_contiguous", [&] { + if (image_size == 1) { + batch_norm_cpu_channels_last_impl(output, input, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + } else { + batch_norm_cpu_contiguous_impl(output, input, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + } + }); + } else if (input.is_contiguous(at::MemoryFormat::ChannelsLast) || input.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "batch_norm_cpu_channels_last", [&] { + batch_norm_cpu_channels_last_impl(output, input, weight, bias, + save_mean, save_invstd, running_mean, running_var, train, eps); + }); + } else { + TORCH_CHECK(false, "batch_norm_cpu_kernel: expecting input to be contiguous."); + } +} + +void batch_norm_cpu_collect_stats_kernel( + Tensor& mean, Tensor& var_sum, const Tensor& input) { + int64_t image_size = input.numel() / input.size(0) / input.size(1); + if (input.is_contiguous()) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "batch_norm_cpu_collect_stats_contiguous", [&] { + if (image_size == 1) { // NC11 is also channels last + batch_norm_cpu_collect_stats_channels_last_impl(mean, var_sum, input); + } else { + batch_norm_cpu_collect_stats_contiguous_impl(mean, var_sum, input); + } + }); + } else if (input.is_contiguous(at::MemoryFormat::ChannelsLast) || input.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "batch_norm_cpu_collect_stats_channels_last", [&] { + batch_norm_cpu_collect_stats_channels_last_impl(mean, var_sum, input); + }); + } else { + TORCH_CHECK(false, "batch_norm_cpu_collect_stats_kernel: expecting input to be contiguous."); + } +} + +void batch_norm_cpu_backward_kernel(Tensor& grad_input, Tensor& grad_weight, Tensor& grad_bias, + const Tensor& grad_output, const Tensor& input, const Tensor& weight, + const Tensor& running_mean, const Tensor& running_var, const Tensor& save_mean, const Tensor& save_invstd, + bool train, double eps) { + int64_t image_size = input.numel() / input.size(0) / input.size(1); + if (input.is_contiguous()) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "batch_norm_cpu_backward_contiguous", [&] { + if (image_size == 1) { // NC11 is also channels last + batch_norm_cpu_backward_channels_last_impl(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + } else { + batch_norm_cpu_backward_contiguous_impl(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + } + }); + } else if (input.is_contiguous(at::MemoryFormat::ChannelsLast) || input.is_contiguous(at::MemoryFormat::ChannelsLast3d)) { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, input.scalar_type(), "batch_norm_cpu_backward_channels_last", [&] { + batch_norm_cpu_backward_channels_last_impl(grad_input, grad_weight, grad_bias, + grad_output, input, weight, running_mean, running_var, save_mean, save_invstd, train, eps); + }); + } else { + TORCH_CHECK(false, "batch_norm_cpu_backward_kernel: expecting input to be contiguous."); + } +} + +}// anonymous namespace + +REGISTER_DISPATCH(batch_norm_cpu_stub, &batch_norm_cpu_kernel) +REGISTER_DISPATCH(batch_norm_cpu_collect_stats_stub, &batch_norm_cpu_collect_stats_kernel) +REGISTER_DISPATCH(batch_norm_cpu_backward_stub, &batch_norm_cpu_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/group_norm_kernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/group_norm_kernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c2bdc472292a6dc390809eb19ffbb592011ad92 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/group_norm_kernel.cpp @@ -0,0 +1,1591 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace at::native { + +namespace { + +template +void GroupNormKernelImplInternal( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + double eps, + Tensor& Y, + Tensor& mean, + Tensor& rstd) { + TORCH_CHECK(X.numel() == N * C * HxW); + TORCH_CHECK(!gamma.defined() || gamma.numel() == C); + TORCH_CHECK(!beta.defined() || beta.numel() == C); + const int64_t G = group; + const int64_t D = C / G; + const T* X_data = X.const_data_ptr(); + const PT* gamma_data = gamma.defined() ? gamma.const_data_ptr() : nullptr; + const PT* beta_data = beta.defined() ? beta.const_data_ptr() : nullptr; + T* Y_data = Y.data_ptr(); + PT* mean_data = mean.data_ptr(); + PT* rstd_data = rstd.data_ptr(); + const bool gamma_null = (gamma_data == nullptr); + const bool beta_null = beta_data == nullptr; + const int64_t inner_size = D * HxW; + + using opmath_t = at::opmath_type; + + at::parallel_for(0, N * G, 1, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + const T* X_ptr = X_data + i * inner_size; + auto [mean_val, rstd_val] = RowwiseMoments(X_ptr, inner_size); + rstd_val = opmath_t(1) / std::sqrt(std::max(rstd_val, opmath_t(0)) + eps); + if (gamma_null && beta_null) { + T* Y_ptr = Y_data + i * inner_size; + for (const auto j : c10::irange(inner_size)) { + Y_ptr[j] = (X_ptr[j] - mean_val) * rstd_val; + } + } else { + const int64_t g = i % G; + for (const auto j : c10::irange(D)) { + const int64_t c = g * D + j; + const opmath_t scale = rstd_val * (gamma_null ? opmath_t(1) : opmath_t(gamma_data[c])); + const opmath_t bias = -scale * mean_val + (beta_null ? opmath_t(0) : opmath_t(beta_data[c])); + X_ptr = X_data + (i * D + j) * HxW; + T* Y_ptr = Y_data + (i * D + j) * HxW; + for (const auto k : c10::irange(HxW)) { + Y_ptr[k] = scale * X_ptr[k] + bias; + } + } + } + mean_data[i] = mean_val; + rstd_data[i] = rstd_val; + } + }); +} + +template +std::enable_if_t>, + std::tuple> +ColumnwiseMoments( + const T* X_data, + int64_t HxW, + int64_t C, + int64_t D) { + using Vec = vec::Vectorized; + constexpr int64_t K = Vec::size(); + const int64_t inner_size = D / K * K; + Vec acc0_vec{0}, acc1_vec{0}; + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + int64_t d = 0; + for (; d < inner_size; d += K) { + Vec x_vec = Vec::loadu(X_ptr + d); + acc0_vec += x_vec; + acc1_vec += x_vec * x_vec; + } + if (D - d > 0) { + Vec x_vec = Vec::loadu(X_ptr + d, D - d); + acc0_vec += x_vec; + acc1_vec += x_vec * x_vec; + } + } + T mean_val = vec::vec_reduce_all([](Vec& x, Vec& y) { return x + y; }, acc0_vec); + T rstd_val = vec::vec_reduce_all([](Vec& x, Vec& y) { return x + y; }, acc1_vec); + return std::tuple(mean_val, rstd_val); +} + + +// std::is_same || std::is_same +template +std::enable_if_t>, + std::tuple, at::opmath_type>> +ColumnwiseMoments( + const T* X_data, + int64_t HxW, + int64_t C, + int64_t D) { + using opmath_t = at::opmath_type; + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + constexpr int64_t K = Vec::size(); + const int64_t inner_size = D / K * K; + fVec acc0_fvec{0}, acc1_fvec{0}, zero{0}; + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + int64_t d = 0; + for (; d < inner_size; d += K) { + Vec x_bvec = Vec::loadu(X_ptr + d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + acc0_fvec += x_fvec0 + x_fvec1; + acc1_fvec += x_fvec0 * x_fvec0 + x_fvec1 * x_fvec1; + } + if (D - d > 0) { + Vec x_bvec = Vec::loadu(X_ptr + d, D - d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + if (D - d > fVec::size()) { + x_fvec1 = fVec::set(zero, x_fvec1, D - d - fVec::size()); + acc0_fvec += x_fvec0 + x_fvec1; + acc1_fvec += x_fvec0 * x_fvec0 + x_fvec1 * x_fvec1; + } else { + x_fvec0 = fVec::set(zero, x_fvec0, D - d); + acc0_fvec += x_fvec0; + acc1_fvec += x_fvec0 * x_fvec0; + } + } + } + opmath_t mean_val = vec::vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, acc0_fvec); + opmath_t rstd_val = vec::vec_reduce_all([](fVec& x, fVec& y) { return x + y; }, acc1_fvec); + return std::tuple(mean_val, rstd_val); +} + +template +inline std::enable_if_t, void> +CalcMeanVar( + const T* X_ptr, + opmath_t* mean_ptr, + opmath_t* rstd_ptr, + int64_t C) { + using Vec = vec::Vectorized; + vec::map2( + [](Vec x, Vec y) { return x + y; }, + mean_ptr, + X_ptr, + mean_ptr, + C); + vec::map2( + [](Vec x, Vec y) { return x * x + y; }, + rstd_ptr, + X_ptr, + rstd_ptr, + C); +} + +// std::is_same || std::is_same +template +inline std::enable_if_t, void> +CalcMeanVar( + const T* X_ptr, + opmath_t* mean_ptr, + opmath_t* rstd_ptr, + int64_t C) { + using fVec = vec::Vectorized; + using Vec = vec::Vectorized; + int64_t d = 0; + for (; d < C - (C % Vec::size()); d += Vec::size()) { + Vec data_bvec = Vec::loadu(X_ptr + d); + fVec mean_fvec0 = fVec::loadu(mean_ptr + d); + fVec mean_fvec1 = fVec::loadu(mean_ptr + d + fVec::size()); + fVec rstd_fvec0 = fVec::loadu(rstd_ptr + d); + fVec rstd_fvec1 = fVec::loadu(rstd_ptr + d + fVec::size()); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + mean_fvec0 = data_fvec0 + mean_fvec0; + mean_fvec1 = data_fvec1 + mean_fvec1; + rstd_fvec0 = data_fvec0 * data_fvec0 + rstd_fvec0; + rstd_fvec1 = data_fvec1 * data_fvec1 + rstd_fvec1; + mean_fvec0.store(mean_ptr + d); + mean_fvec1.store(mean_ptr + d + fVec::size()); + rstd_fvec0.store(rstd_ptr + d); + rstd_fvec1.store(rstd_ptr + d + fVec::size()); + } + if (C - d > 0) { + Vec data_bvec = Vec::loadu(X_ptr + d, C - d); + fVec mean_fvec0 = fVec::loadu(mean_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + fVec mean_fvec1 = fVec::loadu(mean_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + fVec rstd_fvec0 = fVec::loadu(rstd_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + fVec rstd_fvec1 = fVec::loadu(rstd_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + mean_fvec0 = data_fvec0 + mean_fvec0; + mean_fvec1 = data_fvec1 + mean_fvec1; + rstd_fvec0 = data_fvec0 * data_fvec0 + rstd_fvec0; + rstd_fvec1 = data_fvec1 * data_fvec1 + rstd_fvec1; + mean_fvec0.store(mean_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + mean_fvec1.store(mean_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + rstd_fvec0.store(rstd_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + rstd_fvec1.store(rstd_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + } +} + +template +inline std::enable_if_t, void> +ApplyScaleBias( + T* Y_ptr, + const T* X_ptr, + const opmath_t* scale_ptr, + const opmath_t* bias_ptr, + int64_t C) { + using Vec = vec::Vectorized; + vec::map3( + [](Vec x, Vec scale, Vec bias) { return x * scale + bias; }, + Y_ptr, + X_ptr, + scale_ptr, + bias_ptr, + C); +} + +// std::is_same || std::is_same +template +inline std::enable_if_t, void> +ApplyScaleBias( + T* Y_ptr, + const T* X_ptr, + const opmath_t* scale_ptr, + const opmath_t* bias_ptr, + int64_t C) { + using fVec = vec::Vectorized; + using Vec = vec::Vectorized; + int64_t d = 0; + for (; d < C - (C % Vec::size()); d += Vec::size()) { + Vec data_bvec = Vec::loadu(X_ptr + d); + fVec scale_fvec0 = fVec::loadu(scale_ptr + d); + fVec scale_fvec1 = fVec::loadu(scale_ptr + d + fVec::size()); + fVec bias_fvec0 = fVec::loadu(bias_ptr + d); + fVec bias_fvec1 = fVec::loadu(bias_ptr + d + fVec::size()); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + fVec out0 = data_fvec0 * scale_fvec0 + bias_fvec0; + fVec out1 = data_fvec1 * scale_fvec1 + bias_fvec1; + convert_from_float(out0, out1).store(Y_ptr + d); + } + if (C - d > 0) { + Vec data_bvec = Vec::loadu(X_ptr + d, C - d); + fVec scale_fvec0 = fVec::loadu(scale_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + fVec scale_fvec1 = fVec::loadu(scale_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + fVec bias_fvec0 = fVec::loadu(bias_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + fVec bias_fvec1 = fVec::loadu(bias_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + auto [data_fvec0, data_fvec1] = convert_to_float(data_bvec); + fVec out0 = data_fvec0 * scale_fvec0 + bias_fvec0; + fVec out1 = data_fvec1 * scale_fvec1 + bias_fvec1; + convert_from_float(out0, out1).store(Y_ptr + d, C - d); + } +} + +template +void GroupNormKernelImplChannelsLastInternal( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + double eps, + Tensor& Y, + Tensor& mean, + Tensor& rstd) { + TORCH_CHECK(X.numel() == N * C * HxW); + TORCH_CHECK(!gamma.defined() || gamma.numel() == C); + TORCH_CHECK(!beta.defined() || beta.numel() == C); + const int64_t G = group; + const int64_t D = C / G; + const T* X_data = X.const_data_ptr(); + const PT* gamma_data = gamma.defined() ? gamma.const_data_ptr() : nullptr; + const PT* beta_data = beta.defined() ? beta.const_data_ptr() : nullptr; + T* Y_data = Y.data_ptr(); + PT* mean_data = mean.data_ptr(); + PT* rstd_data = rstd.data_ptr(); + + using opmath_t = at::opmath_type; + + const opmath_t s = opmath_t(1) / static_cast(D * HxW); + const bool gamma_null = (gamma_data == nullptr); + const bool beta_null = beta_data == nullptr; + + // NB: About algorithm chosen: + // + // On channels last, GroupNorm has a input shape of {N, H, W, GD}, + // Mean and rstd are collected per each n and g, which involves reduction + // on non-adjacent dimensions. We can parallel in the following 2 impls: + // + // impl-1: parallel on N * G. Only need one omp session but memory access + // per thread is non-contiguous. + // + // impl-2: parallel on N * HxW. Memory access per thread is contiguous, + // but requires help of extra temp buffer of size {T, N, 2C}. + // + // Generally impl-2 has better performance when HxW is large enough, so that + // data per thread {NHWC / T} is much larger then temp buffer per thread {2NC} + // + constexpr int64_t feature_map_threshold = 1024; + if (HxW < feature_map_threshold) { + // impl-1: parallel on N * G. + // + // for each plain of HxW, scale and bias is calculated only once + Tensor buffer = at::empty({N * G, 2 * D}, X.options().dtype(c10::CppTypeToScalarType::value)); + opmath_t* buffer_data = buffer.data_ptr(); + + at::parallel_for(0, N * G, 1, [&](int64_t begin, int64_t end) { + int64_t n{0}, g{0}; + data_index_init(begin, n, N, g, G); + for (const auto i : c10::irange(begin, end)) { + // step-1: for each n and g, collect sum of x and x2 + // + // Note that using vec::map_reduce_all here is simpler to write + // but it is slower since horizontal reduce from vec to scalar is slow. + // So it is better to reduce with a vec across all HxW plain, + // and do a horizontal add just once for each {n, g}. + // + auto [mean_val, rstd_val] = ColumnwiseMoments( + X_data + n * HxW * C + g * D, + HxW, + C, + D); + + mean_val *= s; + rstd_val = std::max(rstd_val * s - mean_val * mean_val, opmath_t(0)); + rstd_val = opmath_t(1) / std::sqrt(rstd_val + eps); + mean_data[i] = mean_val; + rstd_data[i] = rstd_val; + + // step-2: calculate scale and bias + opmath_t* scale_ptr = buffer_data + i * 2 * D; + opmath_t* bias_ptr = scale_ptr + D; + for (const auto d : c10::irange(D)) { + const int64_t c = g * D + d; + scale_ptr[d] = rstd_val * (gamma_null ? opmath_t(1) : opmath_t(gamma_data[c])); + bias_ptr[d] = -scale_ptr[d] * mean_val + (beta_null ? opmath_t(0) : opmath_t(beta_data[c])); + } + + // step-3: apply scale and bias + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + n * HxW * C + m * C + g * D; + T* Y_ptr = Y_data + n * HxW * C + m * C + g * D; + ApplyScaleBias(Y_ptr, X_ptr, scale_ptr, bias_ptr, D); + } + + data_index_step(n, N, g, G); + } + }); + } else { + // impl-2: parallel on N * HxW. + // + // temp buffer holding x and x2 + int num_threads = at::get_num_threads(); + Tensor buffer = at::empty({num_threads, N, 2 * C}, + X.options().dtype(c10::CppTypeToScalarType::value)).zero_(); + opmath_t* buffer_data = buffer.data_ptr(); + Tensor tmp_buffer = at::empty({N, 2 * G}, + X.options().dtype(c10::CppTypeToScalarType::value)); + opmath_t* tmp_buffer_data = tmp_buffer.data_ptr(); + // step-1: accumulate on dimension of C + // + // In order to improve multi-core performance when N=1, + // we parallel on the all the outer dimensions of N and HxW, + // leaving the most inner dimension C for vectorization. + // + // Note that parallel on {N, HxW, G} is not feasible for some common configs, + // e.g. say input shape is {1, 32, h, w} and G = 8, + // this will give D = 4 which is unable to take full SIMD length. + // + // To avoid thread conflict, we make use of a temp buffer of {T, N, 2C}, + // firstly, reduce from {N, HxW, C} to {T, N, 2C} + // + at::parallel_for(0, N * HxW, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + opmath_t* buffer_ptr = buffer_data + tid * N * 2 * C; + + int64_t n{0}, m{0}; + data_index_init(begin, n, N, m, HxW); + for (const auto i : c10::irange(begin, end)) { + opmath_t* mean_ptr = buffer_ptr + n * 2 * C; + opmath_t* rstd_ptr = mean_ptr + C; + const T* X_ptr = X_data + i * C; + CalcMeanVar(X_ptr, mean_ptr, rstd_ptr, C); + data_index_step(n, N, m, HxW); + } + }); + + // step-2: compute mean and rstd + for (const auto n : c10::irange(N)) { + for (const auto g : c10::irange(G)) { + opmath_t mean_val{0}, rstd_val{0}; + for (const auto d : c10::irange(D)) { + for (const auto t : c10::irange(num_threads)) { + opmath_t* buffer_ptr = buffer_data + t * N * 2 * C + n * 2 * C; + mean_val += buffer_ptr[g * D + d]; + rstd_val += buffer_ptr[g * D + d + C]; + } + } + mean_val *= s; + rstd_val = std::max(rstd_val * s - mean_val * mean_val, opmath_t(0)); + rstd_val = opmath_t(1) / std::sqrt(rstd_val + eps); + tmp_buffer_data[n * 2 * G + 2 * g] = mean_val; + tmp_buffer_data[n * 2 * G + 2 * g + 1] = rstd_val; + } + } + + // step-3: compute scale and bias + // + // mean/rstd have shape of {N, G}, gamma/beta have shape of {G, D}. + // And scale/bias have shape of {N, C} so that we can directly vectorize on + // dimension of C in the final step. + // + // We could fuse step 3 and 4 into a single session but this way is better: + // a. D might be too small for vectorization; + // b. Avoid duplicate calculation of scale/bias, each HxW plain share the same scale/bias + // + for (const auto n : c10::irange(N)) { + for (const auto g : c10::irange(G)) { + opmath_t* scale_ptr = buffer_data + n * 2 * C; + opmath_t* bias_ptr = scale_ptr + C; + opmath_t mean_val = tmp_buffer_data[n * 2 * G + 2 * g]; + opmath_t rstd_val = tmp_buffer_data[n * 2 * G + 2 * g + 1]; + mean_data[n * G + g] = mean_val; + rstd_data[n * G + g] = rstd_val; + + for (const auto d : c10::irange(D)) { + const int64_t c = g * D + d; + scale_ptr[c] = rstd_val * (gamma_null ? opmath_t(1) : opmath_t(gamma_data[c])); + bias_ptr[c] = -scale_ptr[c] * mean_val + (beta_null ? opmath_t(0) : opmath_t(beta_data[c])); + } + } + } + + // step-4: apply scale and bias + // + // Parallel on on the all the outer dimensions of N and HxW + // and vectorize on C. + // + at::parallel_for(0, N * HxW, 1, [&](int64_t begin, int64_t end) { + int64_t n{0}, m{0}; + data_index_init(begin, n, N, m, HxW); + for (const auto i : c10::irange(begin, end)) { + const T* X_ptr = X_data + i * C; + T* Y_ptr = Y_data + i * C; + opmath_t* scale_ptr = buffer_data + n * 2 * C; + opmath_t* bias_ptr = scale_ptr + C; + ApplyScaleBias(Y_ptr, X_ptr, scale_ptr, bias_ptr, C); + data_index_step(n, N, m, HxW); + } + }); + } +} + +void GroupNormKernelImpl( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + double eps, + Tensor& Y, + Tensor& mean, + Tensor& rstd) { + const bool mixed_type = is_mixed_type(X, gamma, beta); + switch (X.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, X.scalar_type(), "GroupNormKernelImpl", [&]() { + using param_t = at::opmath_type; + if (mixed_type) { + GroupNormKernelImplInternal( + X, gamma, beta, N, C, HxW, group, eps, Y, mean, rstd); + } else { + GroupNormKernelImplInternal( + X, gamma, beta, N, C, HxW, group, eps, Y, mean, rstd); + } + }); + break; + } + case at::MemoryFormat::ChannelsLast: + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2(ScalarType::BFloat16, ScalarType::Half, X.scalar_type(), "GroupNormKernelImpl", [&]() { + using param_t = at::opmath_type; + if (mixed_type) { + GroupNormKernelImplChannelsLastInternal( + X, gamma, beta, N, C, HxW, group, eps, Y, mean, rstd); + } else { + GroupNormKernelImplChannelsLastInternal( + X, gamma, beta, N, C, HxW, group, eps, Y, mean, rstd); + } + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, ChannelsLast3d, Contiguous"); + } +} + + +template +std::enable_if_t, void> +ComputeInternalGradients( + int64_t N, + int64_t C, + int64_t HxW, + const T* dY, + const T* X, + opmath_t* ds, + opmath_t* db) { + using Vec = at::vec::Vectorized; + at::parallel_for(0, N * C, 1, [=](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + const T* dY_ptr = dY + i * HxW; + const T* X_ptr = X + i * HxW; + ds[i] = at::vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + dY_ptr, + X_ptr, + HxW); + db[i] = at::vec::reduce_all( + [](Vec& x, Vec& y) { return x + y; }, dY_ptr, HxW); + } + }); +} + +template +std::enable_if_t, void> +ComputeInternalGradients( + int64_t N, + int64_t C, + int64_t HxW, + const T* dY, + const T* X, + opmath_t* ds, + opmath_t* db) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + at::parallel_for(0, N * C, 1, [=](int64_t start, int64_t end) { + constexpr int64_t K = Vec::size(); + const int64_t inner_size = HxW / K * K; + std::array ds_arr{}; + std::array db_arr{}; + for (const auto i : c10::irange(start, end)) { + const T* dY_ptr = dY + i * HxW; + const T* X_ptr = X + i * HxW; + fVec ds_vec(0); + fVec db_vec(0); + for (int64_t j = 0; j < inner_size; j += K) { + const Vec dy_bvec = Vec::loadu(dY_ptr + j); + const Vec x_bvec = Vec::loadu(X_ptr + j); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + ds_vec = ds_vec + dy_fvec0 * x_fvec0; + ds_vec = ds_vec + dy_fvec1 * x_fvec1; + db_vec = db_vec + dy_fvec0 + dy_fvec1; + } + ds_vec.store(ds_arr.data()); + db_vec.store(db_arr.data()); + opmath_t ds_val = std::accumulate(ds_arr.cbegin(), ds_arr.cend(), opmath_t(0)); + opmath_t db_val = std::accumulate(db_arr.cbegin(), db_arr.cend(), opmath_t(0)); + for (const auto j : c10::irange(inner_size, HxW)) { + ds_val += opmath_t(dY_ptr[j]) * opmath_t(X_ptr[j]); + db_val += opmath_t(dY_ptr[j]); + } + ds[i] = ds_val; + db[i] = db_val; + } + }); +} + +template +inline std::enable_if_t, void> +CalcDsDb( + const opmath_t* ds_ptr, + const opmath_t* db_ptr, + const PT* gamma_ptr, + const int64_t d, + const int64_t K, + void* ds_arr, + void* db_arr) { + vec::Vectorized ds_vec(0); + vec::Vectorized db_vec(0); + for (int64_t j = 0; j < d; j += K) { + const vec::Vectorized gamma_vec = (gamma_ptr == nullptr) + ? vec::Vectorized(1) + : vec::Vectorized::loadu(gamma_ptr + j); + ds_vec = ds_vec + vec::Vectorized::loadu(ds_ptr + j) * gamma_vec; + db_vec = db_vec + vec::Vectorized::loadu(db_ptr + j) * gamma_vec; + } + ds_vec.store(ds_arr); + db_vec.store(db_arr); +} + +template +inline std::enable_if_t, void> +CalcDsDb( + const opmath_t* ds_ptr, + const opmath_t* db_ptr, + const PT* gamma_ptr, + const int64_t d, + const int64_t K, + void* ds_arr, + void* db_arr) { + using fVec = at::vec::Vectorized; + using Vec = at::vec::Vectorized; + fVec ds_acc(0); + fVec db_acc(0); + for (int64_t j = 0; j < d; j += K) { + const Vec gamma_vec = (gamma_ptr == nullptr) ? Vec(1) : Vec::loadu(gamma_ptr + j); + auto [gamma_vec0, gamma_vec1] = convert_to_float(gamma_vec); + ds_acc += fVec::loadu(ds_ptr + j) * gamma_vec0; + ds_acc += fVec::loadu(ds_ptr + j + fVec::size()) * gamma_vec1; + db_acc += fVec::loadu(db_ptr + j) * gamma_vec0; + db_acc += fVec::loadu(db_ptr + j + fVec::size()) * gamma_vec1; + } + ds_acc.store(ds_arr); + db_acc.store(db_arr); +} + +template +void GroupNormInputBackward( + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + const T* dY, + const T* X, + const PT* mean, + const PT* rstd, + const PT* gamma, + const opmath_t* ds, + const opmath_t* db, + T* dX) { + const int64_t G = group; + const int64_t D = C / G; + const opmath_t s = opmath_t(1) / static_cast(D * HxW); + const bool gamma_null = (gamma == nullptr); + at::parallel_for(0, N * G, 1, [=](int64_t start, int64_t end) { + constexpr int64_t K = vec::Vectorized::size(); + const int64_t d = D / K * K; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + std::array::size()> ds_arr; + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + std::array::size()> db_arr; + for (const auto i : c10::irange(start, end)) { + const int64_t g = i % G; + const opmath_t* ds_ptr = ds + i * D; + const opmath_t* db_ptr = db + i * D; + const PT* gamma_ptr = gamma_null ? nullptr : (gamma + g * D); + CalcDsDb(ds_ptr, db_ptr, gamma_ptr, d, K, ds_arr.data(), db_arr.data()); + opmath_t ds_val = std::accumulate(ds_arr.cbegin(), ds_arr.cend(), opmath_t(0)); + opmath_t db_val = std::accumulate(db_arr.cbegin(), db_arr.cend(), opmath_t(0)); + for (const auto j : c10::irange(d, D)) { + const opmath_t gamma_v = gamma_null ? opmath_t(1) : opmath_t(gamma[g * D + j]); + ds_val += ds_ptr[j] * gamma_v; + db_val += db_ptr[j] * gamma_v; + } + const opmath_t c2 = + (db_val * opmath_t(mean[i]) - ds_val) * opmath_t(rstd[i]) * opmath_t(rstd[i]) * opmath_t(rstd[i]) * s; + const opmath_t c3 = -c2 * opmath_t(mean[i]) - db_val * opmath_t(rstd[i]) * s; + + for (const auto j : c10::irange(D)) { + const int64_t c = g * D + j; + const T* dY_ptr = dY + (i * D + j) * HxW; + const T* X_ptr = X + (i * D + j) * HxW; + T* dX_ptr = dX + (i * D + j) * HxW; + const opmath_t c1 = opmath_t(rstd[i]) * (gamma_null ? opmath_t(1) : opmath_t(gamma[c])); + for (const auto k : c10::irange(HxW)) { + dX_ptr[k] = c1 * opmath_t(dY_ptr[k]) + c2 * opmath_t(X_ptr[k]) + c3; + } + } + } + }); +} + +template +std::enable_if_t, void> +GammaBackward( + int64_t N, + int64_t C, + int64_t group, + const PT* mean, + const PT* rstd, + const opmath_t* ds, + const opmath_t* db, + PT* dgamma) { + const int64_t G = group; + const int64_t D = C / G; + constexpr int64_t K = at::vec::Vectorized::size(); + using Vec = at::vec::Vectorized; + const int64_t inner_size = D / K * K; + for (const auto g : c10::irange(G)) { + int64_t i = 0; + for (; i < inner_size; i += K) { + Vec acc_vec{0}; + for (const auto n : c10::irange(N)) { + const PT* ds_ptr = ds + n * C + g * D + i; + const PT* db_ptr = db + n * C + g * D + i; + auto ds_vec = Vec::loadu(ds_ptr); + auto db_vec = Vec::loadu(db_ptr); + auto mean_vec = Vec(mean[n * G + g]); + auto rstd_vec = Vec(rstd[n * G + g]); + acc_vec += (ds_vec - db_vec * mean_vec) * rstd_vec; + } + acc_vec.store(dgamma + g * D + i); + } + if (D - i > 0) { + Vec acc_vec{0}; + for (const auto n : c10::irange(N)) { + const PT* ds_ptr = ds + n * C + g * D + i; + const PT* db_ptr = db + n * C + g * D + i; + auto ds_vec = Vec::loadu(ds_ptr, D - i); + auto db_vec = Vec::loadu(db_ptr, D - i); + auto mean_vec = Vec(mean[n * G + g]); + auto rstd_vec = Vec(rstd[n * G + g]); + acc_vec += (ds_vec - db_vec * mean_vec) * rstd_vec; + } + acc_vec.store(dgamma + g * D + i, D - i); + } + } +} + +template +std::enable_if_t, void> +GammaBackward( + int64_t N, + int64_t C, + int64_t group, + const PT* mean, + const PT* rstd, + const opmath_t* ds, + const opmath_t* db, + PT* dgamma) { + const int64_t G = group; + const int64_t D = C / G; + using Vec = at::vec::Vectorized; + using fVec = at::vec::Vectorized; + constexpr int64_t K = Vec::size(); + const int64_t inner_size = D / K * K; + for (const auto g : c10::irange(G)) { + int64_t i = 0; + for (; i < inner_size; i += K) { + fVec acc0_vec{0}, acc1_vec{0}; + for (const auto n : c10::irange(N)) { + const opmath_t* ds_ptr = ds + n * C + g * D + i; + const opmath_t* db_ptr = db + n * C + g * D + i; + fVec ds_vec0, ds_vec1, db_vec0, db_vec1; + ds_vec0 = fVec::loadu(ds_ptr); + ds_vec1 = fVec::loadu(ds_ptr + fVec::size()); + db_vec0 = fVec::loadu(db_ptr); + db_vec1 = fVec::loadu(db_ptr + fVec::size()); + fVec mean_vec = fVec(opmath_t(mean[n * G + g])); + fVec rstd_vec = fVec(opmath_t(rstd[n * G + g])); + acc0_vec += (ds_vec0 - db_vec0 * mean_vec) * rstd_vec; + acc1_vec += (ds_vec1 - db_vec1 * mean_vec) * rstd_vec; + } + convert_from_float(acc0_vec, acc1_vec).store(dgamma + g * D + i); + } + if (D - i > 0) { + fVec acc0_vec{0}, acc1_vec{0}; + for (const auto n : c10::irange(N)) { + const opmath_t* ds_ptr = ds + n * C + g * D + i; + const opmath_t* db_ptr = db + n * C + g * D + i; + fVec ds_vec0, ds_vec1, db_vec0, db_vec1; + ds_vec0 = fVec::loadu( + ds_ptr, (D - i) > fVec::size() ? fVec::size() : (D - i)); + ds_vec1 = fVec::loadu( + ds_ptr + fVec::size(), + (D - i) > fVec::size() ? (D - i - fVec::size()) : 0); + db_vec0 = fVec::loadu( + db_ptr, (D - i) > fVec::size() ? fVec::size() : (D - i)); + db_vec1 = fVec::loadu( + db_ptr + fVec::size(), + (D - i) > fVec::size() ? (D - i - fVec::size()) : 0); + fVec mean_vec = fVec(opmath_t(mean[n * G + g])); + fVec rstd_vec = fVec(opmath_t(rstd[n * G + g])); + acc0_vec += (ds_vec0 - db_vec0 * mean_vec) * rstd_vec; + acc1_vec += (ds_vec1 - db_vec1 * mean_vec) * rstd_vec; + } + convert_from_float(acc0_vec, acc1_vec).store(dgamma + g * D + i, D - i); + } + } +} + +template +std::enable_if_t, void> +BetaBackward(int64_t N, int64_t C, const opmath_t* db, PT* dbeta) { + using Vec = at::vec::Vectorized; + constexpr int64_t K = Vec::size(); + Vec acc_vec{0}, zero{0}; + const int64_t inner_size = C / K * K; + int64_t i = 0; + for (; i < inner_size; i += K) { + for (const auto n : c10::irange(N)) { + acc_vec += Vec::loadu(db + n * C + i); + } + acc_vec.store(dbeta + i); + acc_vec = Vec::set(acc_vec, zero); + } + if (C - i > 0) { + for (const auto n : c10::irange(N)) { + acc_vec += Vec::loadu(db + n * C + i, C - i); + } + acc_vec.store(dbeta + i, C - i); + acc_vec = Vec::set(acc_vec, zero, C - i); + } +} + +template +std::enable_if_t, void> +BetaBackward(int64_t N, int64_t C, const opmath_t* db, PT* dbeta) { + using Vec = at::vec::Vectorized; + using fVec = at::vec::Vectorized; + constexpr int64_t K = Vec::size(); + fVec acc0_vec{0}, acc1_vec{0}, zero{0}; + const int64_t inner_size = C / K * K; + int64_t i = 0; + for (; i < inner_size; i += K) { + for (const auto n : c10::irange(N)) { + fVec db_vec0, db_vec1; + db_vec0 = fVec::loadu(db + n * C + i); + db_vec1 = fVec::loadu(db + n * C + i + fVec::size()); + acc0_vec += db_vec0; + acc1_vec += db_vec1; + } + convert_from_float(acc0_vec, acc1_vec).store(dbeta + i); + acc0_vec = fVec::set(acc0_vec, zero); + acc1_vec = fVec::set(acc1_vec, zero); + } + if (C - i > 0) { + for (const auto n : c10::irange(N)) { + fVec db_vec0, db_vec1; + db_vec0 = fVec::loadu( + db + n * C + i, (C - i) > fVec::size() ? fVec::size() : (C - i)); + db_vec1 = fVec::loadu( + db + n * C + i + fVec::size(), + (C - i) > fVec::size() ? (C - i - fVec::size()) : 0); + acc0_vec += db_vec0; + acc1_vec += db_vec1; + } + convert_from_float(acc0_vec, acc1_vec).store(dbeta + i, C - i); + acc0_vec = fVec::set(acc0_vec, zero, C - i); + acc1_vec = fVec::set(acc1_vec, zero, C - i); + } +} + +template +void GroupNormBackwardKernelImplInternal( + const Tensor& dY, + const Tensor& X, + const Tensor& mean, + const Tensor& rstd, + const Tensor& gamma, + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + Tensor& dX, + Tensor& dgamma, + Tensor& dbeta) { + TORCH_CHECK(dY.numel() == N * C * HxW); + TORCH_CHECK(X.numel() == N * C * HxW); + TORCH_CHECK(mean.numel() == N * group); + TORCH_CHECK(rstd.numel() == N * group); + TORCH_CHECK(!gamma.defined() || gamma.numel() == C); + const T* dY_data = dY.const_data_ptr(); + const T* X_data = X.const_data_ptr(); + const PT* mean_data = mean.const_data_ptr(); + const PT* rstd_data = rstd.const_data_ptr(); + const PT* gamma_data = gamma.defined() ? gamma.const_data_ptr() : nullptr; + T* dX_data = dX.defined() ? dX.data_ptr() : nullptr; + PT* dgamma_data = dgamma.defined() ? dgamma.data_ptr() : nullptr; + PT* dbeta_data = dbeta.defined() ? dbeta.data_ptr() : nullptr; + using opmath_t = at::opmath_type; + Tensor ds = at::empty({N, C}, X.options().dtype(c10::CppTypeToScalarType::value)); + Tensor db = at::empty({N, C}, X.options().dtype(c10::CppTypeToScalarType::value)); + opmath_t* ds_data = ds.data_ptr(); + opmath_t* db_data = db.data_ptr(); + ComputeInternalGradients(N, C, HxW, dY_data, X_data, ds_data, db_data); + + if (dX_data != nullptr) { + GroupNormInputBackward( + N, + C, + HxW, + group, + dY_data, + X_data, + mean_data, + rstd_data, + gamma_data, + ds_data, + db_data, + dX_data); + } + if (dgamma_data != nullptr) { + GammaBackward( + N, C, group, mean_data, rstd_data, ds_data, db_data, dgamma_data); + } + if (dbeta_data != nullptr) { + BetaBackward(N, C, db_data, dbeta_data); + } +} + +template +inline std::enable_if_t, void> +DsDbRowwiseMomentsChannelsLast( + const T* dY_ptr, + const T* X_ptr, + opmath_t* ds_ptr, + opmath_t* db_ptr, + int64_t C) { + using Vec = vec::Vectorized; + constexpr int64_t K = vec::Vectorized::size(); + const int64_t inner_size = C / K * K; + int64_t d = 0; + for (; d < inner_size; d += K) { + Vec ds_dev = Vec::loadu(ds_ptr + d); + Vec db_vec = Vec::loadu(db_ptr + d); + Vec x_vec = Vec::loadu(X_ptr + d); + Vec dy_vec = Vec::loadu(dY_ptr + d); + + ds_dev += x_vec * dy_vec; + db_vec += dy_vec; + ds_dev.store(ds_ptr + d); + db_vec.store(db_ptr + d); + } + if (C - d > 0) { + Vec ds_dev = Vec::loadu(ds_ptr + d, C - d); + Vec db_vec = Vec::loadu(db_ptr + d, C - d); + Vec x_vec = Vec::loadu(X_ptr + d, C - d); + Vec dy_vec = Vec::loadu(dY_ptr + d, C - d); + ds_dev += x_vec * dy_vec; + db_vec += dy_vec; + ds_dev.store(ds_ptr + d, C - d); + db_vec.store(db_ptr + d, C - d); + } +} + +template +inline std::enable_if_t, void> +DsDbRowwiseMomentsChannelsLast( + const T* dY_ptr, + const T* X_ptr, + opmath_t* ds_ptr, + opmath_t* db_ptr, + int64_t C) { + using fVec = vec::Vectorized; + using Vec = vec::Vectorized; + int64_t d = 0; + for (; d < C - (C % Vec::size()); d += Vec::size()) { + fVec ds_dev0 = fVec::loadu(ds_ptr + d); + fVec ds_dev1 = fVec::loadu(ds_ptr + d + fVec::size()); + fVec db_vec0 = fVec::loadu(db_ptr + d); + fVec db_vec1 = fVec::loadu(db_ptr + d + fVec::size()); + Vec x_vec = Vec::loadu(X_ptr + d); + Vec dy_vec = Vec::loadu(dY_ptr + d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + ds_dev0 += x_vec0 * dy_vec0; + ds_dev1 += x_vec1 * dy_vec1; + db_vec0 += dy_vec0; + db_vec1 += dy_vec1; + + ds_dev0.store(ds_ptr + d); + ds_dev1.store(ds_ptr + d + fVec::size()); + db_vec0.store(db_ptr + d); + db_vec1.store(db_ptr + d + fVec::size()); + + } + if (C - d > 0) { + fVec ds_dev0 = fVec::loadu(ds_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + fVec ds_dev1 = fVec::loadu(ds_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + fVec db_vec0 = fVec::loadu(db_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + fVec db_vec1 = fVec::loadu(db_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + Vec x_vec = Vec::loadu(X_ptr + d, C - d); + Vec dy_vec = Vec::loadu(dY_ptr + d, C - d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + ds_dev0 += x_vec0 * dy_vec0; + ds_dev1 += x_vec1 * dy_vec1; + db_vec0 += dy_vec0; + db_vec1 += dy_vec1; + + ds_dev0.store(ds_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + ds_dev1.store(ds_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + db_vec0.store(db_ptr + d, (C - d) > fVec::size() ? fVec::size() : (C - d)); + db_vec1.store(db_ptr + d + fVec::size(), (C - d) > fVec::size() ? (C - d - fVec::size()) : 0); + } +} + +template +inline std::enable_if_t>, + std::tuple< + vec::Vectorized, + vec::Vectorized>> +load_util(const T* data_ptr, int64_t n) { + using Vec = vec::Vectorized; + auto vec0 = Vec::loadu(data_ptr, n > Vec::size() ? Vec::size() : n); + auto vec1 = Vec::loadu( + data_ptr + Vec::size(), n > Vec::size() ? (n - Vec::size()) : 0); + return std::tuple(vec0, vec1); +} + +template +inline std::enable_if_t>, + std::tuple< + vec::Vectorized>, + vec::Vectorized>> + > +load_util(const T* data_ptr, int64_t n) { + using Vec = vec::Vectorized; + auto vec = Vec::loadu(data_ptr, n); + return convert_to_float(vec); +} + +template +inline std::enable_if_t, void> +ApplyInputGradientsChannelsLastColMov( + const T* dY_data, + const T* X_data, + T* dX_data, + const PT* rstd, + const PT* gamma, + opmath_t c2, + opmath_t c3, + int64_t HxW, + int64_t C, + int64_t D) { + const bool gamma_null = (gamma == nullptr); + int64_t d = 0; + auto K = vec::Vectorized::size(); + for (; d < D / K * K; d += K) { + auto c1 = vec::Vectorized(*rstd) * + (gamma_null ? vec::Vectorized(1) + : vec::Vectorized::loadu(gamma + d)); + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + T* dX_ptr = dX_data + m * C; + auto dy_vec = vec::Vectorized::loadu(dY_ptr + d); + auto x_vec = vec::Vectorized::loadu(X_ptr + d); + auto dx_vec = c1 * dy_vec + + vec::Vectorized(c2) * x_vec + vec::Vectorized(c3); + dx_vec.store(dX_ptr + d); + } + } + if (D - d > 0) { + auto c1 = vec::Vectorized(*rstd) * + (gamma_null ? vec::Vectorized(1) + : vec::Vectorized::loadu(gamma + d, D - d)); + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + T* dX_ptr = dX_data + m * C; + auto dy_vec = vec::Vectorized::loadu(dY_ptr + d, D - d); + auto x_vec = vec::Vectorized::loadu(X_ptr + d, D - d); + auto dx_vec = c1 * dy_vec + + vec::Vectorized(c2) * x_vec + vec::Vectorized(c3); + dx_vec.store(dX_ptr + d, D - d); + } + } +} + +template +inline std::enable_if_t, void> +ApplyInputGradientsChannelsLastColMov( + const T* dY_data, + const T* X_data, + T* dX_data, + const PT* rstd, + const PT* gamma, + opmath_t c2, + opmath_t c3, + int64_t HxW, + int64_t C, + int64_t D) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + const bool gamma_null = (gamma == nullptr); + auto K = Vec::size(); + int64_t d = 0; + for (; d < D / K * K; d += K) { + auto [c1_0, c1_1] = gamma_null ? std::tuple(fVec(1), fVec(1)) + : load_util(gamma + d, K); + c1_0 = c1_0 * fVec(opmath_t(*rstd)); + c1_1 = c1_1 * fVec(opmath_t(*rstd)); + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + T* dX_ptr = dX_data + m * C; + + Vec dy_vec = Vec::loadu(dY_ptr + d); + Vec x_vec = Vec::loadu(X_ptr + d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + fVec dx_vec0 = c1_0 * dy_vec0 + fVec(c2) * x_vec0 + fVec(c3); + fVec dx_vec1 = c1_1 * dy_vec1 + fVec(c2) * x_vec1 + fVec(c3); + convert_from_float(dx_vec0, dx_vec1).store(dX_ptr + d); + } + } + if (D - d > 0) { + auto [c1_0, c1_1] = gamma_null ? std::tuple(fVec(1), fVec(1)) + : load_util(gamma + d, D - d); + c1_0 = c1_0 * fVec(opmath_t(*rstd)); + c1_1 = c1_1 * fVec(opmath_t(*rstd)); + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + T* dX_ptr = dX_data + m * C; + Vec dy_vec = Vec::loadu(dY_ptr + d, D - d); + Vec x_vec = Vec::loadu(X_ptr + d, D - d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + fVec dx_vec0 = c1_0 * dy_vec0 + fVec(c2) * x_vec0 + fVec(c3); + fVec dx_vec1 = c1_1 * dy_vec1 + fVec(c2) * x_vec1 + fVec(c3); + convert_from_float(dx_vec0, dx_vec1).store(dX_ptr + d, D - d); + } + } +} + +template +inline std::enable_if_t, void> +ApplyInputGradientsChannelsLastRowMov( + const T* dY_data, + const T* X_data, + T* dX_data, + const PT* rstd, + const PT* gamma, + opmath_t c2, + opmath_t c3, + int64_t HxW, + int64_t C, + int64_t D) { + const bool gamma_null = (gamma == nullptr); + int64_t d = 0; + auto K = vec::Vectorized::size(); + for (; d < D / K * K; d += K) { + auto c1 = vec::Vectorized(*rstd) * + (gamma_null ? vec::Vectorized(1) : vec::Vectorized::loadu(gamma + d)); + auto dy_vec = vec::Vectorized::loadu(dY_data + d); + auto x_vec = vec::Vectorized::loadu(X_data + d); + auto dx_vec = c1 * dy_vec + + vec::Vectorized(c2) * x_vec + vec::Vectorized(c3); + dx_vec.store(dX_data + d); + } + if (D - d > 0) { + auto c1 = vec::Vectorized(*rstd) * + (gamma_null ? vec::Vectorized(1) : vec::Vectorized::loadu(gamma + d, D - d)); + auto dy_vec = vec::Vectorized::loadu(dY_data + d, D - d); + auto x_vec = vec::Vectorized::loadu(X_data + d, D - d); + auto dx_vec = c1 * dy_vec + + vec::Vectorized(c2) * x_vec + vec::Vectorized(c3); + dx_vec.store(dX_data + d, D - d); + } +} + +template +inline std::enable_if_t, void> +ApplyInputGradientsChannelsLastRowMov( + const T* dY_data, + const T* X_data, + T* dX_data, + const PT* rstd, + const PT* gamma, + opmath_t c2, + opmath_t c3, + int64_t HxW, + int64_t C, + int64_t D) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + const bool gamma_null = (gamma == nullptr); + auto K = Vec::size(); + int64_t d = 0; + for (; d < D / K * K; d += K) { + auto [c1_0, c1_1] = gamma_null ? std::tuple(fVec(1), fVec(1)) + : load_util(gamma + d, K); + c1_0 = c1_0 * fVec(opmath_t(*rstd)); + c1_1 = c1_1 * fVec(opmath_t(*rstd)); + Vec dy_vec = Vec::loadu(dY_data + d); + Vec x_vec = Vec::loadu(X_data + d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + fVec dx_vec0 = c1_0 * dy_vec0 + fVec(c2) * x_vec0 + fVec(c3); + fVec dx_vec1 = c1_1 * dy_vec1 + fVec(c2) * x_vec1 + fVec(c3); + convert_from_float(dx_vec0, dx_vec1).store(dX_data + d); + } + if (D - d > 0) { + auto [c1_0, c1_1] = gamma_null ? std::tuple(fVec(1), fVec(1)) + : load_util(gamma + d, D - d); + c1_0 = c1_0 * fVec(opmath_t(*rstd)); + c1_1 = c1_1 * fVec(opmath_t(*rstd)); + Vec dy_vec = Vec::loadu(dY_data + d, D - d); + Vec x_vec = Vec::loadu(X_data + d, D - d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + fVec dx_vec0 = c1_0 * dy_vec0 + fVec(c2) * x_vec0 + fVec(c3); + fVec dx_vec1 = c1_1 * dy_vec1 + fVec(c2) * x_vec1 + fVec(c3); + convert_from_float(dx_vec0, dx_vec1).store(dX_data + d, D - d); + } +} + +template +inline typename std:: + enable_if, std::tuple>::type + CalcInternalGradientsChannelsLast( + const T* X_data, + const T* dY_data, + const PT* gamma_ptr, + opmath_t* ds_ptr, + opmath_t* db_ptr, + int64_t HxW, + int64_t C, + int64_t D) { + using Vec = vec::Vectorized; + const bool gamma_null = (gamma_ptr == nullptr); + constexpr int64_t K = Vec::size(); + const int64_t inner_size = D / K * K; + int64_t d = 0; + opmath_t ds_gamma{0}, db_gamma{0}; + for (; d < inner_size; d += K) { + Vec acc0_vec{0}, acc1_vec{0}; + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + Vec x_vec = Vec::loadu(X_ptr + d); + Vec dy_vec = Vec::loadu(dY_ptr + d); + acc0_vec += x_vec * dy_vec; + acc1_vec += dy_vec; + } + acc0_vec.store(ds_ptr + d); + acc1_vec.store(db_ptr + d); + ds_gamma += vec::vec_reduce_all([](Vec& x, Vec& y) { return x + y; }, + acc0_vec * (gamma_null ? Vec(1) : Vec::loadu(gamma_ptr + d))); + db_gamma += vec::vec_reduce_all([](Vec& x, Vec& y) { return x + y; }, + acc1_vec * (gamma_null ? Vec(1) : Vec::loadu(gamma_ptr + d))); + } + if (D - d > 0) { + Vec acc0_vec{0}, acc1_vec{0}; + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + Vec x_vec = Vec::loadu(X_ptr + d, D - d); + Vec dy_vec = Vec::loadu(dY_ptr + d, D - d); + acc0_vec += x_vec * dy_vec; + acc1_vec += dy_vec; + } + acc0_vec.store(ds_ptr + d, D - d); + acc1_vec.store(db_ptr + d, D - d); + ds_gamma += vec::vec_reduce_all([](Vec& x, Vec& y) { return x + y; }, + acc0_vec * (gamma_null ? Vec(1) : Vec::loadu(gamma_ptr + d, D - d))); + db_gamma += vec::vec_reduce_all([](Vec& x, Vec& y) { return x + y; }, + acc1_vec * (gamma_null ? Vec(1) : Vec::loadu(gamma_ptr + d, D - d))); + } + return std::tuple(ds_gamma, db_gamma); +} + +template +inline typename std:: + enable_if, std::tuple>::type + CalcInternalGradientsChannelsLast( + const T* X_data, + const T* dY_data, + const PT* gamma_ptr, + opmath_t* ds_ptr, + opmath_t* db_ptr, + int64_t HxW, + int64_t C, + int64_t D) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized; + const bool gamma_null = (gamma_ptr == nullptr); + constexpr int64_t K = Vec::size(); + const int64_t inner_size = D / K * K; + float ds_gamma{0}, db_gamma{0}; + int64_t d = 0; + for (; d < inner_size; d += K) { + fVec acc0_vec0{0}, acc0_vec1{0}, acc1_vec0{0}, acc1_vec1{0}; + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + Vec x_vec = Vec::loadu(X_ptr + d); + Vec dy_vec = Vec::loadu(dY_ptr + d); + auto [x_vec0, x_vec1] = convert_to_float(x_vec); + auto [dy_vec0, dy_vec1] = convert_to_float(dy_vec); + acc0_vec0 += x_vec0 * dy_vec0; + acc0_vec1 += x_vec1 * dy_vec1; + acc1_vec0 += dy_vec0; + acc1_vec1 += dy_vec1; + } + acc0_vec0.store(ds_ptr + d); + acc0_vec1.store(ds_ptr + d + fVec::size()); + acc1_vec0.store(db_ptr + d); + acc1_vec1.store(db_ptr + d + fVec::size()); + auto [gamma_vec0, gamma_vec1] = gamma_null ? + std::tuple(fVec(1), fVec(1)) : load_util(gamma_ptr + d, K); + ds_gamma += vec::vec_reduce_all( + [](fVec& x, fVec& y) { return x + y; }, acc0_vec0 * gamma_vec0); + ds_gamma += vec::vec_reduce_all( + [](fVec& x, fVec& y) { return x + y; }, acc0_vec1 * gamma_vec1); + db_gamma += vec::vec_reduce_all( + [](fVec& x, fVec& y) { return x + y; }, acc1_vec0 * gamma_vec0); + db_gamma += vec::vec_reduce_all( + [](fVec& x, fVec& y) { return x + y; }, acc1_vec1 * gamma_vec1); + } + for (; d < D; d++) { + opmath_t acc0{0}, acc1{0}; + for (const auto m : c10::irange(HxW)) { + const T* X_ptr = X_data + m * C; + const T* dY_ptr = dY_data + m * C; + acc0 += opmath_t(X_ptr[d]) * opmath_t(dY_ptr[d]); + acc1 += opmath_t(dY_ptr[d]); + } + ds_ptr[d] = acc0; + db_ptr[d] = acc1; + opmath_t gamma_val = gamma_null ? opmath_t(1) : opmath_t(gamma_ptr[d]); + ds_gamma += acc0 * gamma_val; + db_gamma += acc1 * gamma_val; + } + + return std::tuple(ds_gamma, db_gamma); +} + +template +void GroupNormBackwardKernelImplChannelsLastInternal( + const Tensor& dY, + const Tensor& X, + const Tensor& mean, + const Tensor& rstd, + const Tensor& gamma, + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + Tensor& dX, + Tensor& dgamma, + Tensor& dbeta) { + TORCH_CHECK(dY.numel() == N * C * HxW); + TORCH_CHECK(X.numel() == N * C * HxW); + TORCH_CHECK(mean.numel() == N * group); + TORCH_CHECK(rstd.numel() == N * group); + TORCH_CHECK(!gamma.defined() || gamma.numel() == C); + int64_t D = C / group; + int64_t G = group; + const T* dY_data = dY.const_data_ptr(); + const T* X_data = X.const_data_ptr(); + const PT* mean_data = mean.const_data_ptr(); + const PT* rstd_data = rstd.const_data_ptr(); + const PT* gamma_data = gamma.defined() ? gamma.const_data_ptr() : nullptr; + T* dX_data = dX.defined() ? dX.data_ptr() : nullptr; + PT* dgamma_data = dgamma.defined() ? dgamma.data_ptr() : nullptr; + PT* dbeta_data = dbeta.defined() ? dbeta.data_ptr() : nullptr; + const bool gamma_null = (gamma_data == nullptr); + using opmath_t = at::opmath_type; + Tensor ds = at::empty({N, C}, X.options().dtype(c10::CppTypeToScalarType::value)); + Tensor db = at::empty({N, C}, X.options().dtype(c10::CppTypeToScalarType::value)); + opmath_t* ds_data = ds.data_ptr(); + opmath_t* db_data = db.data_ptr(); + const opmath_t s = opmath_t(1) / static_cast(D * HxW); + + // Similar to channels last forward, channels last backward has also 2 impls. + // impl-1: parallel on N * G. Only need one omp session for input gradients + // but memory access per thread is non-contiguous. + // + // impl-2: parallel on N * HxW. Memory access per thread is contiguous, + // but requires help of extra temp buffer of size {T, N, 2C}. + + // Generally impl-2 has better performance when HxW is large enough, so that + // data per thread {NHWC / T} is much larger then temp buffer per thread {2NC} + constexpr int64_t feature_map_threshold = 2048; + if (HxW < feature_map_threshold) { + // impl-1: parallel on N * G. + at::parallel_for(0, N * G, 1, [=](int64_t begin, int64_t end) { + int64_t n{0}, g{0}; + data_index_init(begin, n, N, g, G); + for (const auto i : c10::irange(begin, end)) { + // Step 1. Compute internal gradients. + opmath_t* ds_ptr = ds_data + i * D; + opmath_t* db_ptr = db_data + i * D; + const T* X_ptr = X_data + n * HxW * C + g * D; + const T* dY_ptr = dY_data + n * HxW * C + g * D; + const PT* gamma_ptr = gamma_null ? gamma_data : (gamma_data + g * D); + auto [ds_gamma, db_gamma] = CalcInternalGradientsChannelsLast( + X_ptr, + dY_ptr, + gamma_ptr, + ds_ptr, + db_ptr, + HxW, + C, + D); + + // Step 2. Compute dX. + if (dX_data) { + T* dX_ptr = dX_data + n * HxW * C + g * D; + const PT* rstd_ptr = rstd_data + i; + const opmath_t c2 = (db_gamma * opmath_t(mean_data[i]) - ds_gamma) * + opmath_t(rstd_data[i]) * opmath_t(rstd_data[i]) * opmath_t(rstd_data[i]) * s; + const opmath_t c3 = -c2 * opmath_t(mean_data[i]) - db_gamma * opmath_t(rstd_data[i]) * s; + ApplyInputGradientsChannelsLastColMov(dY_ptr, X_ptr, dX_ptr, rstd_ptr, gamma_ptr, c2, c3, HxW, C, D); + } + + data_index_step(n, N, g, G); + } + }); + + } else { + // impl-2: parallel on N * HxW. + int num_threads = at::get_num_threads(); + Tensor buffer = at::empty({num_threads, N, 2 * C}, + X.options().dtype(c10::CppTypeToScalarType::value)).zero_(); + opmath_t* buffer_data = buffer.data_ptr(); + + Tensor tmp_buffer = at::empty({N, 2 * G}, + X.options().dtype(c10::CppTypeToScalarType::value)); + opmath_t* tmp_buffer_data = tmp_buffer.data_ptr(); + + // Step 1. Each thread compute their own internal gradients to the buffer. + at::parallel_for(0, N * HxW, 1, [&](int64_t begin, int64_t end) { + int tid = at::get_thread_num(); + opmath_t* buffer_ptr = buffer_data + tid * N * 2 * C; + int64_t n{0}, m{0}; + data_index_init(begin, n, N, m, HxW); + for (const auto i : c10::irange(begin, end)) { + opmath_t* ds_ptr = buffer_ptr + n * 2 * C; + opmath_t* db_ptr = ds_ptr + C; + const T* X_ptr = X_data + i * C; + const T* dY_ptr = dY_data + i * C; + + DsDbRowwiseMomentsChannelsLast(dY_ptr, X_ptr, ds_ptr, db_ptr, C); + data_index_step(n, N, m, HxW); + } + }); + + // Step 2. Collect internal gradients from each thread and + // get the final internal gradients to ds, db, and tmp_buffer. + for (const auto n : c10::irange(N)) { + for (const auto g : c10::irange(G)) { + opmath_t ds_gamma{0}, db_gamma{0}; + for (const auto d : c10::irange(D)) { + opmath_t ds_val{0}, db_val{0}; + for (const auto t : c10::irange(num_threads)) { + opmath_t* buffer_ptr = buffer_data + t * N * 2 * C + n * 2 * C; + opmath_t gamma_val = gamma_null ? opmath_t(1) : opmath_t(gamma_data[g * D + d]); + ds_gamma += buffer_ptr[g * D + d] * gamma_val; + db_gamma += buffer_ptr[g * D + d + C] * gamma_val; + ds_val += buffer_ptr[g * D + d]; + db_val += buffer_ptr[g * D + d + C]; + + } + ds_data[n * C + g * D + d] = ds_val; + db_data[n * C + g * D + d] = db_val; + } + tmp_buffer_data[n * 2 * G + 2 * g] = ds_gamma; + tmp_buffer_data[n * 2 * G + 2 * g + 1] = db_gamma; + } + } + + // Step 3. Compute dx. + if (dX_data != nullptr) { + at::parallel_for(0, N * HxW, 1, [&](int64_t begin, int64_t end) { + int64_t n{0}, m{0}; + data_index_init(begin, n, N, m, HxW); + for (const auto i : c10::irange(begin, end)) { + for (const auto g : c10::irange(G)) { + const T* X_ptr = X_data + i * C + g * D; + const T* dY_ptr = dY_data + i * C + g * D; + T* dX_ptr = dX_data + i * C + g * D; + const PT* mean_ptr = mean_data + n * G + g; + const PT* rstd_ptr = rstd_data + n * G + g; + const PT* gamma_ptr = gamma_null ? gamma_data : (gamma_data + g * D); + opmath_t ds_val = tmp_buffer_data[n * 2 * G + 2 * g]; + opmath_t db_val = tmp_buffer_data[n * 2 * G + 2 * g + 1]; + + const opmath_t c2 = (db_val * opmath_t(*mean_ptr) - ds_val) * + opmath_t(*rstd_ptr) * opmath_t(*rstd_ptr)* opmath_t(*rstd_ptr) * s; + const opmath_t c3 = -c2 * opmath_t(*mean_ptr) - db_val * opmath_t(*rstd_ptr) * s; + ApplyInputGradientsChannelsLastRowMov(dY_ptr, X_ptr, dX_ptr, rstd_ptr, gamma_ptr, c2, c3, HxW, C, D); + } + + data_index_step(n, N, m, HxW); + } + }); + } + + } + + // Finally compute dgamma and dbeta. + if (dgamma_data != nullptr) { + GammaBackward( + N, C, group, mean_data, rstd_data, ds_data, db_data, dgamma_data); + } + if (dbeta_data != nullptr) { + BetaBackward(N, C, db_data, dbeta_data); + } +} + +void GroupNormBackwardKernelImpl( + const Tensor& dY, + const Tensor& X, + const Tensor& mean, + const Tensor& rstd, + const Tensor& gamma, + int64_t N, + int64_t C, + int64_t HxW, + int64_t group, + Tensor& dX, + Tensor& dgamma, + Tensor& dbeta) { + // In training, using Amp to enable lower precision data type, + // i.e., BFloat16 or Half, is recommended. + // It will keep module parameters in opmath dtype i.e. float + // while input/output will be in lower precision data type. + // Using parameters in BFloat16 or Half may cause high precision loss. + const bool mixed_type = is_mixed_type(dY, mean); + switch (X.suggest_memory_format()) { + case at::MemoryFormat::Contiguous: { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, X.scalar_type(), "GroupNormBackwardKernelImpl", [&]() { + using param_t = at::opmath_type; + if(mixed_type) { + GroupNormBackwardKernelImplInternal( + dY, X, mean, rstd, gamma, N, C, HxW, group, dX, dgamma, dbeta); + } else { + GroupNormBackwardKernelImplInternal( + dY, X, mean, rstd, gamma, N, C, HxW, group, dX, dgamma, dbeta); + } + }); + break; + } + case at::MemoryFormat::ChannelsLast: + case at::MemoryFormat::ChannelsLast3d: { + AT_DISPATCH_FLOATING_TYPES_AND2( + ScalarType::BFloat16, ScalarType::Half, X.scalar_type(), "GroupNormBackwardKernelImpl", [&]() { + using param_t = at::opmath_type; + if(mixed_type) { + GroupNormBackwardKernelImplChannelsLastInternal( + dY, X, mean, rstd, gamma, N, C, HxW, group, dX, dgamma, dbeta); + } else { + GroupNormBackwardKernelImplChannelsLastInternal( + dY, X, mean, rstd, gamma, N, C, HxW, group, dX, dgamma, dbeta); + } + }); + break; + } + default: + TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, ChannelsLast3d, Contiguous"); + } + +} + +} // namespace + +REGISTER_DISPATCH(GroupNormKernel, &GroupNormKernelImpl) +REGISTER_DISPATCH(GroupNormBackwardKernel, &GroupNormBackwardKernelImpl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int4mm_kernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int4mm_kernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3f5ce941d9255b70bc7e52496c53855628f4e22 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int4mm_kernel.cpp @@ -0,0 +1,1386 @@ +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#if AT_KLEIDIAI_ENABLED() +#include +#include +#endif + +#if (defined(_WIN32) || defined(_WIN64)) +#define RESTRICT __restrict +#else +#define RESTRICT __restrict__ +#endif + +namespace at::native { + +namespace { + +inline bool is_block_start(int index, int BLOCK_SIZE) { + return !(index & (BLOCK_SIZE -1)); +} + +#if (defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2)) && !defined(_MSC_VER) +// convert 16x int4 to int8, handle 64 bits at a time +// used in avx2 and avx512 +inline __m128i convert_int4_to_int8(const uint8_t* data) { + __m128i tmp = _mm_loadu_si64((const __m128i*)data); + __m128i bytes = _mm_cvtepu8_epi16(tmp); + const __m128i lowMask = _mm_set1_epi8(0xF); + __m128i high = _mm_andnot_si128(lowMask, bytes); + __m128i low = _mm_and_si128(lowMask, bytes); + high = _mm_slli_epi16(high, 4); + bytes = _mm_or_si128(low, high); + return bytes; +} +#endif + +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + +// A block : {BLOCK_M, BLOCK_K}, lda = K +// B block : {BLOCK_K, BLOCK_N / 2}, ldb = BLOCK_N / 2 +// C block : {BLOCK_M, BLOCK_N}, ldc = N +// +// ScaleAndZeros block : {1, BLOCK_N, 2} +// +template +inline void tinygemm_kernel( + const BFloat16* RESTRICT A, + const uint8_t* RESTRICT B, + const BFloat16* RESTRICT ScaleAndZeros, + BFloat16* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + + constexpr int ROWS = BLOCK_M; + constexpr int COLS = BLOCK_N / 16; + + const int PREFETCH_SIZE_K = 16 * 4; + const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K; + + // number of blocks on K + const int KB = K / BLOCK_K; + + __m512 va; + __m512 vb[COLS]; + __m512 vc[ROWS * COLS]; + __m512 scale[COLS]; + __m512 zero[COLS]; + + // Lookup table to de-quantize int4 values to bf16. + // Values are dequantized as truly int4 [-8, 7] range; + // + // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero + // + static const __m512 lut = _mm512_set_ps( + 7.0f, 6.0f, 5.0f, 4.0f, + 3.0f, 2.0f, 1.0f, 0.0f, + -1.0f, -2.0f, -3.0f, -4.0f, + -5.0f, -6.0f, -7.0f, -8.0f); + + // index for transpose + static const __m512i idx1 = _mm512_set_epi32( + 30, 28, 26, 24, 22, 20, 18, 16, + 14, 12, 10, 8, 6, 4, 2, 0); + static const __m512i idx2 = _mm512_set_epi32( + 31, 29, 27, 25, 23, 21, 19, 17, + 15, 13, 11, 9, 7, 5, 3, 1); + + // load scale and zero point + auto load_scale_and_zeros = [&](int i, int _kb) { + // load 2x bfloat16 vector + __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * ldc * 2 + 32 * i)); + if (_kb + PREFETCH_SIZE_KB < KB) { + _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * ldc * 2 + 32 * i, _MM_HINT_T0); + } + + // convert to 2x f32 vector + __m512 a, b; + vec::cvtbf16_fp32(t, a, b); + + // transpose scale_and_zero from {16, 2} to {2, 16} + // inputs: + // a: {s0, z0, s1, z1, ..., s7, z7} + // b: {s8, z8, s9, z9, ..., s15, z15} + // output: + // scale: {s0, s1, s2, ..., s15} + // zero: {z0, z1, z2, ..., z15} + scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b); + zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b); + }; + + auto loadc = [&](auto i) { + vc[i] = _mm512_setzero_ps(); + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&, COLS](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + + if constexpr (col == 0) { + float aa = static_cast(A[row * lda + k]); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0); + } + va = _mm512_set1_ps(aa); + } + + if constexpr (row == 0) { + if constexpr (COLS == 4) { + // when BLOCK_N = 64, handle each row at a time + // to reduce de-quantize overhead. + if constexpr (col == 0) { + __m256i b4 = _mm256_loadu_si256((__m256i*)(B + k * ldb)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb, _MM_HINT_T0); + } + + __m512i b32 = _mm512_cvtepu8_epi32(_mm256_castsi256_si128(b4)); + vb[0] = _mm512_permutexvar_ps(b32, lut); + vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]); + vb[2] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut); + vb[2] = _mm512_fmadd_ps(vb[2], scale[2], zero[2]); + + b32 = _mm512_cvtepu8_epi32(_mm256_extracti128_si256(b4, 1)); + vb[1] = _mm512_permutexvar_ps(b32, lut); + vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]); + vb[3] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut); + vb[3] = _mm512_fmadd_ps(vb[3], scale[3], zero[3]); + } + } else { + __m128i b8 = convert_int4_to_int8(B + k * ldb + col * 8); + __m512i b32 = _mm512_cvtepu8_epi32(b8); + vb[col] = _mm512_permutexvar_ps(b32, lut); + vb[col] = _mm512_fmadd_ps(vb[col], scale[col], zero[col]); + } + } + + constexpr int idx = row * COLS + col; + vc[idx] = _mm512_fmadd_ps(va, vb[col], vc[idx]); + }; + + for (int k = 0, kb = 0; k < K; ++k) { + if (is_block_start(k, BLOCK_K)) { + c10::ForcedUnroll{}(load_scale_and_zeros, kb++); + } + c10::ForcedUnroll{}(compute, k); + } + + //store to C + auto storec = [&, COLS](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + if constexpr (COLS == 4) { + // when BLOCK_N = 64, handle each row at a time + // to reduce `cvtfp32_bf16` overhead. + if constexpr (col == 0) { + __m512i c01 = vec::cvtfp32_bf16(vc[row * 4 + 0], vc[row * 4 + 1]); + __m512i c23 = vec::cvtfp32_bf16(vc[row * 4 + 2], vc[row * 4 + 3]); + _mm512_storeu_si512((__m512i*)(C + row * ldc + 0 * 32), c01); + _mm512_storeu_si512((__m512i*)(C + row * ldc + 1 * 32), c23); + } + } else { + __m256i ci = vec::cvtfp32_bf16(vc[i]); + _mm256_storeu_si256((__m256i*)(C + row * ldc + col * 16), ci); + } + }; + c10::ForcedUnroll{}(storec); +} + +#elif defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER) + +template +inline void tinygemm_kernel( + const BFloat16* RESTRICT A, + const uint8_t* RESTRICT B, + const BFloat16* RESTRICT ScaleAndZeros, + BFloat16* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + + constexpr int ROWS = BLOCK_M; + constexpr int COLS = BLOCK_N / 8; + + const int PREFETCH_SIZE_K = 16 * 4; + const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K; + + // number of blocks on K + const int KB = K / BLOCK_K; + + __m256 va; + __m256 vb[COLS]; + __m256 vc[ROWS * COLS]; + __m256 scale[COLS]; + __m256 zero[COLS]; + + static const __m256i idx1 = _mm256_setr_epi32(0, 2, 4, 6, 1, 3, 5, 7); + + // offset to shift from range [0, 15] to [-8, 7] + const __m256 offset = _mm256_set1_ps(-8.0f); + + // load scale and zero point + auto load_scale_and_zeros = [&](int i, int _kb) { + // load 2x bfloat16 vector + __m256i t = _mm256_loadu_si256((__m256i*)(ScaleAndZeros + _kb * ldc * 2 + 16 * i)); + if (_kb + PREFETCH_SIZE_KB < KB) { + _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * ldc * 2 + 16 * i, _MM_HINT_T0); + } + + // convert to 2x f32 vector + __m256 a, b; + vec::cvtbf16_fp32(t, a, b); + + // transpose scale_and_zero from {8, 2} to {2, 8} + // inputs: + // a: {s0, z0, s1, z1, s2, z2, s3, z3} + // b: {s4, z4, s5, z5, s6, z6, s7, z7} + // output: + // scale: {s0, s1, s2, s3, s4, s5, s6, s7} + // zero: {z0, z1, z2, z3, z4, z5, z6, z7} + a = _mm256_permutevar8x32_ps(a, idx1); + b = _mm256_permutevar8x32_ps(b, idx1); + scale[i] = _mm256_permute2f128_ps(a, b, 0b0100000); + zero[i] = _mm256_permute2f128_ps(a, b, 0b0110001); + + // zero = -8 * scale + zero + zero[i] = _mm256_fmadd_ps(scale[i], offset, zero[i]); + }; + + auto loadc = [&](auto i) { + vc[i] = _mm256_setzero_ps(); + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&, COLS](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + + if constexpr (col == 0) { + float aa = static_cast(A[row * lda + k]); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0); + } + va = _mm256_set1_ps(aa); + } + + if constexpr (row == 0) { + if constexpr (COLS == 4) { + // when BLOCK_N = 32, handle each row at a time + if constexpr (col == 0) { + __m256i mask = _mm256_set1_epi32(0xF); + __m128i b4 = _mm_loadu_si128((__m128i*)(B + k * ldb)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb, _MM_HINT_T0); + } + + __m256i b32 = _mm256_cvtepu8_epi32(b4); + vb[0] = _mm256_cvtepi32_ps(_mm256_and_si256(b32, mask)); + vb[0] = _mm256_fmadd_ps(vb[0], scale[0], zero[0]); + vb[2] = _mm256_cvtepi32_ps(_mm256_srli_epi32(b32, 4)); + vb[2] = _mm256_fmadd_ps(vb[2], scale[2], zero[2]); + + b32 = _mm256_cvtepu8_epi32(_mm_shuffle_epi32(b4, _MM_SHUFFLE(3, 2, 3, 2))); + vb[1] = _mm256_cvtepi32_ps(_mm256_and_si256(b32, mask)); + vb[1] = _mm256_fmadd_ps(vb[1], scale[1], zero[1]); + vb[3] = _mm256_cvtepi32_ps(_mm256_srli_epi32(b32, 4)); + vb[3] = _mm256_fmadd_ps(vb[3], scale[3], zero[3]); + } + } else { + if constexpr (col % 2 == 0) { + // de-quantize per 64 bits (16x int4) + __m128i b8 = convert_int4_to_int8(B + k * ldb + col * 4); + __m128i b8_val0 = _mm_set1_epi64x(_mm_extract_epi64(b8, 0)); + __m128i b8_val1 = _mm_set1_epi64x(_mm_extract_epi64(b8, 1)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb + col * 4, _MM_HINT_T0); + } + + vb[col] = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(b8_val0)); + vb[col] = _mm256_fmadd_ps(vb[col], scale[col], zero[col]); + vb[col + 1] = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(b8_val1)); + vb[col + 1] = _mm256_fmadd_ps(vb[col + 1], scale[col + 1], zero[col + 1]); + } + } + } + + constexpr int idx = row * COLS + col; + vc[idx] = _mm256_fmadd_ps(va, vb[col], vc[idx]); + }; + for (int k = 0, kb = 0; k < K; ++k) { + if (is_block_start(k, BLOCK_K)) { + c10::ForcedUnroll{}(load_scale_and_zeros, kb++); + } + c10::ForcedUnroll{}(compute, k); + } + + // store to C + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + if constexpr (col % 2 == 0) { + __m256i ci = vec::cvtfp32_bf16(vc[row * COLS + col], vc[row * COLS + col + 1]); + _mm256_storeu_si256((__m256i*)(C + row * ldc + col * 8), ci); + } + }; + c10::ForcedUnroll{}(storec); +} + +#endif + +#if !defined(C10_MOBILE) && defined(__aarch64__) +#include + +inline float32x4x2_t load_as_float32x4x2(const Half* ptr) { + float16x4x2_t f16_val = vld2_f16(reinterpret_cast(ptr)); + auto val_low = vcvt_f32_f16(f16_val.val[0]); + auto val_high = vcvt_f32_f16(f16_val.val[1]); + return {val_low, val_high}; +} + +inline void store_float32x4(Half* ptr, float32x4_t val) { + vst1_f16(reinterpret_cast(ptr), vcvt_f16_f32(val)); +} + +inline float32x4x2_t load_as_float32x4x2(const BFloat16* ptr) { + int32x4_t shift = vdupq_n_s32(16); + uint16x4x2_t u16_val = vld2_u16(reinterpret_cast(ptr)); + uint32x4_t int_low = vmovl_u16(u16_val.val[0]); + uint32x4_t int_high = vmovl_u16(u16_val.val[1]); + return {vreinterpretq_f32_u32(vshlq_u32(int_low, shift)), vreinterpretq_f32_u32(vshlq_u32(int_high, shift))}; +} + +inline void store_float32x4(BFloat16* ptr, float32x4_t val) { + int32x4_t shift = vdupq_n_s32(-16); + uint32x4_t uint32_val = vshlq_u32(vreinterpretq_u32_f32(val), shift); + vst1_u16(reinterpret_cast(ptr), vmovn_u32(uint32_val)); +} + +inline float32x4x2_t load_as_float32x4x2(const float* ptr) { + return vld2q_f32(ptr); +} + +inline void store_float32x4(float* ptr, float32x4_t val) { + vst1q_f32(ptr, val); +} + +template +inline void tinygemm_kernel_( + const T* RESTRICT A, + const uint8_t* RESTRICT B, + const T* RESTRICT ScaleAndZeros, + T* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + int16_t shift_vals[4] = {0, -4, -8, -12}; + int16x4_t shifts = vld1_s16(shift_vals); + int16x4_t offs = vdup_n_s16(8); + uint16x4_t mask = vdup_n_u16(0x0F); + for (const auto m : c10::irange(BLOCK_M)) { + for (int n = 0; n < BLOCK_N; n+= 16) { + float32x4_t c_val[4]; + float32x4_t scales[4], zeros[4]; + c10::ForcedUnroll<4>{}([&](auto i) { + c_val[i] = vdupq_n_f32(0.0); + }); + for (const auto k : c10::irange(K)) { + const auto a_val = vdupq_n_f32(static_cast(A[m * lda + k])); + if (is_block_start(k, BLOCK_K)) { + int kb = k / BLOCK_K; + c10::ForcedUnroll<4>{}([&](auto i) { + auto scales_and_zeros = load_as_float32x4x2(ScaleAndZeros + kb * ldc * 2 + n * 2 + i * 8); + scales[i] = scales_and_zeros.val[0]; + zeros[i] = scales_and_zeros.val[1]; + }); + } + c10::ForcedUnroll<4>{}([&](auto i) { + uint16_t b_pack = reinterpret_cast(B + k * ldb + n / 2)[i]; + uint16x4_t b_masked = vand_u16(vshl_u16(vdup_n_u16(b_pack), shifts), mask); + int16x4_t b_ints = vsub_s16(vreinterpret_s16_u16(b_masked), offs); + float32x4_t b_vals = vcvtq_f32_s32(vmovl_s16(b_ints)); + b_vals = vaddq_f32(zeros[i], vmulq_f32(scales[i], b_vals)); + c_val[i] = vfmaq_f32(c_val[i], b_vals, a_val); + }); + } + c10::ForcedUnroll<4>{}([&](auto i) { + store_float32x4(C + m * ldc + n + i * 4, c_val[i]); + }); + } + } +} + +template +inline void tinygemm_kernel( + const Half* RESTRICT A, + const uint8_t* RESTRICT B, + const Half* RESTRICT ScaleAndZeros, + Half* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + tinygemm_kernel_(A, B, ScaleAndZeros, C, lda, ldb, ldc, K, BLOCK_K); +} + +template +inline void tinygemm_kernel( + const BFloat16* RESTRICT A, + const uint8_t* RESTRICT B, + const BFloat16* RESTRICT ScaleAndZeros, + BFloat16* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + tinygemm_kernel_(A, B, ScaleAndZeros, C, lda, ldb, ldc, K, BLOCK_K); +} + +template +inline void tinygemm_kernel( + const float* RESTRICT A, + const uint8_t* RESTRICT B, + const float* RESTRICT ScaleAndZeros, + float* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + tinygemm_kernel_(A, B, ScaleAndZeros, C, lda, ldb, ldc, K, BLOCK_K); +} +#endif + +template +inline float convert_int4_to_float(const uint8_t* b, int n) { + static constexpr float lut[16] = { + -8.0f, -7.0f, -6.0f, -5.0f, + -4.0f, -3.0f, -2.0f, -1.0f, + 0.0f, 1.0f, 2.0f, 3.0f, + 4.0f, 5.0f, 6.0f, 7.0f + }; + int index; +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + if constexpr (BLOCK_N == 64) { + const int nb = n/BLOCK_N; + n -= nb*BLOCK_N; + if (n < 32) { + auto val = b[nb * BLOCK_N / 2 + n]; + index = val & 0x0f; + } else { + auto val = b[nb * BLOCK_N / 2 + (n - 32)]; + index = val >> 4; + } + } else +#elif defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER) + if constexpr (BLOCK_N == 32) { + const int nb = n/BLOCK_N; + n -= nb*BLOCK_N; + if (n < 16) { + auto val = b[nb * BLOCK_N / 2 + n]; + index = val & 0x0f; + } else { + auto val = b[nb * BLOCK_N / 2 + (n - 16)]; + index = val >> 4; + } + } else +#endif + { + const auto is_even = (n & 1) == 0; + auto val = b[n/2]; + index = is_even ? (val & 0x0F) : (val >> 4); + } + return lut[index]; +} + +// non-vectorized version +template +inline void tinygemm_kernel( + const T* RESTRICT A, + const uint8_t* RESTRICT B, + const T* RESTRICT ScaleAndZeros, + T* RESTRICT C, + int lda, + int ldb, + int ldc, + int K, + int BLOCK_K) { + + for (const auto m : c10::irange(BLOCK_M)) { + for (const auto n : c10::irange(BLOCK_N)) { + float c_val = 0; + for (const auto k : c10::irange(K)) { + int kb = k / BLOCK_K; + const auto scale = static_cast(ScaleAndZeros[kb * ldc * 2 + n * 2]); + const auto zero = static_cast(ScaleAndZeros[kb * ldc * 2 + n * 2 + 1]); + const auto a_val = static_cast(A[m * lda + k]); + float b_val = convert_int4_to_float(B + k *ldb, n); + b_val = b_val * scale + zero; + + c_val += a_val * b_val; + } + C[m * ldc + n] = c_val; + } + } +} + + +#define LAUNCH_TINYGEMM_KERNEL(MB_SIZE, NB_SIZE) \ + tinygemm_kernel( \ + A_ptr, B_ptr, S_ptr, C_ptr, \ + K, NB_SIZE / 2, N, K, BLOCK_K); + +#define LAUNCH_TINYGEMM_NB_SIZE(MB_SIZE) \ + switch (nb_size) { \ + case 16: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 16); \ + break; \ + case 32: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 32); \ + break; \ + case 48: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 48); \ + break; \ + case 64: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 64); \ + break; \ + default: \ + TORCH_CHECK(false, "Unsupported n block size: ", nb_size); \ + break; \ + } + +// NB: int4 weight pack (with BLOCK_N 64) +// weight (int32): {N/64, 64, K} +// packed (uint8): {N/64, K, 32} +// +// 1. avx512 packed format: +// When N is 64, to do 256-bit unpacking at a time, we pack Lane0 with Lane2, +// Lane1 with Lane3 since we can only do shift on a 128-bit basis. +// +// weight: +// [Lane0] N0...15: {a00, a01, a02, ...} +// [Lane1] N16...31: {a10, a11, a12, ...} +// [Lane2] N32...47: {a20, a21, a22, ...} +// [Lane3] N48...63: {a30, a31, a32, ...} +// +// packed: +// [Lane02] N0...31: {a20|a00, a21|a01, a22|a02, ...} +// [Lane13] N32...63: {a30|a10, a31|a11, a32|a12, ...} +// +// Note: when N is 16, 32 or 48, pack with 64-bit format. +// +// 2. avx2 packed format: +// When N is 32, to do 128-bit unpacking at a time. +// +// weight: +// [Lane0] N0...15: { a0, a1, a2, ...} +// [Lane1] N16...32: {a16, a17, a18, ...} +// +// packed: +// [Lane01] N0...32: {a16|a0, a17|a1, a18|a2, ...} +// +// Note: When N is 16, pack with 64-bit format +// +// 3 non-vectorized packed format: +// Do 64-bit unpacking at a time. +// +// weight: {a0, a1, a2, a3, ..., a14, a15} +// packed: {a1|a0, a3, a2, ..., a15|a14} +// +void weight_to_int4pack_kernel( + const Tensor& weight_packed, + const Tensor& weight) { + + auto weight_packed_data = reinterpret_cast(weight_packed.data_ptr()); + const auto weight_data = weight.const_data_ptr(); + + int N = weight.size(0); + int K = weight.size(1); + + // 64 for avx512 and 32 for avx2/non-vectorized + constexpr int BLOCK_N = vec::Vectorized::size() * 4; + const int NB = (N + BLOCK_N - 1) / BLOCK_N; + + // parallel on NB blocks + at::parallel_for(0, NB, 0, [&](int begin, int end) { + for (const auto i : c10::irange(begin, end)) { + int nb_size = std::min(BLOCK_N, N - i * BLOCK_N); + + const int32_t* src = weight_data + i * BLOCK_N * K; + uint8_t* dst = weight_packed_data + i * K * BLOCK_N / 2; + for (const auto k : c10::irange(K)) { +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + if (nb_size == BLOCK_N) { + for (const auto d : c10::irange(16)) { + int32_t val0 = src[(d + 0) * K + k]; + int32_t val1 = src[(d + 16) * K + k]; + int32_t val2 = src[(d + 32) * K + k]; + int32_t val3 = src[(d + 48) * K + k]; + + uint8_t packed02 = ((uint8_t)val2 << 4) | ((uint8_t)val0); + uint8_t packed13 = ((uint8_t)val3 << 4) | ((uint8_t)val1); + + dst[k * 32 + d] = packed02; + dst[k * 32 + 16 + d] = packed13; + } + } else { + // for nb_size 16, 32, 48 + for (int n = 0; n < nb_size; n += 2) { + int32_t val0 = src[n * K + k]; + int32_t val1 = src[n * K + K + k]; + + uint8_t packed = ((uint8_t)val1 << 4) | ((uint8_t)val0); + dst[k * nb_size / 2 + n / 2] = packed; + } + } +#elif defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER) + if (nb_size == BLOCK_N) { + // for nb_size 32 + for (const auto d : c10::irange(16)) { + int32_t val0 = src[(d + 0) * K + k]; + int32_t val1 = src[(d + 16) * K + k]; + + uint8_t packed01 = ((uint8_t)val1 << 4) | ((uint8_t)val0); + dst[k * 16 + d] = packed01; + } + } else { + // for nb_size 16 + for (int n = 0; n < nb_size; n += 2) { + int32_t val0 = src[n * K + k]; + int32_t val1 = src[n * K + K + k]; + + uint8_t packed = ((uint8_t)val1 << 4) | ((uint8_t)val0); + dst[k * nb_size / 2 + n / 2] = packed; + } + } +#else + for (int n = 0; n < nb_size; n += 2) { + int32_t val0 = src[n * K + k]; + int32_t val1 = src[n * K + K + k]; + + uint8_t packed = ((uint8_t)val1 << 4) | ((uint8_t)val0); + dst[k * nb_size / 2 + n / 2] = packed; + } +#endif + } + } + }); +} + +template +void int4pack_mm_kernel_( + const Tensor& C, + const Tensor& A, + const Tensor& B, + int qGroupSize, + const Tensor& qScaleAndZeros) { + + const auto* A_data = A.const_data_ptr(); + const auto* B_data = reinterpret_cast(B.const_data_ptr()); + auto* C_data = C.data_ptr(); + const auto* S_data = qScaleAndZeros.const_data_ptr(); + + int M = A.size(0); + int N = B.size(0); + int K = A.size(1); + + constexpr int BLOCK_M = 4; + // 64 for avx512 and 32 for avx2/non-vectorized + constexpr int BLOCK_N = vec::Vectorized::size() * 4; + // 32, 64, 128, 256 + const int BLOCK_K = qGroupSize; + + const int MB = (M + BLOCK_M - 1) / BLOCK_M; + const int NB = (N + BLOCK_N - 1) / BLOCK_N; + + at::parallel_for(0, MB * NB, 0, [&](int begin, int end) { + int mb{0}, nb{0}; + data_index_init(begin, mb, MB, nb, NB); + + for ([[maybe_unused]] const auto i : c10::irange(begin, end)) { + int mb_start = mb * BLOCK_M; + int mb_size = std::min(BLOCK_M, M - mb_start); + int nb_start = nb * BLOCK_N; + int nb_size = std::min(BLOCK_N, N - nb_start); + + const auto* A_ptr = A_data + mb_start * K; + const auto* B_ptr = B_data + nb_start * K / 2; + const auto* S_ptr = S_data + nb_start * 2; + auto* C_ptr = C_data + mb_start * N + nb_start; + + switch (mb_size) { + case 1: + LAUNCH_TINYGEMM_NB_SIZE(1); + break; + case 2: + LAUNCH_TINYGEMM_NB_SIZE(2); + break; + case 3: + LAUNCH_TINYGEMM_NB_SIZE(3); + break; + case 4: + LAUNCH_TINYGEMM_NB_SIZE(4); + break; + default: + TORCH_CHECK(false, "Unsupported m block size: ", mb_size); + } + + // move to the next index + data_index_step(mb, MB, nb, NB); + } + }); +} + +void int4pack_mm_kernel( + const Tensor& C, + const Tensor& A, + const Tensor& B, + int qGroupSize, + const Tensor& qScaleAndZeros) { + if (C.scalar_type() == kBFloat16) { + int4pack_mm_kernel_(C, A, B, qGroupSize, qScaleAndZeros); + } else if (C.scalar_type() == kHalf) { + int4pack_mm_kernel_(C, A, B, qGroupSize, qScaleAndZeros); + } else { + int4pack_mm_kernel_(C, A, B, qGroupSize, qScaleAndZeros); + } +} + +#if AT_KLEIDIAI_ENABLED() +bool can_use_kleidiai( + const at::Tensor& scales_zeros, + const int64_t K, + const int64_t block_size) { + bool ret = false; + if (cpuinfo_has_arm_neon_dot()) { + // The Groupwise kernel requires BFloat16 Scales and Channelwise kernel + // requires Float32 Scales. If not provided, we will use fallback + // implementation. + if ((block_size == K && scales_zeros.dtype() == at::kFloat) || + ((block_size < K && !(block_size % 32) && !(K % block_size)) && + scales_zeros.dtype() == at::kBFloat16)) { + ret = true; + } + } + return ret; +} +#endif + +static void ref_dyn_quant_matmul_4bit_channelwise_kernel_bf16( + size_t m, + size_t n, + size_t k, + const uint16_t* lhs_bf16, + const uint8_t* rhs_qs4cx, + const float* rhs_scales, + uint16_t* dst_bf16, + float scalar_min, + float scalar_max, + const float* bias) { + // Roundup lambda for internal stride calculations + auto roundup = [](size_t a, size_t b) { return ((a + b - 1) / b) * b; }; + + // Cast bfloat16 to float32 inline + auto cast_bf16_to_f32 = [](uint16_t bf16_val) { + uint32_t tmp = static_cast(bf16_val) << 16; + float f; + std::memcpy(&f, &tmp, sizeof(f)); + return f; + }; + + // Cast float32 to bfloat16 inline + auto cast_f32_to_bf16 = [](float f) { + uint32_t bits; + std::memcpy(&bits, &f, sizeof(bits)); + return static_cast(bits >> 16); + }; + + // Quantization pack lambda (channelwise QA8DX) + auto quant_pack_8bit_channelwise = + [&](size_t M, size_t K, const uint16_t* src_bf16, int8_t* dst_qa8dx) { + constexpr int8_t kI8Min = std::numeric_limits::lowest(); + constexpr int8_t kI8Max = std::numeric_limits::max(); + + const size_t dst_stride = + K * sizeof(int8_t) + sizeof(float) + sizeof(int32_t); + for (size_t i = 0; i < M; ++i) { + const uint16_t* row_ptr = src_bf16 + i * K; + // find min/max + float mn = FLT_MAX, mx = -FLT_MAX; + for (size_t j = 0; j < K; ++j) { + float v = cast_bf16_to_f32(row_ptr[j]); + mn = std::min(mn, v); + mx = std::max(mx, v); + } + float rmin = std::min(0.0f, mn); + float rmax = std::max(0.0f, mx); + constexpr float qmin = static_cast(kI8Min); + constexpr float qmax = static_cast(kI8Max); + float scale = (rmin == rmax) ? 1.f : (qmax - qmin) / (rmax - rmin); + float recip = scale ? 1.0f / scale : 0.0f; + int32_t zp; + float des_min = rmin * scale; + float des_max = rmax * scale; + float err_min = qmin + des_min; + float err_max = qmax + des_max; + float zp_f = + (err_min + err_max) > 0 ? qmin - des_min : qmax - des_max; + zp_f = std::clamp(zp_f, qmin, qmax); + zp = std::lrintf(zp_f); + int8_t* out_ptr = dst_qa8dx + i * dst_stride; + // store header + *reinterpret_cast(out_ptr) = recip; + *reinterpret_cast(out_ptr + sizeof(float)) = -zp; + out_ptr += sizeof(float) + sizeof(int32_t); + // quantize + for (size_t j = 0; j < K; ++j) { + float v = cast_bf16_to_f32(row_ptr[j]); + int32_t q = static_cast(std::round(v * scale)) + zp; + q = std::clamp( + q, static_cast(kI8Min), static_cast(kI8Max)); + *out_ptr++ = static_cast(q); + } + } + }; + + // MatMul lambda (MXN x MXK -> MNXK BF16) + auto matmul_kernel = [&](size_t M, + size_t N, + size_t K, + const int8_t* lhs, + const uint8_t* rhs, + const float* scales, + uint16_t* dst, + float lo, + float hi) { + const size_t lhs_stride = + K * sizeof(int8_t) + sizeof(float) + sizeof(int32_t); + const size_t rhs_stride = roundup(K, 2) / 2; + for (size_t i = 0; i < M; ++i) { + const int8_t* lhs_row = lhs + i * lhs_stride; + for (size_t j = 0; j < N; ++j) { + int32_t acc = 0; + const int8_t* lptr = lhs_row; + const uint8_t* rptr = rhs + j * rhs_stride; + float lhs_scale = *reinterpret_cast(lptr); + int32_t lhs_off = + *reinterpret_cast(lptr + sizeof(float)); + lptr += sizeof(float) + sizeof(int32_t); + for (size_t t = 0; t < K; ++t) { + int32_t lv = static_cast(lptr[t]); + uint8_t bv = rptr[t / 2]; + int32_t rv = ((t & 1) == 0) ? (static_cast(bv & 0xF) - 8) + : (static_cast(bv >> 4) - 8); + acc += lv * rv + lhs_off * rv; + } + float res = static_cast(acc) * scales[j] * lhs_scale; + if (bias) { + res += bias[j]; + } + res = std::clamp(res, lo, hi); + *dst++ = cast_f32_to_bf16(res); + } + } + }; + + // allocate and run + std::unique_ptr packed( + new int8_t[m * (k * sizeof(int8_t) + sizeof(float) + sizeof(int32_t))]); + quant_pack_8bit_channelwise(m, k, lhs_bf16, packed.get()); + matmul_kernel( + m, + n, + k, + packed.get(), + rhs_qs4cx, + rhs_scales, + dst_bf16, + scalar_min, + scalar_max); +} + +/** + * The Int4 quantized weights must be represented as a uint8 tensor + * For matrix multiplication with a weight shape of (N x K) + * the shape of the 4-bit quantized weights is [N, K/groupsize, groupsize/2]. + * + * For KleidiAI weight packing, the scales, biases, and Int4 quantized + * weights are packed into a single `packed_weights` structure, optimized for + * Arm instructions. + * + * In the fallback reference kernel, no special packing is required for + * Int4 quantized weights. + * + * The Groupwise kernel requires BFloat16 Scales and Channelwise kernel requires + * Float32 Scales. If not provided, we will use fallback implementation. + */ +void dyn_quant_pack_4bit_weight_kernel( + Tensor& packed_weights, + const Tensor& weights, + const Tensor& scales_zeros, + const std::optional& bias, + const int64_t N, + const int64_t K, + const int64_t block_size) { +#if AT_KLEIDIAI_ENABLED() + if (can_use_kleidiai(scales_zeros, K, block_size)) { + const int64_t weight_packed_size = + kleidiai::kai_pack_rhs_int4_size(N, K, block_size, weights.scalar_type()); + packed_weights.resize_({weight_packed_size}); + kleidiai::kai_pack_int4_rhs( + packed_weights, weights, scales_zeros, bias, N, K, block_size); + } else +#endif + { + packed_weights = packed_weights.to(kFloat); + auto weight_reshaped = weights.reshape({-1}).to(kFloat); + auto scales_zeros_reshaped = scales_zeros.reshape({-1}).to(kFloat); + std::vector tensors_to_cat = {weight_reshaped, scales_zeros_reshaped}; + if (bias.has_value()) { + tensors_to_cat.push_back(bias.value().view({-1}).to(kFloat)); + } + auto res = at::cat(tensors_to_cat, 0); + packed_weights.resize_(res.sizes()).copy_(res); + } +} + +void ref_dyn_quant_matmul_4bit_channelwise_kernel( + size_t m, + size_t n, + size_t k, + const float* lhs_f32, + const uint8_t* rhs_qs4cx, + const float* rhs_scales_f32, + float* dst_f32, + float scalar_min, + float scalar_max, + const float* bias) { + const size_t input_size_8bit = m * (k + sizeof(int32_t) + sizeof(float)); + + auto lhs_qa8dx_buffer = std::make_unique(input_size_8bit); + uint8_t* lhs_qa8dx = lhs_qa8dx_buffer.get(); + + // Lambda for quantizing the fp32 input to 8 bit symmetric and pack it in + // required format for matmul + auto input_quant_pack_8bit_channelwise = + [&](size_t m, size_t k, const float* lhs_f32, int8_t* lhs_qa8dx) { + constexpr int8_t kI8Min = std::numeric_limits::lowest(); + constexpr int8_t kI8Max = std::numeric_limits::max(); + + const size_t dst_stride = + (k * sizeof(int8_t) + sizeof(float) + sizeof(int32_t)); + + const size_t lhs_qa8dx_stride = k; + + for (size_t m_idx = 0; m_idx < m; ++m_idx) { + const float* src_ptr = lhs_f32 + m_idx * lhs_qa8dx_stride; + + float max0 = -FLT_MAX; + float min0 = FLT_MAX; + + // Find min/max for each channel + for (size_t k_idx = 0; k_idx < k; ++k_idx) { + const float src0_0 = src_ptr[k_idx]; + + max0 = std::max(src0_0, max0); + min0 = std::min(src0_0, min0); + } + + // Maximum/minimum int8 values + constexpr float qmin = static_cast(kI8Min); + constexpr float qmax = static_cast(kI8Max); + + const float rmin0 = std::min(0.0f, min0); + const float rmax0 = std::max(0.0f, max0); + + const float scale0 = + rmin0 == rmax0 ? 1.f : (qmax - qmin) / (rmax0 - rmin0); + + // Reciprocal to quantize + const float recip_scale0 = scale0 ? 1.0f / scale0 : 0.0f; + + const float descaled_min0 = rmin0 * scale0; + const float descaled_max0 = rmax0 * scale0; + + const float zero_point_from_min_error0 = qmin + descaled_min0; + const float zero_point_from_max_error0 = qmax + descaled_max0; + + float zero_point0 = + zero_point_from_min_error0 + zero_point_from_max_error0 > 0 + ? qmin - descaled_min0 + : qmax - descaled_max0; + + zero_point0 = std::max(zero_point0, qmin); + zero_point0 = std::min(zero_point0, qmax); + + // Round to nearest integer + const int32_t nudged_zero_point0 = std::lrintf(zero_point0); + + int8_t* dst_ptr = lhs_qa8dx + m_idx * dst_stride; + + // LHS offset at the beginning of the row + *((float*)dst_ptr) = recip_scale0; + dst_ptr += sizeof(float); + *((int32_t*)dst_ptr) = -nudged_zero_point0; + dst_ptr += sizeof(int32_t); + + // Quantize the channels + for (size_t k_idx = 0; k_idx < k; ++k_idx) { + const float src0_0 = src_ptr[k_idx]; + + // Scale the values + int32_t v0_s32 = (int32_t)(std::round(src0_0 * scale0)); + + v0_s32 = v0_s32 + nudged_zero_point0; + v0_s32 = std::max(v0_s32, static_cast(kI8Min)); + v0_s32 = std::min(v0_s32, static_cast(kI8Max)); + dst_ptr[0] = (int8_t)v0_s32; + dst_ptr += sizeof(int8_t); + } + } + }; + + // Dynamically Quantize the float32 input to 8 bit asymmetric + input_quant_pack_8bit_channelwise(m, k, lhs_f32, (int8_t*)lhs_qa8dx); + + const size_t lhs_stride = + k * sizeof(int8_t) + sizeof(float) + sizeof(int32_t); + + const size_t rhs_qs4cx_stride = ((((k + 2 - 1) / 2) * 2) / 2); + + for (size_t m_idx = 0; m_idx < m; ++m_idx) { + const int8_t* lhs_ptr_start = (int8_t*)lhs_qa8dx + m_idx * lhs_stride; + + for (size_t n_idx = 0; n_idx < n; ++n_idx) { + // Main f32 accumulator + int32_t iacc = 0; + + const int8_t* lhs_ptr = lhs_ptr_start; + const uint8_t* rhs_ptr = rhs_qs4cx + n_idx * rhs_qs4cx_stride; + + // Get the LHS quantization parameters stored at the + // beginning of each row + const float lhs_scale = *(const float*)lhs_ptr; + lhs_ptr += sizeof(float); + + const int32_t lhs_offset = *(const int32_t*)lhs_ptr; + lhs_ptr += sizeof(int32_t); + + for (size_t k_idx = 0; k_idx < k; ++k_idx) { + // Get the LHS values + const int32_t lhs_v0 = (int32_t)lhs_ptr[0]; + + // Get the RHS values + const uint8_t rhs_byte = rhs_ptr[0]; + + // Unpack the RHS values + int32_t rhs_v0 = 0; + if ((k_idx % 2) == 0) { + rhs_v0 = (((int32_t)(rhs_byte & 0x0F)) - 8); + } else { + rhs_v0 = (((int32_t)(rhs_byte >> 4)) - 8); + } + + iacc += lhs_v0 * rhs_v0; + iacc += lhs_offset * rhs_v0; + + lhs_ptr += 1; + + // Increment only when k_idx is not a multiple of 2 + rhs_ptr += k_idx % 2; + } + + // Get the RHS scale + const float rhs_scale = rhs_scales_f32[n_idx]; + + float main_acc = iacc * rhs_scale; + + main_acc = main_acc * lhs_scale; + + if (bias) { + main_acc += bias[n_idx]; + } + + // Clamp (min-max) operation + main_acc = std::max(main_acc, scalar_min); + main_acc = std::min(main_acc, scalar_max); + + dst_f32[0] = main_acc; + dst_f32 += 1; + } + } +} + +void ref_dyn_quant_matmul_4bit_groupwise_kernel( + size_t m, + size_t n, + size_t k, + size_t bl, + const float* lhs_f32, + const uint8_t* rhs_qs4c32, + const float* rhs_scales_fp32, + float* dst_f32, + float scalar_min, + float scalar_max, + const float* bias) { + // Lambda for LHS quantization + auto lhs_quant_pack = [&](size_t m, + size_t k, + const float* lhs_f32, + int8_t* lhs_qa8dx) { + constexpr int8_t kI8Min = std::numeric_limits::lowest(); + constexpr int8_t kI8Max = std::numeric_limits::max(); + + const size_t dst_stride = + (k * sizeof(int8_t) + sizeof(float) + sizeof(int32_t)); + + for (size_t row_idx = 0; row_idx < m; ++row_idx) { + const float* src_ptr = lhs_f32 + row_idx * k; + + float max0 = -FLT_MAX; + float min0 = FLT_MAX; + + for (size_t k_idx = 0; k_idx < k; ++k_idx) { + const float src0_0 = src_ptr[k_idx]; + max0 = std::max(src0_0, max0); + min0 = std::min(src0_0, min0); + } + + constexpr float qmin = static_cast(kI8Min); + constexpr float qmax = static_cast(kI8Max); + + const float rmin0 = std::min(0.0f, min0); + const float rmax0 = std::max(0.0f, max0); + const float scale0 = + (rmin0 == rmax0) ? 1.f : (qmax - qmin) / (rmax0 - rmin0); + const float recip_scale0 = scale0 ? 1.0f / scale0 : 0.0f; + + const float descaled_min0 = rmin0 * scale0; + const float descaled_max0 = rmax0 * scale0; + + float zero_point0 = (qmin + descaled_min0 + qmax + descaled_max0 > 0) + ? qmin - descaled_min0 + : qmax - descaled_max0; + + zero_point0 = std::max(zero_point0, qmin); + zero_point0 = std::min(zero_point0, qmax); + const int32_t nudged_zero_point0 = std::lrintf(zero_point0); + + int8_t* dst_ptr = lhs_qa8dx + row_idx * dst_stride; + + *((float*)dst_ptr) = recip_scale0; + dst_ptr += sizeof(float); + *((int32_t*)dst_ptr) = -nudged_zero_point0; + dst_ptr += sizeof(int32_t); + + for (size_t k_idx = 0; k_idx < k; ++k_idx) { + const float src0_0 = src_ptr[k_idx]; + int32_t v0_s32 = (int32_t)(std::round(src0_0 * scale0)); + v0_s32 = std::max( + std::min(v0_s32 + nudged_zero_point0, static_cast(kI8Max)), + static_cast(kI8Min)); + dst_ptr[0] = (int8_t)v0_s32; + dst_ptr += sizeof(int8_t); + } + } + }; + + auto lhs_qa8dx_buffer = std::make_unique( + m * (k + sizeof(float) + sizeof(int32_t))); // Allocate for LHS + int8_t* lhs_qa8dx = lhs_qa8dx_buffer.get(); + // Quantize and pack LHS + lhs_quant_pack(m, k, lhs_f32, lhs_qa8dx); + + const size_t num_blocks_row = (((k + bl - 1) / bl) * bl) / bl; + const size_t lhs_stride = k + sizeof(float) + sizeof(int32_t); + const size_t rhs_stride = (((k + 2 - 1) / 2) * 2) / 2; + + for (size_t row_idx = 0; row_idx < m; ++row_idx) { + const int8_t* lhs_ptr_start = lhs_qa8dx + row_idx * lhs_stride; + + for (size_t col_idx = 0; col_idx < n; ++col_idx) { + float main_acc = 0.0f; + const int8_t* lhs_ptr = lhs_ptr_start; + const uint8_t* rhs_ptr = rhs_qs4c32 + col_idx * rhs_stride; + + const float lhs_scale = *(const float*)lhs_ptr; + lhs_ptr += sizeof(float); + const int32_t lhs_offset = *(const int32_t*)lhs_ptr; + lhs_ptr += sizeof(int32_t); + + for (size_t block_idx = 0; block_idx < num_blocks_row; ++block_idx) { + const float rhs_scale = + rhs_scales_fp32[block_idx + col_idx * num_blocks_row]; + int32_t iacc = 0; + + for (size_t i = 0; i < bl; ++i) { + const size_t k_idx = block_idx * bl + i; + if (k_idx >= k) { + break; + } + + const int32_t lhs_v0 = (int32_t)lhs_ptr[0]; + const uint8_t rhs_byte = rhs_ptr[0]; + int32_t rhs_v0 = (k_idx % 2 == 0) ? (((int32_t)(rhs_byte & 0x0F)) - 8) + : (((int32_t)(rhs_byte >> 4)) - 8); + + iacc += lhs_v0 * rhs_v0; + iacc += lhs_offset * rhs_v0; + + lhs_ptr += 1; + rhs_ptr += (k_idx % 2); + } + + main_acc += iacc * rhs_scale; + } + + main_acc = main_acc * lhs_scale; + + if (bias) { + main_acc += bias[col_idx]; + } + + main_acc = std::max(main_acc, scalar_min); + main_acc = std::min(main_acc, scalar_max); + + dst_f32[0] = main_acc; + dst_f32 += 1; + } + } +} + +/** + * Dynamic INT4 weight-only MatMul with per-row input quantization. + * + * Execution Flow: + * + * (INT4 Weights + FP Scales [+ optional Bias]) + * + * Input (FP32 or BF16) Packed Weight Buffer + * | | + * Row-wise Quantization (INT8) | + * | | + * INT8 Input Activation INT4 Quantized Weights + Scales + * \ / + * \ / + * Quantized Matrix Multiply + * | + * Output Tensor (BF16 or FP32) + * + * Notes: + * - Groupwise kernels expect BF16 scales + * - Channelwise kernels expect FP32 scales + * - Bias is currently unsupported in fallback path + */ +void dyn_quant_matmul_4bit_kernel( + const Tensor& output, + const Tensor& inp, + const Tensor& packed_weights, + const int64_t M, + const int64_t N, + const int64_t K, + const int64_t block_size) { +#if AT_KLEIDIAI_ENABLED() + const int64_t weight_packed_size = + kleidiai::kai_pack_rhs_int4_size(N, K, block_size, inp.scalar_type()); + if (weight_packed_size == packed_weights.numel()) { + // KleidiAI interface internally handles the Channelwise and groupwise + // distinction + kleidiai::kai_quant_pack_lhs_int4_mm(output, inp, packed_weights, M, N, K, block_size); + } else +#endif + { + { + void* input = inp.data_ptr(); + void* dst = output.data_ptr(); + + // Extract weights, sclaes and biases form from packed tensor + const int weights_elements = N * K / 2; + const int scale_elements = N * (K / block_size); + TORCH_CHECK(packed_weights.numel() >= (weights_elements + scale_elements), "Invalid packed weight tensor size"); + + auto extracted_weights = packed_weights.narrow(0, 0, weights_elements).to(kByte); + auto extracted_scales_and_bias = packed_weights.narrow(0, weights_elements, packed_weights.size(0) - weights_elements).to(kFloat); + auto float32_scales = extracted_scales_and_bias.narrow(0, 0, scale_elements); + + int bias_elements = packed_weights.numel() - (weights_elements + scale_elements); + float* weight_scales = float32_scales.data_ptr(); + + void* bias_data = nullptr; + if (bias_elements) { + auto float32_bias = extracted_scales_and_bias.narrow(0, scale_elements, bias_elements); + TORCH_CHECK(float32_bias.size(0) == N, "Expected bias length to match output dimension"); + bias_data = float32_bias.data_ptr(); + + } + // 2 elements of 4 bit weights are packed into 1 uint8 packet + uint8_t* weights_4bit = reinterpret_cast(extracted_weights.data_ptr()); + + // Dispatch to reference kernels + if (inp.scalar_type() == at::kBFloat16) { + // BF16 input, BF16 output + constexpr float BF16_MAX = 3.38953139e+38f; + constexpr float BF16_MIN = -BF16_MAX; + if (block_size == K) { + ref_dyn_quant_matmul_4bit_channelwise_kernel_bf16( + M, N, K, + (uint16_t*)input, weights_4bit, weight_scales, + (uint16_t*)dst, BF16_MIN, BF16_MAX, (float*)bias_data); + } else { + TORCH_CHECK(false, "Unsupported block size for BF16 fallback"); + } + } else if (inp.scalar_type() == at::kFloat) { + // FP32 input, FP32 output + if (block_size == K) { + ref_dyn_quant_matmul_4bit_channelwise_kernel( + M, N, K, + (float*)input, weights_4bit, weight_scales, + (float*)dst, -FLT_MAX, FLT_MAX, (float*)bias_data); + } else if (!(block_size % 32) && !(K % block_size)) { + ref_dyn_quant_matmul_4bit_groupwise_kernel( + M, N, K, block_size, + (float*)input, weights_4bit, weight_scales, + (float*)dst, -FLT_MAX, FLT_MAX, (float*)bias_data); + } else { + TORCH_CHECK(false, "Unsupported block size for FP32 fallback"); + } + } else { + TORCH_CHECK(false, "Unsupported input/output dtype combination for int4mm kernel"); + } +} +} +} // anonymous namespace +} +ALSO_REGISTER_AVX512_DISPATCH(weight_to_int4pack_stub, &weight_to_int4pack_kernel) +ALSO_REGISTER_AVX512_DISPATCH(int4pack_mm_stub, &int4pack_mm_kernel) +REGISTER_DISPATCH(dyn_quant_pack_4bit_weight_stub, &dyn_quant_pack_4bit_weight_kernel) +REGISTER_DISPATCH(dyn_quant_matmul_4bit_stub, &dyn_quant_matmul_4bit_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int8mm_kernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int8mm_kernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ce6f8eb1e1bd1d236b8ef8fa3395f1203cd9401 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int8mm_kernel.cpp @@ -0,0 +1,438 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if (defined(_WIN32) || defined(_WIN64)) +#define RESTRICT __restrict +#else +#define RESTRICT __restrict__ +#endif + +namespace at::native { + +namespace { + +#if defined(CPU_CAPABILITY_AVX512) && !defined(_MSC_VER) + +// A block : {BLOCK_M, BLOCK_K}, lda = K +// B block : {BLOCK_K, BLOCK_N}, ldb = K +// C block : {BLOCK_M, BLOCK_N}, ldc = N +// +// scales block: {BLOCK_N} +// +template +inline void tinygemm_kernel( + const BFloat16* RESTRICT A, + const int8_t* RESTRICT B, + const BFloat16* RESTRICT scales, + BFloat16* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + + constexpr int ROWS = BLOCK_M; + constexpr int COLS = BLOCK_N; + + const int PREFETCH_SIZE_K = 16 * 4; + + __m512 va; + __m512 vb[COLS]; + __m512 vc[ROWS * COLS]; + __m512 scale[COLS]; + + auto load_scale = [&](int i) { + float ss = static_cast(scales[i]); + scale[i] = _mm512_set1_ps(ss); + }; + c10::ForcedUnroll{}(load_scale); + + auto loadc = [&](auto i) { + vc[i] = _mm512_setzero_ps(); + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + + if constexpr (col == 0) { + __m256i a16 = _mm256_load_si256((__m256i*)(A + row * lda + k)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0); + } + vec::cvtbf16_fp32(a16, va); + } + + if constexpr (row == 0) { + __m128i b8 = _mm_load_si128((__m128i*)(B + col * ldb + k)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(B + col * ldb + k + PREFETCH_SIZE_K, _MM_HINT_T0); + } + __m512i b32 = _mm512_cvtepi8_epi32(b8); + vb[col] = _mm512_cvtepi32_ps(b32); + vb[col] = _mm512_mul_ps(vb[col], scale[col]); + } + + constexpr int idx = row * COLS + col; + vc[idx] = _mm512_fmadd_ps(va, vb[col], vc[idx]); + }; + + for (int k = 0; k < K; k += 16) { + c10::ForcedUnroll{}(compute, k); + } + + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + C[row * ldc + col] = static_cast(_mm512_reduce_add_ps(vc[i])); + }; + c10::ForcedUnroll{}(storec); +} + +#elif defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER) + +inline float _mm256_reduce_add_ps(__m256& v) { + __m256 v1 = _mm256_permute2f128_ps(v, v, 0x1); + v = _mm256_add_ps(v, v1); + v1 = _mm256_shuffle_ps(v, v, 0x4E); + v = _mm256_add_ps(v, v1); + v1 = _mm256_shuffle_ps(v, v, 0xB1); + v = _mm256_add_ps(v, v1); + return _mm256_cvtss_f32(v); +} + +template +inline void tinygemm_kernel( + const BFloat16* RESTRICT A, + const int8_t* RESTRICT B, + const BFloat16* RESTRICT scales, + BFloat16* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + + constexpr int ROWS = BLOCK_M; + constexpr int COLS = BLOCK_N; + + const int PREFETCH_SIZE_K = 16 * 4; + + __m256 va; + __m256 vb[COLS]; + __m256 vc[ROWS * COLS]; + __m256 scale[COLS]; + + auto load_scale = [&](int i) { + float ss = static_cast(scales[i]); + scale[i] = _mm256_set1_ps(ss); + }; + c10::ForcedUnroll{}(load_scale); + + auto loadc = [&](auto i) { + vc[i] = _mm256_setzero_ps(); + }; + c10::ForcedUnroll{}(loadc); + + auto compute = [&](auto i, int k) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + + if constexpr (col == 0) { + __m128i a16 = _mm_load_si128((__m128i*)(A + row * lda + k)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0); + } + vec::cvtbf16_fp32(a16, va); + } + + if constexpr (row == 0) { + __m128i b8 = _mm_loadu_si64((__m128i*)(B + col * ldb + k)); + if (k + PREFETCH_SIZE_K < K) { + _mm_prefetch(B + col * ldb + k + PREFETCH_SIZE_K, _MM_HINT_T0); + } + __m256i b32 = _mm256_cvtepi8_epi32(b8); + vb[col] = _mm256_cvtepi32_ps(b32); + vb[col] = _mm256_mul_ps(vb[col], scale[col]); + } + + constexpr int idx = row * COLS + col; + vc[idx] = _mm256_fmadd_ps(va, vb[col], vc[idx]); + }; + + for (int k = 0; k < K; k += 8) { + c10::ForcedUnroll{}(compute, k); + } + + auto storec = [&](auto i) { + constexpr int row = i / COLS; + constexpr int col = i % COLS; + C[row * ldc + col] = static_cast(_mm256_reduce_add_ps(vc[i])); + }; + c10::ForcedUnroll{}(storec); +} + +#endif + +#if !defined(C10_MOBILE) && defined(__aarch64__) +#include + +inline float reduce(float32x4_t x) { + auto sum = vpaddq_f32(x, x); + return vgetq_lane_f32(vpaddq_f32(sum, sum), 0); +} + +inline float32x4x2_t load_as_float32x4x2(const Half* ptr) { + float16x8_t f16_val = vld1q_f16(reinterpret_cast(ptr)); + auto val_low = vcvt_f32_f16(vget_low_f16(f16_val)); + auto val_high = vcvt_f32_f16(vget_high_f16(f16_val)); + return {val_low, val_high}; +} + +inline float32x4_t load_as_float32x4(const Half* ptr) { + return vcvt_f32_f16(vld1_f16(reinterpret_cast(ptr))); +} + +inline float32x4x2_t load_as_float32x4x2(const BFloat16* ptr) { + int32x4_t shift = vdupq_n_s32(16); + uint16x8_t u16_val = vld1q_u16(reinterpret_cast(ptr)); + uint32x4_t int_low = vmovl_u16(vget_low_u16(u16_val)); + uint32x4_t int_high = vmovl_u16(vget_high_u16(u16_val)); + return {vreinterpretq_f32_u32(vshlq_u32(int_low, shift)), vreinterpretq_f32_u32(vshlq_u32(int_high, shift))}; +} + +inline float32x4_t load_as_float32x4(const BFloat16* ptr) { + int32x4_t shift = vdupq_n_s32(16); + uint32x4_t as_int = vmovl_u16(vld1_u16(reinterpret_cast(ptr))); + return vreinterpretq_f32_u32(vshlq_u32(as_int, shift)); +} + +inline float32x4_t load_as_float32x4(const float* ptr) { + return vld1q_f32(ptr); +} + +inline float32x4x2_t load_as_float32x4x2(const float* ptr) { + return {vld1q_f32(ptr), vld1q_f32(ptr + 4)}; +} + +template +inline void tinygemm_kernel_( + const T* RESTRICT A, + const int8_t* RESTRICT B, + const T* RESTRICT scales, + T* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + + for (const auto m : c10::irange(BLOCK_M)) { + float32x4_t c_val[BLOCK_N]; + c10::ForcedUnroll{}([&](auto i) { + c_val[i] = vdupq_n_f32(0.0); + }); + for (int k = 0; k < K; k += 8) { + auto a_val = load_as_float32x4x2(A + m * lda + k); + c10::ForcedUnroll{}([&](auto i) { + int16x8_t b_val = vmovl_s8(vld1_s8(B + i * ldb + k)); + auto b_val_low = vcvtq_f32_s32(vmovl_s16(vget_low_s16(b_val))); + auto b_val_high = vcvtq_f32_s32(vmovl_s16(vget_high_s16(b_val))); + c_val[i] = vfmaq_f32(c_val[i], a_val.val[1], b_val_high); + c_val[i] = vfmaq_f32(c_val[i], a_val.val[0], b_val_low); + }); + } + +#if __OPTIMIZE__ + float32x4_t scale_val = load_as_float32x4(scales); + c10::ForcedUnroll{}([&](auto i) { + C[m * ldc + i] = reduce(c_val[i]) * vgetq_lane_f32(scale_val, i); + }); +#else + // Workaround GCCs inability to infer lane index at compile time + // See https://github.com/pytorch/pytorch/issues/126283 + c10::ForcedUnroll{}([&](auto i) { + C[m * ldc + i] = reduce(c_val[i]) * float(scales[i]); + }); +#endif + } +} + +template +inline void tinygemm_kernel( + const Half* RESTRICT A, + const int8_t* RESTRICT B, + const Half* RESTRICT scales, + Half* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + tinygemm_kernel_(A, B, scales, C, lda, ldb, ldc, K); +} + +template +inline void tinygemm_kernel( + const BFloat16* RESTRICT A, + const int8_t* RESTRICT B, + const BFloat16* RESTRICT scales, + BFloat16* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + tinygemm_kernel_(A, B, scales, C, lda, ldb, ldc, K); +} + +template +inline void tinygemm_kernel( + const float* RESTRICT A, + const int8_t* RESTRICT B, + const float* RESTRICT scales, + float* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + tinygemm_kernel_(A, B, scales, C, lda, ldb, ldc, K); +} +#endif + +// non-vectorized version +template +inline void tinygemm_kernel( + const T* RESTRICT A, + const int8_t* RESTRICT B, + const T* RESTRICT scales, + T* RESTRICT C, + int lda, + int ldb, + int ldc, + int K) { + + for (const auto m : c10::irange(BLOCK_M)) { + for (const auto n : c10::irange(BLOCK_N)) { + float c_val = 0; + float scale_val = static_cast(scales[n]); + for (const auto k : c10::irange(K)) { + float a_val = static_cast(A[m * lda + k]); + float b_val = static_cast(B[n * ldb + k]); + c_val += a_val * (b_val * scale_val); + } + C[m * ldc + n] = c_val; + } + } +} + +#define LAUNCH_TINYGEMM_KERNEL(MB_SIZE, NB_SIZE) \ + tinygemm_kernel( \ + A_ptr, B_ptr, S_ptr, C_ptr, \ + lda, K, N, K); + +#define LAUNCH_TINYGEMM_NB_SIZE(MB_SIZE) \ + switch (nb_size) { \ + case 1: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 1); \ + break; \ + case 2: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 2); \ + break; \ + case 3: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 3); \ + break; \ + case 4: \ + LAUNCH_TINYGEMM_KERNEL(MB_SIZE, 4); \ + break; \ + default: \ + TORCH_CHECK(false, "Unsupported n block size: ", nb_size); \ + break; \ + } + +template +void int8pack_mm_kernel_( + const Tensor& C, + const Tensor& A, + const Tensor& B, + const Tensor& scales) { + + const auto* A_data = A.const_data_ptr(); + const auto* B_data = B.const_data_ptr(); + auto* C_data = C.data_ptr(); + const auto* S_data = scales.const_data_ptr(); + + int64_t M = A.size(0); + int64_t N = B.size(0); + int64_t K = A.size(1); + int64_t lda = A.stride(0); + constexpr int64_t BLOCK_M = 4; + constexpr int64_t BLOCK_N = 4; + + const int64_t MB = (M + BLOCK_M - 1) / BLOCK_M; + const int64_t NB = (N + BLOCK_N - 1) / BLOCK_N; + + at::parallel_for(0, MB * NB, 0, [&](int64_t begin, int64_t end) { + int64_t mb{0}, nb{0}; + data_index_init(begin, mb, MB, nb, NB); + + for (const auto i : c10::irange(begin, end)) { + (void)i; + + int64_t mb_start = mb * BLOCK_M; + int64_t mb_size = std::min(BLOCK_M, M - mb_start); + int64_t nb_start = nb * BLOCK_N; + int64_t nb_size = std::min(BLOCK_N, N - nb_start); + + const auto* A_ptr = A_data + mb_start * lda; + const auto* B_ptr = B_data + nb_start * K; + const auto* S_ptr = S_data + nb_start; + auto* C_ptr = C_data + mb_start * N + nb_start; + + switch (mb_size) { + case 1: + LAUNCH_TINYGEMM_NB_SIZE(1); + break; + case 2: + LAUNCH_TINYGEMM_NB_SIZE(2); + break; + case 3: + LAUNCH_TINYGEMM_NB_SIZE(3); + break; + case 4: + LAUNCH_TINYGEMM_NB_SIZE(4); + break; + default: + TORCH_CHECK(false, "Unsupported m block size: ", mb_size); + } + + // move to the next index + data_index_step(mb, MB, nb, NB); + } + }); +} + +void int8pack_mm_kernel( + const Tensor& C, + const Tensor& A, + const Tensor& B, + const Tensor& scales) { + if (C.dtype() == kHalf) { + int8pack_mm_kernel_(C, A, B, scales); + } else if (C.dtype() == kBFloat16) { + int8pack_mm_kernel_(C, A, B, scales); + } else { + int8pack_mm_kernel_(C, A, B, scales); + } +} + +} // anonymous namespace + +ALSO_REGISTER_AVX512_DISPATCH(int8pack_mm_stub, &int8pack_mm_kernel) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int_mm_kernel.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int_mm_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..3076820331085d7b6e0df941d610fad2a290eb7a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/int_mm_kernel.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include + +namespace at::native { + +using weight_to_int4pack_fn = void (*)(const Tensor&, const Tensor&); +using int4pack_mm_fn = + void (*)(const Tensor&, const Tensor&, const Tensor&, int, const Tensor&); +using int8pack_mm_fn = + void (*)(const Tensor&, const Tensor&, const Tensor&, const Tensor&); +using dyn_quant_pack_4bit_weight_fn = void (*)( + Tensor&, + const Tensor&, + const Tensor&, + const std::optional& bias, + const int64_t, + const int64_t, + const int64_t); +using dyn_quant_matmul_4bit_fn = void (*)( + const Tensor&, + const Tensor&, + const Tensor&, + const int64_t, + const int64_t, + const int64_t, + const int64_t); + +DECLARE_DISPATCH(weight_to_int4pack_fn, weight_to_int4pack_stub) +DECLARE_DISPATCH(int4pack_mm_fn, int4pack_mm_stub) +DECLARE_DISPATCH(int8pack_mm_fn, int8pack_mm_stub) +DECLARE_DISPATCH( + dyn_quant_pack_4bit_weight_fn, + dyn_quant_pack_4bit_weight_stub) +DECLARE_DISPATCH(dyn_quant_matmul_4bit_fn, dyn_quant_matmul_4bit_stub) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/layer_norm_kernel.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/layer_norm_kernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c171c40c89b295de955851d3b5e7bbbd060d7e26 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/layer_norm_kernel.cpp @@ -0,0 +1,633 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +namespace at::native { + +namespace { + +template +void LayerNormSecondPass( + const T* X_ptr, + const T* gamma_data, + const T* beta_data, + T* Y_ptr, + int64_t N, + T scale, + T bias) { + using Vec = vec::Vectorized; + const bool gamma_null = gamma_data == nullptr; + const bool beta_null = beta_data == nullptr; + if (gamma_null || beta_null) { + for (const auto j : c10::irange(N)) { + const T gamma_v = gamma_null ? T(1) : gamma_data[j]; + const T beta_v = beta_null ? T(0) : beta_data[j]; + Y_ptr[j] = (X_ptr[j] + bias) * scale * gamma_v + beta_v; + } + } else { + vec::map3( + [scale, bias](Vec x, Vec gamma, Vec beta) { + return (x + Vec(bias)) * Vec(scale) * gamma + beta; + }, + Y_ptr, + X_ptr, + gamma_data, + beta_data, + N); + } +} + +template , int> = 0> +void LayerNormKernelImplInternal( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t M, + int64_t N, + T eps, + Tensor* Y, + Tensor* mean, + Tensor* rstd) { + const T* X_data = X.const_data_ptr(); + const T* gamma_data = gamma.defined() ? gamma.const_data_ptr() : nullptr; + const T* beta_data = beta.defined() ? beta.const_data_ptr() : nullptr; + T* Y_data = Y->data_ptr(); + T* mean_data = mean ? mean->data_ptr() : nullptr; + T* rstd_data = rstd ? rstd->data_ptr() : nullptr; + + const bool mean_null = mean_data == nullptr; + const bool rstd_null = rstd_data == nullptr; + at::parallel_for(0, M, 1, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + const T* X_ptr = X_data + i * N; + T* Y_ptr = Y_data + i * N; + auto [mean_val, rstd_val] = RowwiseMoments(X_ptr, N); + rstd_val = T(1) / std::sqrt(rstd_val + eps); + const T scale = rstd_val; + const T bias = - mean_val; + LayerNormSecondPass(X_ptr, gamma_data, beta_data, Y_ptr, N, scale, bias); + if (!mean_null) { + mean_data[i] = mean_val; + } + if (!rstd_null) { + rstd_data[i] = rstd_val; + } + } + }); +} + +template , int> = 0> +void layer_norm_kernel_mixed_type( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t M, + int64_t N, + float eps, + Tensor* Y, + Tensor* mean, + Tensor* rstd) { + using bVec = Vectorized; + using fVec = Vectorized; + const T* X_data = X.const_data_ptr(); + const param_t* gamma_data = gamma.defined() ? gamma.const_data_ptr() : nullptr; + const param_t* beta_data = beta.defined() ? beta.const_data_ptr() : nullptr; + T* Y_data = Y->data_ptr(); + param_t* mean_data = mean ? mean->data_ptr() : nullptr; + param_t* rstd_data = rstd ? rstd->data_ptr() : nullptr; + + const bool gamma_null = gamma_data == nullptr; + const bool beta_null = beta_data == nullptr; + const bool mean_null = mean_data == nullptr; + const bool rstd_null = rstd_data == nullptr; + at::parallel_for(0, M, 1, [&](int64_t start, int64_t end) { + for (const auto i : c10::irange(start, end)) { + const T* X_ptr = X_data + i * N; + T* Y_ptr = Y_data + i * N; + auto [mean_val, rstd_val] = RowwiseMoments(X_ptr, N); + rstd_val = float(1) / std::sqrt(rstd_val + eps); + const float scale = rstd_val; + const float bias = -rstd_val * mean_val; + int64_t d = 0; + for (; d < N - (N % bVec::size()); d += bVec::size()) { + bVec x_bvec = bVec::loadu(X_ptr + d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + auto [gamma_fvec0, gamma_fvec1] = gamma_null ? std::make_tuple(fVec(1), fVec(1)) : load2f(gamma_data + d); + auto [beta_fvec0, beta_fvec1] = beta_null ? std::make_tuple(fVec(0), fVec(0)) : load2f(beta_data + d); + fVec y_fvec0 = (x_fvec0 * fVec(scale) + fVec(bias)) * gamma_fvec0 + beta_fvec0; + fVec y_fvec1 = (x_fvec1 * fVec(scale) + fVec(bias)) * gamma_fvec1 + beta_fvec1; + bVec y_bvec = convert_from_float(y_fvec0, y_fvec1); + y_bvec.store(Y_ptr + d); + } + for (; d < N; d++) { + const float gamma_v = gamma_null ? float(1) : float(gamma_data[d]); + const float beta_v = beta_null ? float(0) : float(beta_data[d]); + Y_ptr[d] = (float(X_ptr[d]) * scale + bias) * gamma_v + beta_v; + } + if (!mean_null) { + mean_data[i] = mean_val; + } + if (!rstd_null) { + rstd_data[i] = rstd_val; + } + } + }); +} + +template , int> = 0> +void LayerNormKernelImplInternal( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t M, + int64_t N, + float eps, + Tensor* Y, + Tensor* mean, + Tensor* rstd) { + const bool mixed_type = is_mixed_type(X, gamma, beta); + if (mixed_type) { + layer_norm_kernel_mixed_type(X, gamma, beta, M, N, eps, Y, mean, rstd); + } else { + layer_norm_kernel_mixed_type(X, gamma, beta, M, N, eps, Y, mean, rstd); + } +} + +void LayerNormKernelImpl( + const Tensor& X, + const Tensor& gamma, + const Tensor& beta, + int64_t M, + int64_t N, + double eps, + Tensor* Y, + Tensor* mean, + Tensor* rstd) { + TORCH_DCHECK_EQ(X.numel(), M * N); + DCHECK(!gamma.defined() || gamma.numel() == N); + DCHECK(!beta.defined() || beta.numel() == N); + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, X.scalar_type(), + "LayerNormKernelImpl", [&]() { + LayerNormKernelImplInternal( + X, gamma, beta, M, N, eps, Y, mean, rstd); + }); +} + +template +void layer_norm_backward_frame( + const T* dY_data, + const T* X_data, + const T2* mean_data, + const T2* rstd_data, + const T2* gamma_data, + T* dX_data, + T* dgamma_buffer_ptr, + T* dbeta_buffer_ptr, + // NOTE: the below @lint-ignore is only necessary because we compile + // specializations of this function for c10::complex. + // It's extremely likely that nobody actually takes layer norms of + // complex tensors, and even if they are, c10::complex is laid out poorly + // and basically should never be used. + // So it would be nice in the future to figure out how to stop compiling + // specializations of compute kernels for c10::complex. + // @lint-ignore CLANGTIDY facebook-hte-ConstantArgumentPassByValue + const opmath_t scale, + const bool gamma_null, + const bool dX_null, + const bool dgamma_null, + const bool dbeta_null, + int64_t N, + int64_t i) { + using Vec = vec::Vectorized; + const T* dY_ptr = dY_data + i * N; + const T* X_ptr = X_data + i * N; + if (!dgamma_null) { + const opmath_t a = rstd_data[i]; + const opmath_t b = -a * mean_data[i]; + // Scalar math: + // for (const auto j : c10::irange(N)) { + // dgamma_data[j] += dY_ptr[j] * (a * X_ptr[j] + b); + // } + vec::map3( + [a, b](Vec dgamma, Vec dy, Vec x) { + return dgamma + dy * (Vec(a) * x + Vec(b)); + }, + dgamma_buffer_ptr, + dgamma_buffer_ptr, + dY_ptr, + X_ptr, + N); + } + if (!dbeta_null) { + // Scalar math: + // for (const auto j : c10::irange(N)) { + // dbeta_data[j] += dY_ptr[j]; + // } + vec::map2( + [](Vec dbeta, Vec dy) { return dbeta + dy; }, + dbeta_buffer_ptr, + dbeta_buffer_ptr, + dY_ptr, + N); + } + if (!dX_null) { + T* dX_ptr = dX_data + i * N; + opmath_t ds = opmath_t(0); + opmath_t db = opmath_t(0); + // Scalar math: + // for (const auto j : c10::irange(N)) { + // const T gamma_v = gamma_null ? T(1) : gamma_data[j]; + // ds += dY_ptr[j] * X_ptr[j] * gamma_v; + // db += dY_ptr[j] * gamma_v; + // } + if (gamma_null) { + ds = vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + dY_ptr, + X_ptr, + N); + db = vec::reduce_all( + [](Vec& x, Vec& y) { return x + y; }, dY_ptr, N); + } else { + ds = vec::map3_reduce_all( + [](Vec x, Vec y, Vec z) { return x * y * z; }, + [](Vec x, Vec y) { return x + y; }, + dY_ptr, + X_ptr, + gamma_data, + N); + db = vec::map2_reduce_all( + [](Vec x, Vec y) { return x * y; }, + [](Vec x, Vec y) { return x + y; }, + dY_ptr, + gamma_data, + N); + } + const opmath_t a = rstd_data[i]; + const opmath_t b = (db * opmath_t(mean_data[i]) - ds) * a * a * a * scale; + const opmath_t c = -b * opmath_t(mean_data[i]) - db * a * scale; + // Scalar math: + // for (const auto j : c10::irange(N)) { + // const T gamma_v = gamma_null ? T(1) : gamma_data[j]; + // dX_ptr[j] = a * dY_ptr[j] * gamma_v + b * X_ptr[j] + c; + // } + if (gamma_null) { + vec::map2( + [a, b, c](Vec dy, Vec x) { + return Vec(a) * dy + Vec(b) * x + Vec(c); + }, + dX_ptr, + dY_ptr, + X_ptr, + N); + } else { + vec::map3( + [a, b, c](Vec dy, Vec gamma, Vec x) { + return Vec(a) * dy * gamma + Vec(b) * x + Vec(c); + }, + dX_ptr, + dY_ptr, + gamma_data, + X_ptr, + N); + } + } +} + +template && std::is_same_v, int> = 0> +void layer_norm_backward_frame( + const T* dY_data, + const T* X_data, + const float* mean_data, + const float* rstd_data, + const float* gamma_data, + T* dX_data, + T* dgamma_buffer_ptr, + T* dbeta_buffer_ptr, + const float scale, + const bool gamma_null, + const bool dX_null, + const bool dgamma_null, + const bool dbeta_null, + int64_t N, + int64_t i) { + using bVec = Vectorized; + using fVec = Vectorized; + const T* dY_ptr = dY_data + i * N; + const T* X_ptr = X_data + i * N; + if (!dgamma_null) { + const float a = rstd_data[i]; + const float b = -a * mean_data[i]; + // Scalar math: + // for (const auto j : c10::irange(N)) { + // dgamma_data[j] += dY_ptr[j] * (a * X_ptr[j] + b); + // } + vec::map3( + [a, b](fVec dgamma, fVec dy, fVec x) { + return dgamma + dy * (fVec(a) * x + fVec(b)); + }, + dgamma_buffer_ptr, + dgamma_buffer_ptr, + dY_ptr, + X_ptr, + N); + } + if (!dbeta_null) { + // Scalar math: + // for (const auto j : c10::irange(N)) { + // dbeta_data[j] += dY_ptr[j]; + // } + vec::map2( + [](fVec dbeta, fVec dy) { return dbeta + dy; }, + dbeta_buffer_ptr, + dbeta_buffer_ptr, + dY_ptr, + N); + } + if (!dX_null) { + T* dX_ptr = dX_data + i * N; + float ds = float(0); + float db = float(0); + // Scalar math: + // for (const auto j : c10::irange(N)) { + // const T gamma_v = gamma_null ? T(1) : gamma_data[j]; + // ds += dY_ptr[j] * X_ptr[j] * gamma_v; + // db += dY_ptr[j] * gamma_v; + // } + if (gamma_null) { + ds = vec::map2_reduce_all( + [](fVec x, fVec y) { return x * y; }, + [](fVec x, fVec y) { return x + y; }, + dY_ptr, + X_ptr, + N); + db = vec::reduce_all( + [](fVec& x, fVec& y) { return x + y; }, dY_ptr, N); + } else { + if (N < bVec::size()) { + bVec x_bvec = bVec::loadu(X_ptr, N); + bVec dy_bvec = bVec::loadu(dY_ptr, N); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + auto [gamma_fvec0, gamma_fvec1] = load2f(gamma_data, N); + if (N > fVec::size()) { + fVec db_fvec0 = dy_fvec0 * gamma_fvec0; + fVec db_fvec1 = dy_fvec1 * gamma_fvec1; + fVec ds_fvec0 = x_fvec0 * db_fvec0; + fVec ds_fvec1 = x_fvec1 * db_fvec1; + ds_fvec0 = fVec::set(ds_fvec0, ds_fvec0 + ds_fvec1, N - fVec::size()); + ds = vec_reduce_all([](fVec x, fVec y) { return x + y; }, ds_fvec0); + db_fvec0 = fVec::set(db_fvec0, db_fvec0 + db_fvec1, N - fVec::size()); + db = vec_reduce_all([](fVec x, fVec y) { return x + y; }, db_fvec0); + } else { + fVec db_fvec0 = dy_fvec0 * gamma_fvec0; + fVec ds_fvec0 = x_fvec0 * db_fvec0; + ds = vec_reduce_all([](fVec x, fVec y) { return x + y; }, ds_fvec0, N); + db = vec_reduce_all([](fVec x, fVec y) { return x + y; }, db_fvec0, N); + } + } else { + int64_t d = bVec::size(); + bVec x_bvec = bVec::loadu(X_ptr); + bVec dy_bvec = bVec::loadu(dY_ptr); + fVec ds_fvec0, ds_fvec1, db_fvec0, db_fvec1, acc_ds_fvec0, acc_ds_fvec1, acc_db_fvec0, acc_db_fvec1; + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + auto [gamma_fvec0, gamma_fvec1] = load2f(gamma_data); + acc_db_fvec0 = dy_fvec0 * gamma_fvec0; + acc_db_fvec1 = dy_fvec1 * gamma_fvec1; + acc_ds_fvec0 = x_fvec0 * acc_db_fvec0; + acc_ds_fvec1 = x_fvec1 * acc_db_fvec1; + for (; d < N - (N % bVec::size()); d += bVec::size()) { + x_bvec = bVec::loadu(X_ptr + d); + dy_bvec = bVec::loadu(dY_ptr + d); + std::tie(x_fvec0, x_fvec1) = convert_to_float(x_bvec); + std::tie(dy_fvec0, dy_fvec1) = convert_to_float(dy_bvec); + std::tie(gamma_fvec0, gamma_fvec1) = load2f(gamma_data + d); + db_fvec0 = dy_fvec0 * gamma_fvec0; + db_fvec1 = dy_fvec1 * gamma_fvec1; + ds_fvec0 = x_fvec0 * db_fvec0; + ds_fvec1 = x_fvec1 * db_fvec1; + acc_ds_fvec0 = acc_ds_fvec0 + ds_fvec0; + acc_ds_fvec1 = acc_ds_fvec1 + ds_fvec1; + acc_db_fvec0 = acc_db_fvec0 + db_fvec0; + acc_db_fvec1 = acc_db_fvec1 + db_fvec1; + } + if (N - d > 0) { + x_bvec = bVec::loadu(X_ptr + d, N - d); + dy_bvec = bVec::loadu(dY_ptr + d, N - d); + std::tie(x_fvec0, x_fvec1) = convert_to_float(x_bvec); + std::tie(dy_fvec0, dy_fvec1) = convert_to_float(dy_bvec); + std::tie(gamma_fvec0, gamma_fvec1) = load2f(gamma_data + d, N - d); + if (N - d > fVec::size()) { + db_fvec0 = dy_fvec0 * gamma_fvec0; + db_fvec1 = dy_fvec1 * gamma_fvec1; + ds_fvec0 = x_fvec0 * db_fvec0; + ds_fvec1 = x_fvec1 * db_fvec1; + acc_ds_fvec0 = acc_ds_fvec0 + ds_fvec0; + acc_ds_fvec1 = fVec::set(acc_ds_fvec1, acc_ds_fvec1 + ds_fvec1, N - d - fVec::size()); + acc_db_fvec0 = acc_db_fvec0 + db_fvec0; + acc_db_fvec1 = fVec::set(acc_db_fvec1, acc_db_fvec1 + db_fvec1, N - d - fVec::size()); + } else { + db_fvec0 = dy_fvec0 * gamma_fvec0; + ds_fvec0 = x_fvec0 * db_fvec0; + acc_ds_fvec0 = fVec::set(acc_ds_fvec0, acc_ds_fvec0 + ds_fvec0, N - d); + acc_db_fvec0 = fVec::set(acc_db_fvec0, acc_db_fvec0 + db_fvec0, N - d); + } + } + acc_ds_fvec0 = acc_ds_fvec0 + acc_ds_fvec1; + acc_db_fvec0 = acc_db_fvec0 + acc_db_fvec1; + ds = vec_reduce_all([](fVec x, fVec y) { return x + y; }, acc_ds_fvec0); + db = vec_reduce_all([](fVec x, fVec y) { return x + y; }, acc_db_fvec0); + } + } + const float a = rstd_data[i]; + const float b = (db * mean_data[i] - ds) * a * a * a * scale; + const float c = -b * mean_data[i] - db * a * scale; + // Scalar math: + // for (const auto j : c10::irange(N)) { + // const T gamma_v = gamma_null ? T(1) : gamma_data[j]; + // dX_ptr[j] = a * dY_ptr[j] * gamma_v + b * X_ptr[j] + c; + // } + if (gamma_null) { + vec::map2( + [a, b, c](fVec dy, fVec x) { + return fVec(a) * dy + fVec(b) * x + fVec(c); + }, + dX_ptr, + dY_ptr, + X_ptr, + N); + } else { + int64_t d = 0; + for (; d < N - (N % bVec::size()); d += bVec::size()) { + bVec x_bvec = bVec::loadu(X_ptr + d); + bVec dy_bvec = bVec::loadu(dY_ptr + d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + auto [gamma_fvec0, gamma_fvec1] = load2f(gamma_data + d); + fVec r_fvec0 = fVec(a) * dy_fvec0 * gamma_fvec0 + fVec(b) * x_fvec0 + fVec(c); + fVec r_fvec1 = fVec(a) * dy_fvec1 * gamma_fvec1 + fVec(b) * x_fvec1 + fVec(c); + bVec r_bvec = convert_from_float(r_fvec0, r_fvec1); + r_bvec.store(dX_ptr + d); + } + if (N - d > 0) { + bVec x_bvec = bVec::loadu(X_ptr + d, N - d); + bVec dy_bvec = bVec::loadu(dY_ptr + d, N - d); + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + auto [dy_fvec0, dy_fvec1] = convert_to_float(dy_bvec); + auto [gamma_fvec0, gamma_fvec1] = load2f(gamma_data + d, N - d); + fVec r_fvec0 = fVec(a) * dy_fvec0 * gamma_fvec0 + fVec(b) * x_fvec0 + fVec(c); + fVec r_fvec1 = fVec(a) * dy_fvec1 * gamma_fvec1 + fVec(b) * x_fvec1 + fVec(c); + bVec r_bvec = convert_from_float(r_fvec0, r_fvec1); + r_bvec.store(dX_ptr + d, static_cast(N - d)); + } + } + } +} + +template +void LayerNormBackwardKernelImplInternal( + const Tensor& dY, + const Tensor& X, + const Tensor& mean, + const Tensor& rstd, + const Tensor& gamma, + int64_t M, + int64_t N, + Tensor* dX, + Tensor* dgamma, + Tensor* dbeta) { + using opmath_t = at::opmath_type; + TORCH_DCHECK_EQ(dY.numel(), M * N); + TORCH_DCHECK_EQ(X.numel(), M * N); + TORCH_DCHECK_EQ(mean.numel(), M); + TORCH_DCHECK_EQ(rstd.numel(), M); + DCHECK(!gamma.defined() || gamma.numel() == N); + const T* dY_data = dY.template const_data_ptr(); + const T* X_data = X.template const_data_ptr(); + const T2* mean_data = mean.template const_data_ptr(); + const T2* rstd_data = rstd.template const_data_ptr(); + const T2* gamma_data = + gamma.defined() ? gamma.template const_data_ptr() : nullptr; + T* dX_data = dX->defined() ? dX->template data_ptr() : nullptr; + T2* const dgamma_data = dgamma->defined() ? dgamma->template data_ptr() : nullptr; + T2* const dbeta_data = dbeta->defined() ? dbeta->template data_ptr() : nullptr; + const opmath_t scale = opmath_t(1) / static_cast(N); + const bool gamma_null = gamma_data == nullptr; + const bool dX_null = dX_data == nullptr; + const bool dgamma_null = dgamma_data == nullptr; + const bool dbeta_null = dbeta_data == nullptr; + + // 1. Use two path parallel reduction for dgamma and dbeta: + // First path: allocate an immediate buffer of size {2, max_threads, N}, + // dgamma_buffer = buffer[0], dbeta_buffer = buffer[1] + // Parallel along dim0 and reduce dY and X along dim0 to buffer. + // Second path: parallel along dim1 and reduce buffer to dgamma and dbeta. + // + // 2. Fuse first path of dgamma/dbeta with dX to reuse X[i] and dY[i] in L1 + // cache. + // + int num_threads = at::get_num_threads(); + Tensor buffer = at::empty({0}, X.options()); + T* buffer_data = nullptr; + if (!dgamma_null || !dbeta_null) { + // zero the immediate buffer and skip zero dgamma and dbeta + buffer.resize_({2, num_threads, N}).zero_(); + buffer_data = buffer.template data_ptr(); + } + + // First path of dgamma/dbeta and dX + at::parallel_for(0, M, 1, [&](int64_t start, int64_t end) { + int tid = at::get_thread_num(); + TORCH_CHECK( + tid < num_threads, + "expect thread id smaller than ", + num_threads, + ", got thread id ", + tid); + T* dgamma_buffer_ptr = dgamma_null ? nullptr : buffer_data + tid * N; + T* dbeta_buffer_ptr = + dbeta_null ? nullptr : buffer_data + num_threads * N + tid * N; + for (const auto i : c10::irange(start, end)) { + layer_norm_backward_frame(dY_data, X_data, mean_data, rstd_data, gamma_data, dX_data, dgamma_buffer_ptr, dbeta_buffer_ptr, scale, gamma_null, dX_null, dgamma_null, dbeta_null, N, i); + } + }); + + // Second path of dgamma/dbeta + if (buffer_data != nullptr) { + parallel_for(0, N, 1, [&](int64_t start, int64_t end) { + for (const auto j : c10::irange(start, end)) { + opmath_t dgamma_v = opmath_t(0); + opmath_t dbeta_v = opmath_t(0); + for (const auto i : c10::irange(num_threads)) { + dgamma_v += buffer_data[i * N + j]; + dbeta_v += buffer_data[num_threads * N + i * N + j]; + } + if (!dgamma_null) { + dgamma_data[j] = dgamma_v; + } + if (!dbeta_null) { + dbeta_data[j] = dbeta_v; + } + } + }); + } +} + +void LayerNormBackwardKernelImpl( + const Tensor& dY, + const Tensor& X, + const Tensor& mean, + const Tensor& rstd, + const Tensor& gamma, + int64_t M, + int64_t N, + Tensor* dX, + Tensor* dgamma, + Tensor* dbeta) { + if (at::isReducedFloatingType(X.scalar_type())) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(X.scalar_type(), "LayerNormBackwardKernelImpl", [&]() { + if (gamma.scalar_type() == at::kFloat) { + LayerNormBackwardKernelImplInternal( + dY.contiguous(), X, mean, rstd, gamma, M, N, dX, dgamma, dbeta); + } else { + LayerNormBackwardKernelImplInternal( + dY.contiguous(), X, mean, rstd, gamma, M, N, dX, dgamma, dbeta); + } + }); + } else { + AT_DISPATCH_FLOATING_TYPES(X.scalar_type(), "LayerNormBackwardKernelImpl", [&]() { + LayerNormBackwardKernelImplInternal( + dY.contiguous(), X, mean, rstd, gamma, M, N, dX, dgamma, dbeta); + }); + } +} + +} // namespace + +REGISTER_DISPATCH(LayerNormKernel, &LayerNormKernelImpl) +REGISTER_DISPATCH(LayerNormBackwardKernel, &LayerNormBackwardKernelImpl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/mixed_data_type.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/mixed_data_type.h new file mode 100644 index 0000000000000000000000000000000000000000..6bb14031e487ea1ea4838ba3dc6a8a52e8627f18 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/mixed_data_type.h @@ -0,0 +1,41 @@ +#pragma once + +#include + +namespace at::native { + +inline ScalarType first_type() { + return ScalarType::Undefined; +} + +template +inline ScalarType first_type(const Tensor& arg, const Args&... parameters) { + return arg.defined() ? arg.scalar_type() : first_type(parameters...); +} + +template +inline bool is_mixed_type(const Tensor& input, const Args&... parameters) { + const auto parameter_type = first_type(parameters...); + return ((parameter_type != ScalarType::Undefined) && + (parameter_type != input.scalar_type())); +} + +// currently on CPU, mixed data type is only supported +// when input is 'BFloat16' or 'Half' and parameters are 'Float' +inline void check_mixed_data_type(const Tensor& input) { + TORCH_CHECK(at::isReducedFloatingType(input.scalar_type()), + "mixed dtype (CPU): all inputs must share same datatype."); +} + +template +inline void check_mixed_data_type(const Tensor& input, const Tensor& parameter, const Args&... parameters) { + TORCH_CHECK(!parameter.defined() || parameter.scalar_type() == ScalarType::Float, + "mixed dtype (CPU): expect parameter to have scalar type of Float"); + check_mixed_data_type(input, parameters...); +} + +inline ScalarType param_scalar_type(const Tensor& t, bool is_mixed_type) { + return is_mixed_type ? ScalarType::Float : t.scalar_type(); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/moments_utils.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/moments_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..0d7b7fb0e819c77ae601f932f89fc5745d4d64f1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/moments_utils.h @@ -0,0 +1,211 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + +template using opmath_t = at::opmath_type; + +constexpr int64_t kChunkSize = 16; + +template +void AddMoments( + int64_t m0_add, + const T& m1_add, + const T& m2_add, + int64_t& m0, + T& m1, + T& m2) { + const int64_t n = m0 + m0_add; + const T c = n == 0 ? static_cast(0) : static_cast(m0_add) / static_cast(n); + const T delta = m1_add - m1; + m1 += c * delta; + m2 += m2_add + delta * delta * c * static_cast(m0); + m0 = n; +} + +template +C10_ALWAYS_INLINE void AddMomentsVec( + int64_t m0_add, + const vec::Vectorized& m1_add, + const vec::Vectorized& m2_add, + int64_t& m0, + vec::Vectorized& m1, + vec::Vectorized& m2) { + using Vec = vec::Vectorized; + const int64_t n = m0 + m0_add; + const T c = n == 0 ? static_cast(0) : static_cast(m0_add) / static_cast(n); + const Vec c_vec(c); + const Vec delta = m1_add - m1; + const Vec m2_tmp = m2 + m2_add; + const Vec c_vec_delta = c_vec * delta; + const Vec m0_delta = delta * Vec(static_cast(m0)); + m1 = m1 + c_vec_delta; + m2 = fmadd(m0_delta, c_vec_delta, m2_tmp); + m0 = n; +} + +template +inline std::enable_if_t>, void> +UpdateMomentsVec( + int64_t m0, + const T* X_ptr, + const std::array>, kChunkSize>& c_vecs, + int64_t& m0_stk0, + vec::Vectorized>& m1_stk0, + vec::Vectorized>& m2_stk0) { + using Vec = vec::Vectorized>; + Vec m1_vec(0); + Vec m2_vec(0); + for (const auto j : c10::irange(m0)) { + const Vec x_vec = Vec::loadu(X_ptr + j * Vec::size()); + const Vec tmpVec = c_vecs[j]; + const Vec delta_vec = x_vec - m1_vec; + m1_vec = fmadd(tmpVec, delta_vec, m1_vec); + const Vec tmpVec2 = x_vec - m1_vec; + m2_vec = fmadd(delta_vec, tmpVec2, m2_vec); + } + AddMomentsVec(m0, m1_vec, m2_vec, m0_stk0, m1_stk0, m2_stk0); +} + +// each bfloat16/half vector will be converted to two float vectors, +// and accumulated successively on m1_stk0/m2_stk0. +template +inline std::enable_if_t>, void> +UpdateMomentsVec( + int64_t m0, + const T* X_ptr, + const std::array>, kChunkSize>& c_vecs, + int64_t& m0_stk0, + vec::Vectorized>& m1_stk0, + vec::Vectorized>& m2_stk0) { + using Vec = vec::Vectorized; + using fVec = vec::Vectorized>; + fVec m1_fvec0(0), m1_fvec1(0); + fVec m2_fvec0(0), m2_fvec1(0); + for (const auto j : c10::irange(m0)) { + const Vec x_bvec = Vec::loadu(X_ptr + j * Vec::size()); + const fVec tmpVec = c_vecs[j]; + auto [x_fvec0, x_fvec1] = convert_to_float(x_bvec); + const fVec delta_fvec0 = x_fvec0 - m1_fvec0; + const fVec delta_fvec1 = x_fvec1 - m1_fvec1; + m1_fvec0 = fmadd(delta_fvec0, tmpVec, m1_fvec0); + m1_fvec1 = fmadd(delta_fvec1, tmpVec, m1_fvec1); + const fVec delta_fvec2 = x_fvec0 - m1_fvec0; + const fVec delta_fvec3 = x_fvec1 - m1_fvec1; + m2_fvec0 = fmadd(delta_fvec0, delta_fvec2, m2_fvec0); + m2_fvec1 = fmadd(delta_fvec1, delta_fvec3, m2_fvec1); + } + AddMomentsVec(m0, m1_fvec0, m2_fvec0, m0_stk0, m1_stk0, m2_stk0); + AddMomentsVec(m0, m1_fvec1, m2_fvec1, m0_stk0, m1_stk0, m2_stk0); +} + +// Compute rowwise moments by Welford algorithm and cascade sum to improve +// numerical stability. +// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance +// https://en.wikipedia.org/wiki/Pairwise_summation +template +std::pair, opmath_t> RowwiseMomentsImpl(const T* X, int64_t N, int64_t ddof = 0) { + using math_t = opmath_t; + + constexpr int64_t kVecSize = vec::Vectorized::size(); + constexpr int64_t kAccVecSize = vec::Vectorized::size(); + const int64_t n = N / kVecSize; + const int64_t m = divup(n, kChunkSize); + const int64_t depth = utils::CeilLog2(m); + + using Vec = vec::Vectorized; + const Vec kZeroVec(math_t(0)); + std::array m0_stk = {{0}}; + std::array m1_stk; + m1_stk.fill(kZeroVec); + std::array m2_stk; + m2_stk.fill(kZeroVec); + + for (const auto i : c10::irange(m)) { + const T* X_ptr = X + i * kChunkSize * kVecSize; + const int64_t m0 = std::min(kChunkSize, n - i * kChunkSize); + static std::array c_vecs = ([]() { + std::array result; + for (const auto i : c10::irange(kChunkSize)) { + result[i] = Vec(math_t(1) / static_cast(i + 1)); + } + return result; + })(); + UpdateMomentsVec(m0, X_ptr, c_vecs, m0_stk[0], m1_stk[0], m2_stk[0]); + + int64_t mask = i + 1; + for (int64_t j = 1; j < depth && (mask & 1) == 0; ++j) { + AddMomentsVec( + m0_stk[j - 1], + m1_stk[j - 1], + m2_stk[j - 1], + m0_stk[j], + m1_stk[j], + m2_stk[j]); + m0_stk[j - 1] = 0; + m1_stk[j - 1] = kZeroVec; + m2_stk[j - 1] = kZeroVec; + mask >>= 1; + } + } + for (const auto i : c10::irange(1, depth)) { + AddMomentsVec( + m0_stk[i], m1_stk[i], m2_stk[i], m0_stk[0], m1_stk[0], m2_stk[0]); + } + + std::array m1_arr{}; + std::array m2_arr{}; + m1_stk[0].store(m1_arr.data()); + m2_stk[0].store(m2_arr.data()); + + int64_t m0 = 0; + math_t m1 = 0; + math_t m2 = 0; + for (int64_t i = n * kVecSize; i < N; ++i) { + math_t x = static_cast(X[i]); + const math_t delta = x - m1; + ++m0; + m1 += delta / static_cast(m0); + m2 += delta * (x - m1); + } + // for BFloat16, each vector in m1_arr/m2_arr holds 2*n accumulated result + int64_t m0_add = n * kVecSize / kAccVecSize; + for (const auto i : c10::irange(kAccVecSize)) { + AddMoments(m0_add, m1_arr[i], m2_arr[i], m0, m1, m2); + } + + return std::make_pair(m1, m2 / static_cast(N - ddof)); +} + +template +std::pair, opmath_t> RowwiseMoments(const T* X, int64_t N, int64_t ddof = 0) { + using Vec = vec::Vectorized; + constexpr int64_t kVecSize = Vec::size(); + const int64_t n = N / kVecSize; + const int64_t m = divup(n, kChunkSize); + const int64_t depth = utils::CeilLog2(m); + if (depth <= 4) { + return RowwiseMomentsImpl(X, N, ddof); + } else if (depth <= 8) { + return RowwiseMomentsImpl(X, N, ddof); + } else if (depth <= 16) { + return RowwiseMomentsImpl(X, N, ddof); + } else if (depth <= 32) { + return RowwiseMomentsImpl(X, N, ddof); + } else { + return RowwiseMomentsImpl(X, N, ddof); + } +} + +} // namespace CPU_CAPABILITY +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/scaled_modified_bessel_k0.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/scaled_modified_bessel_k0.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ea07998f17c2521843c6332d8d2489e15ccc45c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/scaled_modified_bessel_k0.cpp @@ -0,0 +1,24 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include + +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + static void scaled_modified_bessel_k0_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "scaled_modified_bessel_k0_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return scaled_modified_bessel_k0_forward(x); + }); + }); + } // scaled_modified_bessel_k0_kernel(TensorIteratorBase& iterator) +} // namespace CPU_CAPABILITY + +REGISTER_DISPATCH(special_scaled_modified_bessel_k0_stub, &CPU_CAPABILITY::scaled_modified_bessel_k0_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/scaled_modified_bessel_k1.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/scaled_modified_bessel_k1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92a278b8553a64c4ee0f407ccadb9f728b347d93 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/scaled_modified_bessel_k1.cpp @@ -0,0 +1,24 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include + +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + static void scaled_modified_bessel_k1_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "scaled_modified_bessel_k1_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return scaled_modified_bessel_k1_forward(x); + }); + }); + } // scaled_modified_bessel_k1_kernel(TensorIteratorBase& iterator) +} // namespace CPU_CAPABILITY + +REGISTER_DISPATCH(special_scaled_modified_bessel_k1_stub, &CPU_CAPABILITY::scaled_modified_bessel_k1_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/spherical_bessel_j0.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/spherical_bessel_j0.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78c49df5bbd3b61658e82e99c7fa06b83fc9321e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/spherical_bessel_j0.cpp @@ -0,0 +1,24 @@ +#define TORCH_ASSERT_NO_OPERATORS + +#include + +#include +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + static void spherical_bessel_j0_kernel(TensorIteratorBase& iterator) { + TORCH_INTERNAL_ASSERT(iterator.ntensors() == 2); + + AT_DISPATCH_FLOATING_TYPES(iterator.common_dtype(), "spherical_bessel_j0_cpu", [&]() { + cpu_kernel(iterator, [](scalar_t x) { + return spherical_bessel_j0_forward(x); + }); + }); + } // spherical_bessel_j0_kernel(TensorIteratorBase& iterator) +} // namespace CPU_CAPABILITY + +REGISTER_DISPATCH(special_spherical_bessel_j0_stub, &CPU_CAPABILITY::spherical_bessel_j0_kernel) +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/utils.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..edf4e0db39d4d9312184a37d883e8efc604e2223 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/utils.h @@ -0,0 +1,220 @@ +#pragma once + +#include +#include +#include +#include + +#ifdef USE_FBGEMM +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi") +#include +C10_DIAGNOSTIC_POP() +#endif + +namespace at::native { + +template +inline void _store(T* dst, at::vec::Vectorized src) { + src.store(dst); +} + +inline void _store(at::BFloat16* dst, at::vec::Vectorized src) { + auto res = at::vec::convert_float_bfloat16(src, src); + res.store(dst, at::vec::Vectorized::size()); +} + +inline void _store(at::Half* dst, at::vec::Vectorized src) { + auto res = at::vec::convert_float_half(src, src); + res.store(dst, at::vec::Vectorized::size()); +} + +inline namespace CPU_CAPABILITY { + +template +inline T data_index_init(T offset) { + return offset; +} + +template +inline T data_index_init(T offset, T& x, const T& X, Args&&... args) { + offset = data_index_init(offset, std::forward(args)...); + x = offset % X; + return offset / X; +} + +inline bool data_index_step() { + return true; +} + +template +inline bool data_index_step(T& x, const T& X, Args&&... args) { + if (data_index_step(std::forward(args)...)) { + x = ((x + 1) == X) ? 0 : (x + 1); + return x == 0; + } + return false; +} + +// Helper struct for bfloat16/float16 vectorization +// Useful when you need float as immediate dtype or accumulate dtype +using namespace vec; +struct Vec2 { + Vectorized val0, val1; + Vec2(Vectorized v0, Vectorized v1) : val0(v0), val1(v1) {} + Vec2(float v) : val0(v), val1(v) {} + static Vec2 loadu(const BFloat16* ptr) { + auto [v0, v1] = convert_bfloat16_float(Vectorized::loadu(ptr)); + return {v0, v1}; + } + static Vec2 loadu(const Half* ptr) { + auto [v0, v1] = convert_half_float(Vectorized::loadu(ptr)); + return {v0, v1}; + } + static Vec2 loadu(const float* ptr) { + return {Vectorized::loadu(ptr), Vectorized::loadu(ptr + Vectorized::size())}; + } + void store(BFloat16* ptr) const { + Vectorized val = convert_float_bfloat16(val0, val1); + val.store(ptr); + } + void store(Half* ptr) const { + Vectorized val = convert_float_half(val0, val1); + val.store(ptr); + } + void store(float* ptr) const { + val0.store(ptr); + val1.store(ptr + Vectorized::size()); + } +}; +inline Vec2 operator+(const Vec2& a, const Vec2& b) { return {a.val0 + b.val0, a.val1 + b.val1}; } +inline Vec2 operator*(const Vec2& a, const Vec2& b) { return {a.val0 * b.val0, a.val1 * b.val1}; } +inline Vec2 operator-(const Vec2& a, const Vec2& b) { return {a.val0 - b.val0, a.val1 - b.val1}; } +inline Vec2 operator/(const Vec2& a, const Vec2& b) { return {a.val0 / b.val0, a.val1 / b.val1}; } +inline Vec2 maximum(const Vec2& a, const Vec2& b) { return {vec::maximum(a.val0, b.val0), vec::maximum(a.val1, b.val1)}; } +inline Vec2 minimum(const Vec2& a, const Vec2& b) { return {vec::minimum(a.val0, b.val0), vec::minimum(a.val1, b.val1)}; } + +template struct VectorizedType { using type = Vectorized; }; +template <> struct VectorizedType { using type = Vec2; }; +template <> struct VectorizedType { using type = Vec2; }; +template using VecType = typename VectorizedType::type; + +// Helper for mixed data type parameter Vec::load +inline std::tuple, Vectorized> load2f(const BFloat16* ptr) { + return convert_bfloat16_float(Vectorized::loadu(ptr)); +} + +inline std::tuple, Vectorized> load2f(const Half* ptr) { + return convert_half_float(Vectorized::loadu(ptr)); +} + +inline std::tuple, Vectorized> load2f(const float* ptr) { + using Vec = Vectorized; + return std::make_tuple(Vec::loadu(ptr), Vec::loadu(ptr + Vec::size())); +} + +inline std::tuple, Vectorized> load2f(const BFloat16* ptr, int64_t count) { + return convert_bfloat16_float(Vectorized::loadu(ptr, count)); +} + +inline std::tuple, Vectorized> load2f(const Half* ptr, int64_t count) { + return convert_half_float(Vectorized::loadu(ptr, count)); +} + +inline std::tuple, Vectorized> load2f(const float* ptr, int64_t count) { + using Vec = Vectorized; + if (count > Vec::size()) { + return std::make_tuple(Vec::loadu(ptr), Vec::loadu(ptr + Vec::size(), count - Vec::size())); + } else { + return std::make_tuple(Vec::loadu(ptr, count), Vec(0)); + } +} + +} // namespace + +namespace utils { + +template +T CeilLog2(const T& x) { + if (x <= 2) { + return 1; + } + // Last set bit is floor(log2(x)), floor + 1 is ceil + // except when x is an exact powers of 2, so subtract 1 first + return static_cast(llvm::findLastSet(static_cast(x) - 1)) + 1; +} + +// matrix transpose: +// src has shape of M by N, with leading dimension of ld_src +// dst has shape of N by M, with leading dimension of ld_dst +template +inline void transpose(int64_t M, int64_t N, const T* src, int64_t ld_src, T* dst, int64_t ld_dst) { + for (int64_t j = 0; j < N; j++) { + for (int64_t i = 0; i < M; i++) { + dst[j * ld_dst + i] = c10::load(&(src[i * ld_src + j])); + } + } +} + +#ifdef USE_FBGEMM +template <> +inline void transpose(int64_t M, int64_t N, const float* src, int64_t ld_src, float* dst, int64_t ld_dst) { + TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM."); + fbgemm::transpose_simd(M, N, src, ld_src, dst, ld_dst); +} + +template <> +inline void transpose(int64_t M, int64_t N, const uint16_t* src, int64_t ld_src, uint16_t* dst, int64_t ld_dst) { + TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM."); + fbgemm::transpose_simd(M, N, src, ld_src, dst, ld_dst); +} + +template <> +inline void transpose(int64_t M, int64_t N, const uint8_t* src, int64_t ld_src, uint8_t* dst, int64_t ld_dst) { + TORCH_CHECK(fbgemm::fbgemmSupportedCPU(), "Your CPU does not support FBGEMM."); + fbgemm::transpose_simd(M, N, src, ld_src, dst, ld_dst); +} +#endif + +template +inline void parallel_sparse_csr( + const TensorAccessor& crow_acc, + const int64_t M, + const int64_t nnz, + const F& f) { + TORCH_CHECK(crow_acc.size(0) == M + 1); + + // directly parallel on `M` may lead to load imbalance, + // statically determine thread partition here to average payload + // for each thread. + int num_threads = at::get_num_threads(); + std::vector thread_splits(num_threads + 1, M); + + int64_t thread_averge_payload = std::max((int64_t)1, divup(nnz, num_threads)); + + thread_splits[0] = 0; + int64_t sum = 0; + int64_t t = 1; + for (const auto m : c10::irange(M)) { + int64_t row_start = crow_acc[m]; + int64_t row_end = crow_acc[m + 1]; + sum += row_end - row_start; + if (sum > t * thread_averge_payload) { + thread_splits[t] = m; + t++; + } + } + // need to restore the last index, + // due to rounding error when calculating `thread_averge_payload`. + thread_splits[num_threads] = M; + + at::parallel_for(0, num_threads, 1, [&](int64_t cbegin, int64_t cend) { + int tid = at::get_thread_num(); + int64_t begin = thread_splits[tid]; + int64_t end = thread_splits[tid + 1]; + f(begin, end); + }); +} + +} // namespace utils + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cpu/zmath.h b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/zmath.h new file mode 100644 index 0000000000000000000000000000000000000000..3ebef428705350d4dffe37b612b0f368ea87cb78 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cpu/zmath.h @@ -0,0 +1,250 @@ +#pragma once + +// Complex number math operations that act as no-ops for other dtypes. +#include +#include +#include + +namespace at::native { +inline namespace CPU_CAPABILITY { + +template +inline VALUE_TYPE zabs (SCALAR_TYPE z) { + return z; +} + +template<> +inline c10::complex zabs > (c10::complex z) { + return c10::complex(std::abs(z)); +} + +template<> +inline float zabs , float> (c10::complex z) { + return std::abs(z); +} + +template<> +inline c10::complex zabs > (c10::complex z) { + return c10::complex(std::abs(z)); +} + +template<> +inline double zabs , double> (c10::complex z) { + return std::abs(z); +} + +// This overload corresponds to non-complex dtypes. +// The function is consistent with its NumPy equivalent +// for non-complex dtypes where `pi` is returned for +// negative real numbers and `0` is returned for 0 or positive +// real numbers. +// Note: `nan` is propagated. +template +inline VALUE_TYPE angle_impl (SCALAR_TYPE z) { + if (at::_isnan(z)) { + return z; + } + return z < 0 ? c10::pi : 0; +} + +template<> +inline c10::complex angle_impl > (c10::complex z) { + return c10::complex(std::arg(z), 0.0); +} + +template<> +inline float angle_impl , float> (c10::complex z) { + return std::arg(z); +} + +template<> +inline c10::complex angle_impl > (c10::complex z) { + return c10::complex(std::arg(z), 0.0); +} + +template<> +inline double angle_impl , double> (c10::complex z) { + return std::arg(z); +} + +template +constexpr VALUE_TYPE real_impl (SCALAR_TYPE z) { + return z; //No-Op +} + +template<> +constexpr c10::complex real_impl > (c10::complex z) { + return c10::complex(z.real(), 0.0); +} + +template<> +constexpr float real_impl , float> (c10::complex z) { + return z.real(); +} + +template<> +constexpr c10::complex real_impl > (c10::complex z) { + return c10::complex(z.real(), 0.0); +} + +template<> +constexpr double real_impl , double> (c10::complex z) { + return z.real(); +} + +template +constexpr VALUE_TYPE imag_impl (SCALAR_TYPE /*z*/) { + return 0; +} + +template<> +constexpr c10::complex imag_impl > (c10::complex z) { + return c10::complex(z.imag(), 0.0); +} + +template<> +constexpr float imag_impl , float> (c10::complex z) { + return z.imag(); +} + +template<> +constexpr c10::complex imag_impl > (c10::complex z) { + return c10::complex(z.imag(), 0.0); +} + +template<> +constexpr double imag_impl , double> (c10::complex z) { + return z.imag(); +} + +template +inline TYPE conj_impl (TYPE z) { + return z; //No-Op +} + +template<> +inline c10::complex conj_impl > (c10::complex z) { + return c10::complex{z.real(), -z.imag()}; +} + +template<> +inline c10::complex conj_impl > (c10::complex z) { + return c10::complex(z.real(), -z.imag()); +} + +template<> +inline c10::complex conj_impl > (c10::complex z) { + return c10::complex(z.real(), -z.imag()); +} + +template +inline TYPE ceil_impl (TYPE z) { + return std::ceil(z); +} + +template <> +inline c10::complex ceil_impl (c10::complex z) { + return c10::complex(std::ceil(z.real()), std::ceil(z.imag())); +} + +template <> +inline c10::complex ceil_impl (c10::complex z) { + return c10::complex(std::ceil(z.real()), std::ceil(z.imag())); +} + +template +inline c10::complex sgn_impl (c10::complex z) { + if (z == c10::complex(0, 0)) { + return c10::complex(0, 0); + } else { + return z / zabs(z); + } +} + +template +inline TYPE floor_impl (TYPE z) { + return std::floor(z); +} + +template <> +inline c10::complex floor_impl (c10::complex z) { + return c10::complex(std::floor(z.real()), std::floor(z.imag())); +} + +template <> +inline c10::complex floor_impl (c10::complex z) { + return c10::complex(std::floor(z.real()), std::floor(z.imag())); +} + +template +inline TYPE round_impl (TYPE z) { + return std::nearbyint(z); +} + +template <> +inline c10::complex round_impl (c10::complex z) { + return c10::complex(std::nearbyint(z.real()), std::nearbyint(z.imag())); +} + +template <> +inline c10::complex round_impl (c10::complex z) { + return c10::complex(std::nearbyint(z.real()), std::nearbyint(z.imag())); +} + +template +inline TYPE trunc_impl (TYPE z) { + return std::trunc(z); +} + +template <> +inline c10::complex trunc_impl (c10::complex z) { + return c10::complex(std::trunc(z.real()), std::trunc(z.imag())); +} + +template <> +inline c10::complex trunc_impl (c10::complex z) { + return c10::complex(std::trunc(z.real()), std::trunc(z.imag())); +} + +template ::value, int> = 0> +inline TYPE max_impl (TYPE a, TYPE b) { + if (_isnan(a) || _isnan(b)) { + return std::numeric_limits::quiet_NaN(); + } else { + return std::max(a, b); + } +} + +template ::value, int> = 0> +inline TYPE max_impl (TYPE a, TYPE b) { + if (_isnan(a)) { + return a; + } else if (_isnan(b)) { + return b; + } else { + return std::abs(a) > std::abs(b) ? a : b; + } +} + +template ::value, int> = 0> +inline TYPE min_impl (TYPE a, TYPE b) { + if (_isnan(a) || _isnan(b)) { + return std::numeric_limits::quiet_NaN(); + } else { + return std::min(a, b); + } +} + +template ::value, int> = 0> +inline TYPE min_impl (TYPE a, TYPE b) { + if (_isnan(a)) { + return a; + } else if (_isnan(b)) { + return b; + } else { + return std::abs(a) < std::abs(b) ? a : b; + } +} + +} // end namespace +} //end at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AbsKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AbsKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..3469b1c2246e7f729d8cf619776b403579da8f17 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AbsKernel.cu @@ -0,0 +1,51 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include + +namespace at::native { + +template +struct AbsFunctor { + __device__ __forceinline__ scalar_t operator() (const scalar_t a) const { + return std::abs(a); + } +}; + +constexpr char abs_name[] = "abs_kernel"; +void abs_kernel_cuda(TensorIteratorBase& iter) { + auto dtype = iter.dtype(); + if (at::isComplexType(dtype)) { +#if AT_USE_JITERATOR() + static const auto abs_string = jiterator_stringify( + template T abs_kernel(T x) { return std::abs(x); }); + AT_DISPATCH_COMPLEX_TYPES_AND(kComplexHalf, dtype, "abs_cuda", [&]() { + jitted_gpu_kernel< + /*name=*/abs_name, + /*return_dtype=*/scalar_t, + /*common_dtype=*/scalar_t, + /*arity=*/1>(iter, abs_string); + }); +#else + AT_DISPATCH_COMPLEX_TYPES_AND(kComplexHalf, dtype, "abs_cuda", [&]() { + using opmath_t = at::opmath_type; + gpu_kernel(iter, AbsFunctor()); + }); +#endif + } else { + AT_DISPATCH_ALL_TYPES_AND3( + ScalarType::Half, + ScalarType::BFloat16, + ScalarType::Bool, + iter.dtype(), + "abs_cuda", + [&]() { gpu_kernel(iter, AbsFunctor()); }); + } +} + + REGISTER_DISPATCH(abs_stub, &abs_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Activation.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Activation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca89b5b35b75f0ab718b454cd7231198673b0f0e --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Activation.cpp @@ -0,0 +1,108 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +// ----------------------------------- +// glu backward +// ----------------------------------- + +Tensor& glu_backward_cuda_out(const Tensor& grad_output, const Tensor& input, + int64_t dim, Tensor& grad_input) { + TORCH_CHECK(input.dim() > 0, "glu does not support 0-dimensional tensors"); + auto wrap_dim = maybe_wrap_dim(dim, input.dim()); + auto input_sizes = input.sizes(); + const int64_t nIn = input_sizes[wrap_dim]; + TORCH_CHECK(nIn % 2 == 0, "Halving dimension must be even, but dimension ", + wrap_dim, " is size ", nIn); + + resize_output(grad_input, input_sizes); + + DimVector iter_shape(input_sizes); + const auto dim_size = nIn / 2; + iter_shape[wrap_dim] = dim_size; + TORCH_CHECK(grad_output.sizes() == IntArrayRef{iter_shape}); + + const auto iter = at::TensorIteratorConfig() + .add_output(grad_input) + .add_const_input(input) + .add_const_input(grad_output) + .resize_outputs(false) + .declare_static_shape(iter_shape) + .build(); + + if (iter.numel() == 0) { + return grad_input; + } + + const auto I_stride = input.strides()[wrap_dim] * dim_size; + const auto gI_stride = grad_input.strides()[wrap_dim] * dim_size; + + if (iter.can_use_32bit_indexing()) { + launch_glu_backward_kernel(iter, gI_stride, I_stride); + } else { + for (const auto& sub_iter: iter.with_32bit_indexing()) { + launch_glu_backward_kernel(sub_iter, gI_stride, I_stride); + } + } + return grad_input; +} + +Tensor glu_backward_cuda(const Tensor& grad_output, const Tensor& input, int64_t dim) { + auto grad_input = at::empty({0}, input.options()); + return glu_backward_cuda_out(grad_output, input, dim, grad_input); +} + +// ----------------------------------- +// log_sigmoid forward +// ----------------------------------- + +std::tuple log_sigmoid_forward_out_cuda(const Tensor& input, Tensor& result, Tensor& buffer) { + // NOTE: buffer is only used by CPU dispatch, we just ignore it here + auto iter = TensorIteratorConfig() + .add_output(result) + .add_const_input(input) + .build(); + launch_log_sigmoid_forward_kernel(iter); + return std::forward_as_tuple(result, buffer); +} + +std::tuple log_sigmoid_forward_cuda(const Tensor& input) { + auto result = at::empty_like(input); + auto buffer = at::empty({0}, input.options()); + log_sigmoid_forward_out_cuda(input, result, buffer); + return std::forward_as_tuple(result, buffer); +} + +TORCH_IMPL_FUNC(gelu_out_cuda) ( + const Tensor& /*self*/, std::string_view approximate, const Tensor& /*result*/ +) { + GeluCUDAKernelImpl(*this, get_gelutype_enum(approximate)); +} + +TORCH_IMPL_FUNC(gelu_backward_out_cuda) ( + const Tensor& /*grad*/, const Tensor& /*self*/, std::string_view approximate, const Tensor& /*grad_input*/ +) { + GeluBackwardCUDAKernelImpl(*this, get_gelutype_enum(approximate)); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Activation.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Activation.h new file mode 100644 index 0000000000000000000000000000000000000000..9823bae18f8be70120a442e26fd85165b80b5acc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Activation.h @@ -0,0 +1,20 @@ +#pragma once +#include +#include + +namespace at { +struct TensorIteratorBase; +class TensorBase; +} + +namespace at::native { + +void launch_glu_backward_kernel(const TensorIteratorBase& iter, + int64_t gI_stride, int64_t I_stride); + +void launch_log_sigmoid_forward_kernel(TensorIteratorBase& iter); + +void GeluCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate); +void GeluBackwardCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationEluKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationEluKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..a2b7505aa374cb02c4eb6fe992908072adb3efc7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationEluKernel.cu @@ -0,0 +1,86 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void elu_kernel( + TensorIteratorBase& iter, + const Scalar& alpha, + const Scalar& scale, + const Scalar& input_scale) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "elu_cuda", + [&]() { + using opmath_t = at::opmath_type; + auto negcoef = alpha.to() * scale.to(); + auto poscoef = scale.to(); + auto negiptcoef = input_scale.to(); + gpu_kernel( + iter, + [negcoef, poscoef, negiptcoef] GPU_LAMBDA(scalar_t a) -> scalar_t { + opmath_t aop = static_cast(a); + return aop > 0 ? aop * poscoef + : std::expm1(aop * negiptcoef) * negcoef; + }); + }); +} + +void elu_backward_kernel( + TensorIteratorBase& iter, + const Scalar& alpha, + const Scalar& scale, + const Scalar& input_scale, + bool is_result) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "elu_backward_cuda", + [&]() { + using opmath_t = at::opmath_type; + auto negcoef = alpha.to() * scale.to(); + auto poscoef = scale.to(); + auto negiptcoef = input_scale.to(); + gpu_kernel( + iter, + [negcoef, poscoef, negiptcoef, is_result] GPU_LAMBDA( + scalar_t a, scalar_t b) -> scalar_t { + opmath_t aop = static_cast(a); + opmath_t bop = static_cast(b); + + if (is_result) { + return bop <= 0 ? aop * negiptcoef * (bop + negcoef) + : aop * poscoef; + } else { + return bop <= 0 + ? aop * negiptcoef * negcoef * std::exp(bop * negiptcoef) + : aop * poscoef; + } + }); + }); +} +} // namespace + +REGISTER_DISPATCH(elu_stub, &elu_kernel) +REGISTER_DISPATCH(elu_backward_stub, &elu_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationGeluKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationGeluKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..c52d8ab18e25495c93795eb12074a979c36539c5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationGeluKernel.cu @@ -0,0 +1,88 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +void GeluCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate) { + if (approximate == GeluType::Tanh) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, it.dtype(), "GeluCUDAKernelImpl", [&]() { + gpu_kernel(it, [] GPU_LAMBDA(scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + constexpr opmath_t kBeta = M_SQRT2 * M_2_SQRTPI * opmath_t(0.5); + constexpr opmath_t kKappa = 0.044715; + auto x_cube = static_cast(x) * static_cast(x) * static_cast(x); + auto inner = kBeta * (static_cast(x) + kKappa * x_cube); + return opmath_t(0.5) * static_cast(x) * (opmath_t(1) + c10::cuda::compat::tanh(inner)); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, it.dtype(), "GeluCUDAKernelImpl", [&]() { + gpu_kernel(it, [] GPU_LAMBDA(scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + constexpr opmath_t kAlpha = M_SQRT1_2; + return static_cast(x) * opmath_t(0.5) * (opmath_t(1) + ::erf(static_cast(x) * kAlpha)); + }); + }); + } +} + +void GeluBackwardCUDAKernelImpl(TensorIteratorBase& it, GeluType approximate) { + if (approximate == GeluType::Tanh) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, + it.dtype(), "GeluBackwardCUDAKernelImpl", [&]() { + gpu_kernel(it, [] GPU_LAMBDA(scalar_t dy, scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + constexpr opmath_t kBeta = M_SQRT2 * M_2_SQRTPI * opmath_t(0.5); + constexpr opmath_t kKappa = 0.044715; + auto x_sq = static_cast(x) * static_cast(x); + auto x_cube = x_sq * static_cast(x); + auto inner = kBeta * (static_cast(x) + kKappa * x_cube); + auto tanh_inner = c10::cuda::compat::tanh(inner); + + auto left = opmath_t(0.5) * static_cast(x); + auto right = opmath_t(1) + tanh_inner; + + auto left_derivative = opmath_t(0.5) * right; + + auto tanh_derivative = opmath_t(1) - tanh_inner * tanh_inner; + auto inner_derivative = kBeta * (opmath_t(1) + opmath_t(3) * kKappa * x_sq); + auto right_derivative = left * tanh_derivative * inner_derivative; + + return static_cast(dy) * (left_derivative + right_derivative); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, + it.dtype(), "GeluBackwardCUDAKernelImpl", [&]() { + gpu_kernel(it, [] GPU_LAMBDA(scalar_t dy, scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + constexpr opmath_t kBeta = M_2_SQRTPI * M_SQRT1_2 * opmath_t(0.5); + constexpr opmath_t kAlpha = M_SQRT1_2; + const opmath_t cdf = + opmath_t(0.5) * (opmath_t(1) + ::erf(static_cast(x) * kAlpha)); + const opmath_t pdf = + c10::cuda::compat::exp( + opmath_t(-0.5) * static_cast(x) * static_cast(x)) * + kBeta; + return static_cast(dy) * (cdf + static_cast(x) * pdf); + }); + }); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationGluKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationGluKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..a601d95f4a9089bd94cffa39cef67ad99ebcae04 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationGluKernel.cu @@ -0,0 +1,141 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +// ----------------------------------- +// glu forward +// ----------------------------------- +void glu_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.dtype(), "glu_cuda", [&]() { + using opmath_t = at::opmath_type; + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t a_, scalar_t b_) -> scalar_t { + const opmath_t a = a_; + const opmath_t b = b_; + const opmath_t one = opmath_t(1); + const opmath_t sigmoid = one / (one + std::exp(-b)); + return a * sigmoid; + }); + }); +} + +// ----------------------------------- +// glu forward ad +// ----------------------------------- +void glu_jvp_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.dtype(), "glu_cuda", [&]() { + using opmath_t = at::opmath_type; + gpu_kernel( + iter, + [] GPU_LAMBDA( + scalar_t res_, scalar_t b_, scalar_t da_, scalar_t db_) + -> scalar_t { + const opmath_t res = res_; + const opmath_t b = b_; + const opmath_t da = da_; + const opmath_t db = db_; + const opmath_t one = opmath_t(1); + + const opmath_t sig_b = one / (one + std::exp(-b)); + return (da * sig_b + res * (db - sig_b * db)); + }); + }); +} + +// ----------------------------------- +// glu backward +// ----------------------------------- + +// Byte offsets don't require multiplication by sizeof(T), so are slightly +// cheaper. For fixed offsets, this removes all penalty from 64-bit indexing. +template +__device__ T* byte_offset(T* ptr, int64_t offset) { + using byte_ptr_t = typename std:: + conditional_t, const char*, char*>; + return reinterpret_cast(reinterpret_cast(ptr) + offset); +} + +template +__global__ void glu_backward_kernel( + int numel, + scalar_t* gI, + const scalar_t* I, + const scalar_t* gO, + OffsetCalc offset_calculator, + int64_t gI_byte_offset, + int64_t I_byte_offset) { + using opmath_t = at::opmath_type; + + const uint32_t linear_index = blockIdx.x * blockDim.x + threadIdx.x; + if (linear_index >= numel) { + return; + } + const auto offsets = offset_calculator.get(linear_index); + + // We explicitly iterate over the first half of the input tensor, and + // gI_byte_offset and I_byte_offset are the offsets to access the + // corresponding index in the second half of the tensor. + const opmath_t a = I[offsets[1]]; + const opmath_t b = *byte_offset(I + offsets[1], I_byte_offset); + const opmath_t gO_val = gO[offsets[2]]; + + const auto one = opmath_t(1); + const opmath_t sigmoid = one / (one + std::exp(-b)); + + auto* gA = gI + offsets[0]; + *gA = sigmoid * gO_val; + + auto* gB = byte_offset(gA, gI_byte_offset); + *gB = (one - sigmoid) * sigmoid * gO_val * a; +} + +void launch_glu_backward_kernel( + const TensorIteratorBase& iter, + int64_t gI_stride, + int64_t I_stride) { + const auto N = iter.numel(); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY( + N > 0 && N <= std::numeric_limits::max()); + const auto offset_calculator = make_element_offset_calculator<3>(iter); + constexpr int64_t block_size = 256; + const int64_t grid = (N + block_size - 1) / block_size; + const auto stream = at::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.common_dtype(), "glu_backward_cuda", [&] { + auto gI = static_cast(iter.data_ptr(0)); + auto I = static_cast(iter.data_ptr(1)); + auto gO = static_cast(iter.data_ptr(2)); + glu_backward_kernel<<>>( + N, + gI, + I, + gO, + offset_calculator, + gI_stride * sizeof(scalar_t), + I_stride * sizeof(scalar_t)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); +} + +REGISTER_DISPATCH(glu_stub, &glu_kernel) +REGISTER_DISPATCH(glu_jvp_stub, &glu_jvp_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardshrinkKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardshrinkKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..883875983c0bb7e1be2ac476a9671194b82bbd04 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardshrinkKernel.cu @@ -0,0 +1,39 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void hardshrink_kernel(TensorIteratorBase& iter, const Scalar& value) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "hardshrink_cuda", + [&]() { + auto lambd = value.to(); + gpu_kernel(iter, [lambd] GPU_LAMBDA(scalar_t a) -> scalar_t { + return (a >= -lambd && a <= lambd) ? scalar_t(0) : a; + }); + }); +} +} // namespace + +REGISTER_DISPATCH(hardshrink_stub, &hardshrink_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardsigmoidKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardsigmoidKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..02ac7bfc03c42735bdd997fbb8b24042fab8fe7c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardsigmoidKernel.cu @@ -0,0 +1,74 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void hardsigmoid_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "hardsigmoid_cuda", + [&]() { + using opmath_t = at::opmath_type; + const opmath_t zero(0.0f); + const opmath_t one_sixth(1.0f / 6.0f); + const opmath_t three(3.0f); + const opmath_t six(6.0f); + gpu_kernel( + iter, + [zero, one_sixth, three, six] GPU_LAMBDA( + scalar_t self_val) -> scalar_t { + opmath_t x = static_cast(self_val); + return std::min(std::max(x + three, zero), six) * one_sixth; + }); + }); +} + +void hardsigmoid_backward_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "hardsigmoid_backward_cuda", + [&]() { + using opmath_t = at::opmath_type; + const opmath_t zero(0.0f); + const opmath_t three(3.0f); + const opmath_t neg_three(-3.0f); + const opmath_t one_sixth(1.0f / 6.0f); + gpu_kernel( + iter, + [zero, three, neg_three, one_sixth] GPU_LAMBDA( + scalar_t grad_val_, scalar_t self_val_) -> scalar_t { + opmath_t grad_val = static_cast(grad_val_); + opmath_t self_val = static_cast(self_val_); + return (self_val > neg_three && self_val < three) + ? grad_val * one_sixth + : zero; + }); + }); +} + +} // namespace + +REGISTER_DISPATCH(hardsigmoid_stub, &hardsigmoid_kernel) +REGISTER_DISPATCH(hardsigmoid_backward_stub, &hardsigmoid_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardswishKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardswishKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..3a936bb36150a1e8cb14aec1578bdb3c207a1506 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardswishKernel.cu @@ -0,0 +1,63 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void hardswish_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "hardswish_cuda", [&]() { + using opmath_t = at::opmath_type; + const opmath_t zero(0.0f); + const opmath_t one_sixth(1.0f / 6.0f); + const opmath_t three(3.0f); + const opmath_t six(6.0f); + gpu_kernel(iter, [zero, one_sixth, three, six]GPU_LAMBDA(scalar_t self_val) -> scalar_t { + opmath_t x = static_cast(self_val); + return x * std::min(std::max(x + three, zero), six) * one_sixth; + }); + }); +} + +void hardswish_backward_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "hardswish_backward_cuda", [&]() { + using opmath_t = at::opmath_type; + const opmath_t zero(0.0f); + const opmath_t three(3.0f); + const opmath_t neg_three(-3.0f); + const opmath_t one_half(0.5f); + gpu_kernel( + iter, + [zero, three, neg_three, one_half]GPU_LAMBDA(scalar_t grad_val_, scalar_t self_val_) -> scalar_t { + opmath_t grad_val = static_cast(grad_val_); + opmath_t self_val = static_cast(self_val_); + if (self_val <= neg_three) { + return zero; + } else if (self_val < three) { + return grad_val * ((self_val / three) + one_half); + } else { + return grad_val; + } + }); + }); +} +} // namespace + +REGISTER_DISPATCH(hardswish_stub, &hardswish_kernel) +REGISTER_DISPATCH(hardswish_backward_stub, &hardswish_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardtanhKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardtanhKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..48c9f20a75c00285d8184a0a3b69b3fd4e0dacfe --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationHardtanhKernel.cu @@ -0,0 +1,45 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void hardtanh_backward_kernel( + TensorIterator& iter, + const Scalar& min, + const Scalar& max) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, at::ScalarType::BFloat16, + iter.dtype(), "hardtanh_backward_cuda", [&]() { + using opmath_t = at::opmath_type; + auto min_val = min.to(); + auto max_val = max.to(); + gpu_kernel( + iter, + [min_val, max_val] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + opmath_t aop = static_cast(a); + opmath_t bop = static_cast(b); + return (bop <= min_val) || (bop >= max_val) ? opmath_t(0) : aop; + }); + }); +} +} // namespace + +REGISTER_DISPATCH(hardtanh_backward_stub, &hardtanh_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationLeakyReluKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationLeakyReluKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..fc752a56d148e6e01b73fc322f88a7cdcb6d386d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationLeakyReluKernel.cu @@ -0,0 +1,62 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void leaky_relu_kernel(TensorIteratorBase& iter, const Scalar& negval_) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "leaky_relu_cuda", + [&]() { + using opmath_t = at::opmath_type; + auto negval = negval_.to(); + gpu_kernel(iter, [negval] GPU_LAMBDA(scalar_t a) -> scalar_t { + opmath_t aop = static_cast(a); + return aop > opmath_t(0) ? aop : aop * negval; + }); + }); +} + +void leaky_relu_backward_kernel( + TensorIteratorBase& iter, + const Scalar& negval_) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "leaky_relu_backward_cuda", + [&]() { + using opmath_t = at::opmath_type; + auto negval = negval_.to(); + gpu_kernel( + iter, [negval] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + opmath_t aop = static_cast(a); + opmath_t bop = static_cast(b); + return aop > opmath_t(0) ? bop : bop * negval; + }); + }); +} +} // namespace + +REGISTER_DISPATCH(leaky_relu_stub, &leaky_relu_kernel) +REGISTER_DISPATCH(leaky_relu_backward_stub, &leaky_relu_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationLogSigmoidKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationLogSigmoidKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..d4a98b59bb974cb0961afc05ac8896bd9ee00e70 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationLogSigmoidKernel.cu @@ -0,0 +1,64 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +// ----------------------------------- +// log_sigmoid forward +// ----------------------------------- + +void launch_log_sigmoid_forward_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.common_dtype(), "log_sigmoid_forward_cuda", [&] { + using opmath_t = at::opmath_type; + + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t in_) -> scalar_t { + const opmath_t in = in_; + const auto min = std::min(opmath_t(0), in); + const auto z = std::exp(-std::abs(in)); + return min - std::log1p(z); + }); + }); +} + +namespace { +// ----------------------------------- +// log_sigmoid backward +// ----------------------------------- +void log_sigmoid_backward_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, iter.common_dtype(), "log_sigmoid_backward_cuda", [&] { + using opmath_t = at::opmath_type; + gpu_kernel( + iter, [] GPU_LAMBDA(scalar_t in_, scalar_t grad_out_) -> scalar_t { + const opmath_t in = in_; + const opmath_t grad_out = grad_out_; + + auto in_negative = in < opmath_t(0); + auto max_deriv = in_negative ? opmath_t(1) : opmath_t(0); + auto sign = in_negative ? opmath_t(1) : -opmath_t(1); + const auto z = std::exp(-std::abs(in)); + return grad_out * (max_deriv - sign * (z / (opmath_t(1) + z))); + }); + }); +} +} // namespace + +REGISTER_DISPATCH(log_sigmoid_backward_stub, &log_sigmoid_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationMishKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationMishKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..447ca9e1fc96af83bab204945a6491360f03e4dd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationMishKernel.cu @@ -0,0 +1,64 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void mish_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "mish_cuda", + [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + const opmath_t x_acc = static_cast(x); + return x_acc * + c10::cuda::compat::tanh( + c10::cuda::compat::log1p(c10::cuda::compat::exp(x_acc))); + }); + }); +} + +void mish_backward_kernel(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "mish_backward_cuda", + [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t dy, scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + const opmath_t dy_acc = static_cast(dy); + const opmath_t x_acc = static_cast(x); + const opmath_t s_acc = + opmath_t(1) / (opmath_t(1) + c10::cuda::compat::exp(-x_acc)); + const opmath_t t_acc = c10::cuda::compat::tanh( + c10::cuda::compat::log1p(c10::cuda::compat::exp(x_acc))); + return dy_acc * + (t_acc + x_acc * s_acc * (opmath_t(1) - t_acc * t_acc)); + }); + }); +} +} // namespace + +REGISTER_DISPATCH(mish_stub, &mish_kernel) +REGISTER_DISPATCH(mish_backward_stub, &mish_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationPreluKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationPreluKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..2032e31ad5baa91c591743a74436c7f016da9949 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationPreluKernel.cu @@ -0,0 +1,48 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +// ----------------------------------- +// prelu +// ----------------------------------- +void prelu_kernel(TensorIterator &iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "prelu_cuda", [&] { + gpu_kernel(iter, + [] GPU_LAMBDA (scalar_t input, scalar_t weight) -> scalar_t { + return (input > 0) ? input : weight * input; + }); + }); +} + +void prelu_backward_kernel(TensorIterator &iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "prelu_backward_cuda", [&] { + gpu_kernel_multiple_outputs(iter, + [] GPU_LAMBDA (scalar_t input, scalar_t weight, scalar_t grad) -> thrust::tuple { + auto mask = input > 0; + auto grad_input = mask ? grad : weight * grad; + auto grad_weight = mask ? scalar_t{0} : input * grad; + return {grad_input, grad_weight}; + }); + }); +} + +REGISTER_DISPATCH(prelu_stub, &prelu_kernel) +REGISTER_DISPATCH(prelu_backward_stub, &prelu_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSiluKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSiluKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..9ccdb4d0589275dbe120535af4199276c3a08d9c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSiluKernel.cu @@ -0,0 +1,60 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void silu_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "silu_cuda", + [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + const opmath_t x_acc = static_cast(x); + return x_acc / (opmath_t(1) + ::exp(-x_acc)); + }); + }); +} + +void silu_backward_kernel(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "silu_backward_cuda", + [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t dy, scalar_t x) -> scalar_t { + using opmath_t = at::opmath_type; + const opmath_t dy_acc = static_cast(dy); + const opmath_t x_acc = static_cast(x); + const opmath_t s_acc = + opmath_t(1) / (opmath_t(1) + c10::cuda::compat::exp(-x_acc)); + return dy_acc * s_acc * (opmath_t(1) + x_acc * (opmath_t(1) - s_acc)); + }); + }); +} +} // namespace + +REGISTER_DISPATCH(silu_stub, &silu_kernel) +REGISTER_DISPATCH(silu_backward_stub, &silu_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSoftplusKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSoftplusKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..0977e0c682e9d2d6787b35df0be34804d0989b59 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSoftplusKernel.cu @@ -0,0 +1,74 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void softplus_kernel( + TensorIteratorBase& iter, + const Scalar& beta_, + const Scalar& threshold_) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "softplus_cuda", + [&]() { + using opmath_t = at::opmath_type; + auto beta = beta_.to(); + auto threshold = threshold_.to(); + gpu_kernel(iter, [beta, threshold] GPU_LAMBDA(scalar_t a) -> scalar_t { + opmath_t aop = static_cast(a); + return (aop * beta) > threshold + ? aop + : (::log1p(std::exp(aop * beta))) / beta; + }); + }); +} + +void softplus_backward_kernel( + TensorIteratorBase& iter, + const Scalar& beta_, + const Scalar& threshold_) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "softplus_backward_cuda", + [&]() { + using opmath_t = at::opmath_type; + auto beta = beta_.to(); + auto threshold = threshold_.to(); + gpu_kernel( + iter, + [beta, threshold] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + opmath_t aop = static_cast(a); + opmath_t bop = static_cast(b); + opmath_t z = std::exp(bop * beta); + return (bop * beta) > threshold ? aop + : aop * z / (z + opmath_t(1.)); + }); + }); +} + +} // namespace + +REGISTER_DISPATCH(softplus_stub, &softplus_kernel) +REGISTER_DISPATCH(softplus_backward_stub, &softplus_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSoftshrinkKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSoftshrinkKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..cc25569696c69356bfacb015579295b7c926f3d9 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationSoftshrinkKernel.cu @@ -0,0 +1,59 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +void softshrink_kernel(TensorIteratorBase& iter, const Scalar& value) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "softshrink_cuda", + [&]() { + auto lambd = value.to(); + gpu_kernel(iter, [lambd] GPU_LAMBDA(scalar_t a) -> scalar_t { + return at::_isnan(a) ? a : (a > lambd ? a - lambd : (a < -lambd ? a + lambd : scalar_t(0))); + }); + }); +} + +void shrink_backward_kernel(TensorIteratorBase& iter, const Scalar& value) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "shrink_backward_cuda", + [&]() { + auto lambd = value.to(); + gpu_kernel( + iter, + [lambd] GPU_LAMBDA( + scalar_t grad_val, scalar_t self_val) -> scalar_t { + return (self_val >= -lambd && self_val <= lambd) ? scalar_t(0) + : grad_val; + }); + }); +} +} // namespace + +REGISTER_DISPATCH(softshrink_stub, &softshrink_kernel) +REGISTER_DISPATCH(shrink_backward_stub, &shrink_backward_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationThresholdKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationThresholdKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..2d4b7fc3093987d67904424a64af4a0e639aa88d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ActivationThresholdKernel.cu @@ -0,0 +1,52 @@ +#define TORCH_ASSERT_NO_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { +namespace { + +template +void threshold_kernel_impl( + TensorIteratorBase& iter, + scalar_t threshold, + scalar_t value) { + gpu_kernel_with_scalars( + iter, [=] GPU_LAMBDA(scalar_t x, scalar_t other) -> scalar_t { + return x <= threshold ? value : other; + }); +} + +static void threshold_kernel_cuda( + TensorIteratorBase& iter, + const Scalar& threshold, + const Scalar& value) { + AT_DISPATCH_ALL_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "threshold_cuda", + [&] { + threshold_kernel_impl( + iter, threshold.to(), value.to()); + }); +} + +} // namespace + +REGISTER_DISPATCH(threshold_stub, &threshold_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveAveragePooling.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveAveragePooling.cu new file mode 100644 index 0000000000000000000000000000000000000000..a80b75c5e578920275fa1ef26163daa3cee2c515 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveAveragePooling.cu @@ -0,0 +1,824 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +#include + +#include +#include +#include + +#define START_IND(a,b,c) ((int64_t)((a / b) * c + ((a % b) * c) / b)) +#define END_IND(a,b,c) (1 + ((int64_t)(a + 1) * c - 1) / b) + +#define START_IND_INT(a,b,c) ((a * c) / b) +#define END_IND_INT(a,b,c) (((a + 1) * c + b - 1) / b) +// #define START_IND(a,b,c) a * c / b +// #define END_IND(a,b,c) (a + 1) * c / b + ((a + 1) * c % b > 0)?1:0 + +#define CUDA_MAX_THREADS 1024 // this is safe, in reality 256 is our limit +#define BLOCK_STRIDE 2 // increasing block_stride to lower # of blocks launched + +namespace at::native { + +namespace { + + // 4d tensor B x D x H x W + // All kernels view batch dim B and feature dim D as collapsed. + + /* + * Description: + * this function adaptively average pools an input 4D tensor along dimensions 2 and 3 + * 4D input, 4D output + */ + template + __global__ void adaptive_average_pool(const scalar_t *input, scalar_t *output, + int isizeH, int isizeW, + int osizeH, int osizeW, + int64_t istrideD, int64_t istrideH, int64_t istrideW) + { + using opmath_t = at::opmath_type; + // iterators on output pixels + int oh, ow; + + // select input/output plane based on thread/block ID + int o_plane = blockIdx.x; + int i_plane = o_plane; + + output = output + o_plane*osizeH*osizeW; + input = input + i_plane*istrideD; + + int ostartH = blockDim.y*blockIdx.y + threadIdx.y; + int oendH = osizeH; + const int ostepH = blockDim.y*gridDim.y; + + int ostartW = threadIdx.x; + int oendW = osizeW; + const int ostepW = blockDim.x; + + // For all output pixels... + for(oh = ostartH; oh < oendH; oh += ostepH) { + + int istartH = START_IND(oh, osizeH, isizeH); + int iendH = END_IND(oh, osizeH, isizeH); + int kH = iendH - istartH; + + for(ow = ostartW; ow < oendW; ow += ostepW) { + + int istartW = START_IND(ow, osizeW, isizeW); + int iendW = END_IND(ow, osizeW, isizeW); + int kW = iendW - istartW; + + // Compute the average pooling over corresponding input pixels + const scalar_t *ptr_input = input + istartH*istrideH + istartW*istrideW; + scalar_t *ptr_output = output + oh*osizeW + ow; + opmath_t sum = static_cast(0); + int ih, iw; + for(ih = 0; ih < kH; ++ih) { + for(iw = 0; iw < kW; ++iw) { + scalar_t val = ptr_input[iw*istrideW]; + sum += val; + } + ptr_input += istrideH; // next input line + } + // Update output + *ptr_output = sum / kH / kW; + } + } + } + + /* + * Description: + * this function computes the gradInput from gradOutput + */ + template + __global__ void adaptive_average_gradinput( + T *gradInput, const T *gradOutput, + int isizeH, int isizeW, int osizeH, int osizeW + ) + { + // iterators on input pixels + int ih, iw; + + // select input/output plane based on thread/block ID + int i_plane = blockIdx.x; + int o_plane = i_plane; + + gradOutput = gradOutput + o_plane*osizeH*osizeW; + gradInput = gradInput + i_plane*isizeH*isizeW; + + int istartH = blockDim.y*blockIdx.y + threadIdx.y; + int iendH = isizeH; + int istepH = blockDim.y*gridDim.y; + + int istartW = threadIdx.x; + int iendW = isizeW; + int istepW = blockDim.x; + + // compute gradInput + for(ih = istartH; ih < iendH; ih += istepH) { + + int ostartH = START_IND(ih, isizeH, osizeH); + int oendH = END_IND(ih, isizeH, osizeH); + + for(iw = istartW; iw < iendW; iw += istepW) { + + int ostartW = START_IND(iw, isizeW, osizeW); + int oendW = END_IND(iw, isizeW, osizeW); + + // Compute the gradients over corresponding output pixels + T *ptr_gradInput = gradInput + ih*isizeW + iw; + + int oh, ow; + for(oh = ostartH; oh < oendH; ++oh) { + int kH = START_IND(oh, osizeH, isizeH) - END_IND(oh, osizeH, isizeH); + for(ow = ostartW; ow < oendW; ++ow) { + int kW = START_IND(ow, osizeW, isizeW) - END_IND(ow, osizeW, isizeW); + T grad_delta = gradOutput[ow + oh*osizeW] / kH / kW; + *ptr_gradInput += grad_delta; + } + } + } + } + } + + /* + * Description: + * this function computes the gradInput from gradOutput + * (uses atomic add) + */ + template + __global__ void atomic_adaptive_average_gradinput( + T *gradInput, const T *gradOutput, + int isizeH, int isizeW, int osizeH, int osizeW + ) + { + // iterators on output indices + int oh, ow; + + // select input/output plane based on thread/block ID + int o_plane = blockIdx.x; + int i_plane = o_plane; + + gradOutput = gradOutput + o_plane*osizeW*osizeH; + gradInput = gradInput + i_plane*isizeW*isizeH; + + int ostartH = blockDim.y*blockIdx.y + threadIdx.y; + int oendH = osizeH; + int ostepH = blockDim.y*gridDim.y; + + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + // For all output pixels... + for(oh = ostartH; oh < oendH; oh += ostepH) { + + int istartH = START_IND(oh, osizeH, isizeH); + int iendH = END_IND(oh, osizeH, isizeH); + int kH = iendH - istartH; + + for(ow = ostartW; ow < oendW; ow += ostepW) { + + int istartW = START_IND(ow, osizeW, isizeW); + int iendW = END_IND(ow, osizeW, isizeW); + int kW = iendW - istartW; + + // Compute the gradients for over corresponding input pixels + T *ptr_gradInput = gradInput + istartH*isizeW + istartW; + const T *ptr_gradOutput = gradOutput + oh*osizeW + ow; + T grad_delta = *ptr_gradOutput / kW / kH; + + int ih, iw; + for(ih = 0; ih < kH; ++ih) { + for(iw = 0; iw < kW; ++iw) { + // atomic add since different threads could update same variable + gpuAtomicAddNoReturn(&(ptr_gradInput[iw]), grad_delta); + } + ptr_gradInput += isizeW; // next input line + } + } + } + } + + /* + * Description: + * this function adaptively average pools an input 4D tensor along dimensions 2 and 3 + * NHWC layout for both input and output tensor + * 4D input, 4D output + */ + template + C10_LAUNCH_BOUNDS_1(CUDA_MAX_THREADS) + __global__ void adaptive_average_pool_nhwc(const scalar_t* __restrict__ input, scalar_t* __restrict__ output, + int sizeB, int sizeC, + int isizeH, int isizeW, + int osizeH, int osizeW, + int kernel_stride_C, int kernel_size_C, + index_t istrideB, index_t istrideC, + index_t istrideH, index_t istrideW) + { + using opmath_t = at::opmath_type; + extern __shared__ int smem[]; + opmath_t *out_cached = reinterpret_cast(smem); + + // flattening cta for pre-computation & smem initialization; + int thread_id = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * threadIdx.z); + int block_size = blockDim.x * blockDim.y * blockDim.z; + + // use shared memory to store temporary output value. This is simply to + // reduce register usage. + for (index_t i = thread_id; i < kernel_size_C*blockDim.x*blockDim.y*blockDim.z; i+= block_size) { + out_cached[i] = opmath_t(0.0); + } + + __syncthreads(); + + // each CTA handles a portion of a single slice on batch dimension; + int batch_id = blockIdx.x % sizeB; + int channel_id = blockIdx.x / sizeB; + int channel_offset = threadIdx.x + channel_id * blockDim.x; + + // each CTA handles a single slice on batch dimension; + // We use gridDim.x to handle striding on C as well. + output = output + batch_id * osizeH * osizeW * sizeC; + input = input + batch_id * istrideB; + + // split out_cached and exclusively it assigned to each thread; + out_cached = &out_cached[(threadIdx.z * blockDim.y + threadIdx.y) * kernel_size_C * blockDim.x]; + + // iterate on output H & W. + // Each CTA handles a consecutive H & W section (TILE); Do NOT stride CTA on + // tile so there's a better chance to hit L1 cache. + index_t oH = (osizeH + gridDim.z-1) / gridDim.z; + index_t oW = (osizeW + gridDim.y-1) / gridDim.y; + index_t ostartH = threadIdx.z + blockIdx.z*oH; + index_t oendH = ::min(ostartH+oH, osizeH); + index_t ostartW = threadIdx.y + blockIdx.y*oW; + index_t oendW = ::min(ostartW+oW, osizeW); + + // Stride for threads, each warp can reuse L1 as they go. So theoretically + // better chance to survive cache eviction. + for (int oh = ostartH; oh < oendH; oh+=blockDim.z) { + int istartH = START_IND_INT(oh, osizeH, isizeH); + int iendH = END_IND_INT(oh, osizeH, isizeH); + for (int ow = ostartW; ow < oendW; ow+=blockDim.y) { + int istartW = START_IND_INT(ow, osizeW, isizeW); + int iendW = END_IND_INT(ow, osizeW, isizeW); + scalar_t factor = scalar_t(1.0) / ((iendH-istartH) * (iendW-istartW)); + + // loop on input: hierarchy h->w->c, use shared memory here hopefully + // would not stall global memory read; + for (index_t ih = istartH; ih < iendH; ih++) { + for (index_t iw = istartW; iw < iendW; iw++) { + int cached_index = threadIdx.x; + const scalar_t *ptr_input = input + ih*istrideH + iw*istrideW; + for (index_t c = channel_offset; + c < sizeC; + c += blockDim.x*kernel_stride_C) { + out_cached[cached_index] += ptr_input[c*istrideC]; + cached_index += blockDim.x; + } + } + } + scalar_t *ptr_output = output + (oh * osizeW + ow) * sizeC; + + int cached_index = threadIdx.x; + // write accumulated output to global memory; + for (index_t c = channel_offset; + c < sizeC; + c += blockDim.x*kernel_stride_C) { + // This causes numerical issueptr when unit test with NCHW kernel; + // switch to could verify the correctness; + // output[c] = out_cached[c] / (iendH-istartH) / (iendW-istartW); + ptr_output[c] = out_cached[cached_index] * factor; + out_cached[cached_index] = opmath_t(0.0); + cached_index += blockDim.x; + } + // no need to __syncthreads() since out_cached is not shared. + } + } + } + + /* + * Description: + * this function computes the gradInput from gradOutput + * NHWC layout for both input and output tensor + * 4D input, 4D output + */ + template + C10_LAUNCH_BOUNDS_1(CUDA_MAX_THREADS) + __global__ void adaptive_average_gradinput_nhwc(scalar_t* __restrict__ gradInput, const scalar_t* __restrict__ gradOutput, + int sizeB, int sizeC, + int isizeH, int isizeW, + int osizeH, int osizeW, + int kernel_stride_C, int kernel_size_C, + index_t ostrideB, index_t ostrideC, + index_t ostrideH, index_t ostrideW) + { + extern __shared__ int smem[]; + index_t *ostartW_cached = smem; + index_t *oendW_cached = &ostartW_cached[isizeW]; + + // be careful with alignment, in case scalar_t is fp16, we want to assign + // int pointers first. + scalar_t *r_kW_cached = reinterpret_cast(&oendW_cached[isizeW]); + scalar_t *r_kH_cached = &r_kW_cached[osizeW]; + scalar_t *out_cached = &r_kH_cached[osizeH]; + + // flattening cta for pre-computation & smem initialization; + int thread_id = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * threadIdx.z); + int block_size = blockDim.x * blockDim.y * blockDim.z; + + // Precompute output start/end index per input index on width dimension; + // Not doing this for height dimension, as that's our out-most loop. + for (index_t i = thread_id; i < isizeW; i+= block_size) { + ostartW_cached[i] = START_IND_INT(i, isizeW, osizeW); + oendW_cached[i] = END_IND_INT(i, isizeW, osizeW); + } + + // Precompute pooling height/weight factor for each output element; + // This is used to weight output gradient when accumulate them on input + // gradient. + // Technically we don't have to compute it for the whole `osizeH`, since + // each cta only covers a consecutive portion of the entire output. But it's + // not going to save us from code divergence, and shared memory save is not + // an issue neither, so just leave it as is for now. + for (index_t i = thread_id; i < osizeH; i+= block_size) { + r_kH_cached[i] = scalar_t(1.0) / (END_IND_INT(i, osizeH, isizeH) - START_IND_INT(i, osizeH, isizeH)); + } + for (index_t i = thread_id; i < osizeW; i+= block_size) { + r_kW_cached[i] = scalar_t(1.0) / (END_IND_INT(i, osizeW, isizeW) - START_IND_INT(i, osizeW, isizeW)); + } + + // each CTA handles a portion of a single slice on batch dimension; + int batch_id = blockIdx.x % sizeB; + int channel_id = blockIdx.x / sizeB; + int channel_offset = threadIdx.x + channel_id * blockDim.x; + + // use shared memory to store temporary output value. This is simply to + // reduce register usage. + for (index_t i = thread_id; i < kernel_size_C*blockDim.x*blockDim.y*blockDim.z; i+= block_size) { + out_cached[i] = scalar_t(0.0); + } + + __syncthreads(); + + // each CTA handles a portion of a single slice on batch dimension; + // We use gridDim.x to handle striding on C as well. + gradInput = gradInput + batch_id * isizeH * isizeW * sizeC; + gradOutput = gradOutput + batch_id * ostrideB; + + // split out_cached and exclusively it assigned to each thread; + out_cached = &out_cached[(threadIdx.z * blockDim.y + threadIdx.y) * blockDim.x * kernel_size_C]; + + // iterate on input H & W. + // Each CTA handles a consecutive H & W section (TILE); Do NOT stride CTA on + // tile so there's a better chance to hit L1 cache. + index_t iH = (isizeH + gridDim.z-1) / gridDim.z; + index_t iW = (isizeW + gridDim.y-1) / gridDim.y; + index_t istartH = threadIdx.z + blockIdx.z*iH; + index_t iendH = ::min(istartH+iH, isizeH); + index_t istartW = threadIdx.y + blockIdx.y*iW; + index_t iendW = ::min(istartW+iW, isizeW); + + // Stride for threads, each warp can reuse L1 as they go. So theoretically + // better chance to survive cache eviction. + for (index_t ih = istartH; ih < iendH; ih+=blockDim.z) { + index_t ostartH = START_IND_INT(ih, isizeH, osizeH); + index_t oendH = END_IND_INT(ih, isizeH, osizeH); + for (index_t iw = istartW; iw < iendW; iw+=blockDim.y) { + // loop on output: hierarchy h->w->c, so we could reuse weight factor f + // because it remains the same for given oh & ow + for(index_t oh = ostartH; oh < oendH; ++oh) { + for(index_t ow = ostartW_cached[iw]; ow < oendW_cached[iw]; ++ow) { + scalar_t f = r_kW_cached[ow] * r_kH_cached[oh]; + const scalar_t* ptr_gradOutput = gradOutput + oh*ostrideH + ow*ostrideW; + int cached_index = threadIdx.x; + for (index_t c = channel_offset; + c < sizeC; + c += blockDim.x*kernel_stride_C) { + out_cached[cached_index] += ptr_gradOutput[c*ostrideC] * f; + cached_index += blockDim.x; + } + } + } + scalar_t *ptr_gradInput = gradInput + (ih * isizeW + iw) * sizeC; + int cached_index = threadIdx.x; + // write accumulated gradIput to global memory; + for (index_t c = channel_offset; + c < sizeC; + c += blockDim.x*kernel_stride_C) { + ptr_gradInput[c] = out_cached[cached_index]; + out_cached[cached_index] = scalar_t(0.0); + cached_index += blockDim.x; + } + // no need to __syncthreads() since out_cached is not shared. + } + } + } + + // 4d tensor B x D x H x W + + void adaptive_avg_pool2d_out_cuda_template( + Tensor& output, + const Tensor& input, + IntArrayRef output_size) + { + TensorArg input_arg{ input, "input", 1 }, + output_arg{ output, "output", 2 }; + checkAllSameGPU(__func__, {input_arg, output_arg}); + + TORCH_CHECK(output_size.size() == 2, "adaptive_avg_pool2d: output_size must be 2"); + int64_t ndim = input.dim(); + TORCH_CHECK((ndim == 3 || ndim == 4), + "adaptive_avg_pool2d(): Expected 3D or 4D tensor, but got ", input.sizes()); + for (const auto i : {-2, -1}) { + TORCH_CHECK(input.size(i) > 0, + "adaptive_avg_pool2d(): Expected input to have non-zero size for non-batch dimensions, " + "but input has sizes ", input.sizes(), " with dimension ", i + ndim, " being " + "empty"); + } + + Tensor input_ = input; + switch (input.suggest_memory_format()) { + case at::MemoryFormat::ChannelsLast: { + // special case for tensor memory format in channels_last + TORCH_CHECK(input.ndimension() == 4, + "adaptive_avg_pool2d(): Expected 4D tensor, but got ", + input.sizes()); + + int sizeB = input_.size(0); + int sizeC = input_.size(1); + int isizeH = input_.size(2); + int isizeW = input_.size(3); + + int64_t istrideB = input_.stride(0); + int64_t istrideC = input_.stride(1); + int64_t istrideH = input_.stride(2); + int64_t istrideW = input_.stride(3); + + int osizeH = output_size[0]; + int osizeW = output_size[1]; + // preserve channels_last stride on output tensor; + if (!output.is_contiguous(at::MemoryFormat::ChannelsLast)) { + // TODO: modify this after resize_ added `memory_format` tag + output.resize_({sizeB, sizeC, osizeH, osizeW}).as_strided_({sizeB, sizeC, osizeH, osizeW}, {sizeC*osizeH*osizeW, 1, osizeW*sizeC, sizeC}); + } + + if (output.numel() == 0) { + return; + } + + const int max_threads = std::min( + at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, CUDA_MAX_THREADS); + int* maxThreadsDim = at::cuda::getCurrentDeviceProperties()->maxThreadsDim; + int* maxGridSize = at::cuda::getCurrentDeviceProperties()->maxGridSize; + size_t sharedMemPerBlock = at::cuda::getCurrentDeviceProperties()->sharedMemPerBlock; + + // Launch kernel on output tensor elements. Logic behind launch config: + // output tensor size NCHW, strides NHWC; + // Launch on: + // N -> grid.x + // H -> grid.z * block.z + // W -> grid.y * block.y + // C -> block.x + // encourage larger block_y & block_z for better cache hit while maintain + // reasonable block_x for coalesced memory access; + int block_x = std::min( + {maxThreadsDim[0], lastPow2(sizeC), at::cuda::warp_size()}); + int block_y = std::min( + {maxThreadsDim[1], lastPow2(osizeW), max_threads / block_x}); + int block_z = std::min( + {maxThreadsDim[2], lastPow2(osizeH), max_threads / block_x / block_y}); + block_x = std::min( + {maxThreadsDim[0], lastPow2(sizeC), max_threads / block_y / block_z}); + const dim3 block(block_x, block_y, block_z); + int kernel_stride_C = ceil_div(sizeC, block_x * 4); + int kernel_size_C = ceil_div(sizeC, block_x * kernel_stride_C); + + // Do NOT clip grid_x, striding on Batch dimension is not in the kernel, + // although it could be easily implemented given current kernel. + int grid_x = sizeB*kernel_stride_C; + // it's OK to clip grid_y & grid_z, as we block the two dimensions in the kernel; + int grid_y = std::min( + maxGridSize[1], ceil_div(osizeW, block_y*BLOCK_STRIDE)); + int grid_z = std::min( + maxGridSize[2], ceil_div(osizeH, block_z*BLOCK_STRIDE)); + const dim3 grid(grid_x, grid_y, grid_z); + + + // we are dealing with packed tensor here. max index is the same as numel. + // TODO: to really support input tensor large enough to go beyond int32, + // we will need to restrict out shared memory usage and adjust the launch + // config; + AT_ASSERT(input_.numel() < std::numeric_limits::max()); + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input_.scalar_type(), "adaptive_avg_pool2d_nhwc_cuda", [&] { + using opmath_t = at::opmath_type; + size_t shmem_size = (kernel_size_C * block_x * block_y * block_z) * sizeof(opmath_t); + AT_ASSERT(shmem_size <= sharedMemPerBlock); + adaptive_average_pool_nhwc<<>> ( + input_.const_data_ptr(), + output.mutable_data_ptr(), + sizeB, sizeC, isizeH, isizeW, osizeH, osizeW, + kernel_stride_C, kernel_size_C, + istrideB, istrideC, istrideH, istrideW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + ); + break; + } + case at::MemoryFormat::Contiguous: { + int64_t grid_x = input.size(-3); + if (input.ndimension() == 4) { + input_ = input.contiguous(); + grid_x *= input_.size(-4); + } + int64_t sizeD = input_.size(-3); + int64_t isizeH = input_.size(-2); + int64_t isizeW = input_.size(-1); + + int64_t istrideD = input_.stride(-3); + int64_t istrideH = input_.stride(-2); + int64_t istrideW = input_.stride(-1); + + int64_t osizeH = output_size[0]; + int64_t osizeW = output_size[1]; + if (input.ndimension() == 4) { + output.resize_({input_.size(-4), sizeD, osizeH, osizeW}); + } else { + output.resize_({sizeD, osizeH, osizeW}); + } + if (output.numel() == 0) { + return; + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input_.scalar_type(), "adaptive_avg_pool2d_cuda", [&] { + const scalar_t *input_data = input_.const_data_ptr(); + scalar_t *output_data = output.mutable_data_ptr(); + + // cuda blocks & threads: + int blocksH = std::max((int)(16L / sizeD), 1); + dim3 blocks(grid_x, blocksH); + dim3 threads(32, 8); + + // run averagepool kernel + adaptive_average_pool <<>> ( + input_data, output_data, + isizeH, isizeW, osizeH, osizeW, + istrideD, istrideH, istrideW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + ); + break; + } + default: + TORCH_CHECK( + false, + "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + } + + void adaptive_avg_pool2d_backward_out_cuda_template( + Tensor& gradInput, + const Tensor& gradOutput_, + const Tensor& input) + { + TensorArg grad_input_arg{ gradInput, "gradInput", 1 }, + grad_output_arg{ gradOutput_, "gradOutput_", 2 }, + input_arg{ input, "input", 3 }; + + adaptive_pool_empty_output_check(gradOutput_, "adaptive_avg_pool2d_backward"); + TORCH_CHECK(input.dim() == gradOutput_.dim(), + __func__, ": Expected dimensions ", input.dim(), " for `gradOutput_` but got dimensions ", gradOutput_.dim()); + + checkAllSameGPU(__func__, {grad_input_arg, grad_output_arg, input_arg}); + + switch (input.suggest_memory_format()) { + case at::MemoryFormat::ChannelsLast: { + // special case for tensor memory format in channels_last + TORCH_CHECK(input.ndimension() == 4, + "adaptive_avg_pool2d_backward_cuda(): Expected 4D tensor, but got ", input.ndimension()); + + int sizeB = input.size(0); + int sizeC = input.size(1); + int isizeH = input.size(2); + int isizeW = input.size(3); + + Tensor gradOutput = gradOutput_; + + int64_t ostrideB = gradOutput.stride(0); + int64_t ostrideC = gradOutput.stride(1); + int64_t ostrideH = gradOutput.stride(2); + int64_t ostrideW = gradOutput.stride(3); + + int osizeH = gradOutput.size(-2); + int osizeW = gradOutput.size(-1); + + // preserve channels_last stride on input tensor; + if (!gradInput.is_contiguous(at::MemoryFormat::ChannelsLast)) { + gradInput.as_strided_( + {sizeB, sizeC, isizeH, isizeW}, + {sizeC*isizeH*isizeW, 1, isizeW*sizeC, sizeC}); + } + + int max_threads = std::min( + at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, CUDA_MAX_THREADS); + int* maxThreadsDim = at::cuda::getCurrentDeviceProperties()->maxThreadsDim; + int* maxGridSize = at::cuda::getCurrentDeviceProperties()->maxGridSize; + size_t sharedMemPerBlock = at::cuda::getCurrentDeviceProperties()->sharedMemPerBlock; + + // Launch kernel on input tensor elements. Logic behind launch config: + // input tensor size NCHW, strides NHWC; + // Launch on: + // N(C) -> grid.x (striding on C to reduce sh_mem usage) + // H -> grid.z * block.z + // W -> grid.y * block.y + // C -> block.x + // encourage larger block_y & block_z for better cache hit while maintain + // reasonable block_x for coalesced memory access; + bool done = false; + do { + int block_x = std::max(std::min( + {maxThreadsDim[0], lastPow2(sizeC), at::cuda::warp_size()}), 1); + int block_y = std::max(std::min( + {maxThreadsDim[1], lastPow2(isizeW), max_threads / block_x}), 1); + int block_z = std::max(std::min( + {maxThreadsDim[2], lastPow2(isizeH), max_threads / block_x / block_y}), 1); + block_x = std::max(std::min( + {maxThreadsDim[0], lastPow2(sizeC), max_threads / block_y / block_z}), 1); + const dim3 block(block_x, block_y, block_z); + int kernel_stride_C = ceil_div(sizeC, block_x * 4); + int kernel_size_C = ceil_div(sizeC, block_x * kernel_stride_C); + + // Do NOT clip grid_x, striding on Batch dimension is not in the kernel, + // although it could be easily implemented given current kernel. + int grid_x = sizeB*kernel_stride_C; + // it's OK to clip grid_y & grid_z, as we block the two dimensions in the kernel; + int grid_y = std::min( + maxGridSize[1], ceil_div(isizeW, block_y*BLOCK_STRIDE)); + int grid_z = std::min( + maxGridSize[2], ceil_div(isizeH, block_z*BLOCK_STRIDE)); + const dim3 grid(grid_x, grid_y, grid_z); + + // we are dealing with packed tensor here. max index is the same as numel. + // TODO: to really support input tensor large enough to go beyond int32, + // we will need to restrict out shared memory usage and adjust the launch + // config; + AT_ASSERT(input.numel() < std::numeric_limits::max()); + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool2d_backward_nhwc_cuda", [&] { + size_t shmem_size = (kernel_size_C * block_x * block_y * block_z + osizeH + osizeW) * sizeof(scalar_t) + 2 * isizeW * sizeof(int32_t); + if (shmem_size <= sharedMemPerBlock) { + adaptive_average_gradinput_nhwc<<>> ( + gradInput.mutable_data_ptr(), + gradOutput.const_data_ptr(), + sizeB, sizeC, isizeH, isizeW, osizeH, osizeW, + kernel_stride_C, kernel_size_C, + ostrideB, ostrideC, ostrideH, ostrideW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + done = true; + } else { + TORCH_WARN_ONCE("Requested shmem_size exceeds sharedMemPerBlock limit! Reducing max_threads..."); + max_threads /= 2; + } + } + ); + } while (!done && max_threads); + if (!done) { + TORCH_INTERNAL_ASSERT(false, "Couldn't reduce launch bounds to accommodate sharedMemPerBlock limit"); + } + break; + } + case at::MemoryFormat::Contiguous: { + bool atomic = true; // suboptimal, but without atomic it doesn't pass the tests + + Tensor gradOutput = gradOutput_.contiguous(); + + int64_t sizeD = input.size(-3); + int64_t isizeH = input.size(-2); + int64_t isizeW = input.size(-1); + + int64_t osizeH = gradOutput.size(-2); + int64_t osizeW = gradOutput.size(-1); + + int64_t grid_x = sizeD; + if (input.ndimension() == 4) grid_x *= input.size(-4); + + //bool atomic = (isizeW%osizeW != 0) || (isizeH%osizeH != 0); + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool2d_backward_cuda", [&] { + const scalar_t *gradOutput_data = gradOutput.const_data_ptr(); + scalar_t *gradInput_data = gradInput.mutable_data_ptr(); + + // cuda blocks & threads: + int blocksH = std::max((int)(16L / sizeD), 1); + dim3 blocks(grid_x, blocksH); + dim3 threads(32, 8); + + if(atomic) + { + // run updateGradInput kernel, accumulate gradients atomically + atomic_adaptive_average_gradinput <<>> ( + gradInput_data, gradOutput_data, + isizeH, isizeW, osizeH, osizeW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + else + { + // run updateGradInput kernel + adaptive_average_gradinput <<>> ( + gradInput_data, gradOutput_data, + isizeH, isizeW, osizeH, osizeW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + } + ); + break; + } + default: + TORCH_CHECK( + false, + "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + + } + } + +} // namespace + + Tensor& adaptive_avg_pool2d_out_cuda( + const Tensor& input, + IntArrayRef output_size, + Tensor& output) + { + adaptive_avg_pool2d_out_cuda_template( + output, input, output_size); + return output; + } + + Tensor adaptive_avg_pool2d_cuda( + at::Tensor const& input, + IntArrayRef output_size) + { + auto output = at::empty({0}, input.options()); + adaptive_avg_pool2d_out_cuda_template( + output, input, output_size); + return output; + } + + Tensor& adaptive_avg_pool2d_backward_out_cuda( + Tensor& gradInput, + const Tensor& gradOutput, + const Tensor& input) + { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("adaptive_avg_pool2d_backward_out_cuda"); + gradInput.resize_as_(input); + if (gradInput.numel() != 0) { + adaptive_avg_pool2d_backward_out_cuda_template( + gradInput, gradOutput, input); + } + return gradInput; + } + + Tensor adaptive_avg_pool2d_backward_cuda( + const Tensor& gradOutput, + const Tensor& input) + { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("adaptive_avg_pool2d_backward_cuda"); + auto gradInput = at::zeros_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + if (gradInput.numel() != 0) { + adaptive_avg_pool2d_backward_out_cuda_template( + gradInput, gradOutput, input); + } + return gradInput; + } + +} // namespace at::native + +#undef BLOCK_STRIDE +#undef CUDA_MAX_THREADS +#undef START_IND +#undef END_IND diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveAveragePooling3d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveAveragePooling3d.cu new file mode 100644 index 0000000000000000000000000000000000000000..d76267280e0ed3aae67c4995a0d80f0f40d5bdbb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveAveragePooling3d.cu @@ -0,0 +1,551 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +#include + +#include +#include +#include + + +namespace at::native { + +namespace { + +__device__ inline int64_t start_index(int64_t a, int64_t b, int64_t c) { + return (a / b) * c + ((a % b) * c) / b; +} + +__device__ inline int64_t end_index(int64_t a, int64_t b, int64_t c) { + return 1 + ((a + 1) * c - 1) / b; +} + +// 5d tensor B x D x T x H x W +// All kernels view batch dim B and dim D as collapsed. + +/* + * Description: + * this function adaptively average pools an input 5D tensor along dimensions + * 2, 3, and 4 5D input, 5D output + * + * gridDim.y blocks work together on a single 2D output plane specified by + * (blockIdx.x + offsetZ). + */ +template +__global__ void adaptiveaveragepool( + const scalar_t *input, scalar_t *output, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t sizeD, int64_t istrideB, int64_t istrideD, + int64_t istrideT, int64_t istrideH, int64_t istrideW, + int64_t offsetZ) { + // iterates on output pixels + int ot, oh, ow; + + // compute offsets based on thread/block ID + int ostartH = blockIdx.y * blockDim.y + threadIdx.y; + int oendH = osizeH; + int ostepH = gridDim.y * blockDim.y; + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + // select output plane + int64_t o_plane = blockIdx.x + offsetZ; + ot = o_plane % osizeT; // output frame/time + int d = o_plane / osizeT; // flattened (batch, channel) index + + // Decompose d into batch and channel indices + int batch_idx = d / sizeD; + int channel_idx = d % sizeD; + + // input frame/time range is fixed. + int istartT = start_index(ot, osizeT, isizeT); + int iendT = end_index(ot, osizeT, isizeT); + int kT = iendT - istartT; + + // output offset by slice/feature and frame/time + scalar_t *output_dt = output + o_plane*osizeH*osizeW; + + // For all output pixels... + for (oh = ostartH; oh < oendH; oh += ostepH) { + int istartH = start_index(oh, osizeH, isizeH); + int iendH = end_index(oh, osizeH, isizeH); + int kH = iendH - istartH; + + for (ow = ostartW; ow < oendW; ow += ostepW) { + int istartW = start_index(ow, osizeW, isizeW); + int iendW = end_index(ow, osizeW, isizeW); + int kW = iendW - istartW; + + scalar_t *ptr_output = output_dt + oh*osizeW + ow; + accscalar_t sum = static_cast(0); + + int it, ih, iw; + for (it = 0; it < kT; ++it) { + for (ih = 0; ih < kH; ++ih) { + for (iw = 0; iw < kW; ++iw) { + int64_t input_offset = batch_idx * istrideB + channel_idx * istrideD + + (istartT + it) * istrideT + + (istartH + ih) * istrideH + (istartW + iw) * istrideW; + scalar_t val = input[input_offset]; + sum += static_cast(val); + } + } + } + // Update output + const accscalar_t divide_factor = static_cast(kT * kH * kW); + *ptr_output = static_cast(sum / divide_factor); + } + } +} + +template +void adaptiveaveragepool_loop( + const scalar_t *input_data, scalar_t *output_data, + int64_t totalZ, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t sizeD, int64_t istrideB, int64_t istrideD, int64_t istrideT, int64_t istrideH, int64_t istrideW) { + int64_t offsetZ = 0; + dim3 threads(32, 8); + // each H*W plane is processed by blocksH thread blocks + int blocksH = std::max((int)(16L / totalZ), 1); + while (totalZ > 0) { + dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); + adaptiveaveragepool + <<>>( + input_data, output_data, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW, + sizeD, istrideB, istrideD, + istrideT, istrideH, istrideW, + offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + totalZ -= 65535; + offsetZ += 65535; + } +} + +/* + * Description: + * This function computes the gradInput from gradOutput. + * + * gridDim.y blocks work together on a single 2D output plane specified by + * (blockIdx.x + offsetZ). + */ +template +__global__ void adaptiveaveragegradinput( + scalar_t *gradInput, const scalar_t *gradOutput, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t offsetZ) +{ + // iterators on input pixels + int it, ih, iw; + + // compute offsets based on thread/block ID + int istartH = blockIdx.y * blockDim.y + threadIdx.y; + int iendH = isizeH; + int istepH = gridDim.y * blockDim.y; + int istartW = threadIdx.x; + int iendW = isizeW; + int istepW = blockDim.x; + + // select input plane + int64_t i_plane = blockIdx.x + offsetZ; + it = i_plane % isizeT; // output frame/time + int d = i_plane / isizeT; // slice/feature + + // output frame/time range is fixed. + int ostartT = start_index(it, isizeT, osizeT); + int oendT = end_index(it, isizeT, osizeT); + + // gradInput offset by slice/feature and frame/time. + scalar_t *gradInput_dt = gradInput + i_plane*isizeH*isizeW; + // gradOutput offset by slice/feature and earliest relevant frame/time + const scalar_t *gradOutput_dt = gradOutput + (d*osizeT + ostartT)*osizeH*osizeW; + + // For all input pixels... + for (ih = istartH; ih < iendH; ih += istepH) { + int ostartH = start_index(ih, isizeH, osizeH); + int oendH = end_index(ih, isizeH, osizeH); + + for (iw = istartW; iw < iendW; iw += istepW) { + int ostartW = start_index(iw, isizeW, osizeW); + int oendW = end_index(iw, isizeW, osizeW); + + // Compute the gradients from corresponding output pixels + scalar_t *ptr_gradInput = gradInput_dt + ih*isizeW + iw; + const scalar_t *ptr_gradOutput = gradOutput_dt; + + // for all relevant output pixels + int ot, oh, ow; + for (ot = ostartT; ot < oendT; ++ot) { + int kT = end_index(ot, osizeT, isizeT) - start_index(ot, osizeT, isizeT); + for (oh = ostartH; oh < oendH; ++oh) { + int kH = end_index(oh, osizeH, isizeH) - start_index(oh, osizeH, isizeH); + for (ow = ostartW; ow < oendW; ++ow) { + int kW = end_index(ow, osizeW, isizeW) - start_index(ow, osizeW, isizeW); + const accscalar_t divide_factor = kW * kH * kT; + accscalar_t grad_delta = static_cast(ptr_gradOutput[oh*osizeW + ow] / divide_factor); + *ptr_gradInput += static_cast(grad_delta); + } + } + ptr_gradOutput += osizeH*osizeW; // next output frame + } + } + } +} + +template +void adaptiveaveragegradinput_loop( + scalar_t *gradInput_data, const scalar_t *gradOutput_data, + int64_t totalZ, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW) { + int64_t offsetZ = 0; + dim3 threads(32, 8); + // each H*W plane is processed by blocksH thread blocks + int blocksH = std::max((int)(16L / totalZ), 1); + while (totalZ > 0) { + dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); + adaptiveaveragegradinput + <<>>( + gradInput_data, gradOutput_data, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW, + offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + totalZ -= 65535; + offsetZ += 65535; + } +} + +/* + * Description: + * This function computes the gradInput from gradOutput. + * + * gridDim.y blocks work together on a single 2D output plane specified by + * (blockIdx.x + offsetZ). + * + * (uses atomic add) + * + */ +template +__global__ void atomicadaptiveaveragegradinput( + scalar_t *gradInput, const scalar_t *gradOutput, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t offsetZ) +{ + // iterators on output pixels + int ot, oh, ow; + + // compute offsets based on thread/block ID + int ostartH = blockIdx.y * blockDim.y + threadIdx.y; + int oendH = osizeH; + int ostepH = gridDim.y * blockDim.y; + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + // select output plane + int64_t o_plane = blockIdx.x + offsetZ; + ot = o_plane % osizeT; // output frame/time + int d = o_plane / osizeT; // output slice/feature + + // input frame/time range is fixed. + int istartT = start_index(ot, osizeT, isizeT); + int iendT = end_index(ot, osizeT, isizeT); + int kT = iendT - istartT; + + // gradInput offset by slice/feature and earliest relevant frame/time + scalar_t *gradInput_nt = gradInput + (d*isizeT + istartT)*isizeH*isizeW; + // gradOutput offset by slice/feature and frame/time + const scalar_t *gradOutput_nt = gradOutput + o_plane*osizeH*osizeW; + + // For all output pixels... + for (oh = ostartH; oh < oendH; oh += ostepH) { + int istartH = start_index(oh, osizeH, isizeH); + int iendH = end_index(oh, osizeH, isizeH); + int kH = iendH - istartH; + + for (ow = ostartW; ow < oendW; ow += ostepW) { + int istartW = start_index(ow, osizeW, isizeW); + int iendW = end_index(ow, osizeW, isizeW); + int kW = iendW - istartW; + + // Compute the gradients from corresponding input pixels + scalar_t *ptr_gradInput = gradInput_nt + istartH*isizeW + istartW; + const scalar_t *ptr_gradOutput = gradOutput_nt + oh*osizeW + ow; + scalar_t grad_delta = *ptr_gradOutput / kT / kH / kW; + + int it, ih, iw; + for (it = 0; it < kT; ++it) { + for (ih = 0; ih < kH; ++ih) { + for (iw = 0; iw < kW; ++iw) { + gpuAtomicAddNoReturn(&(ptr_gradInput[ih*isizeW + iw]), grad_delta); + } + } + ptr_gradInput += isizeH*isizeW; // next input frame + } + } + } +} + +template +void atomicadaptiveaveragegradinput_loop( + scalar_t* gradInput_data, const scalar_t* gradOutput_data, + int64_t totalZ, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW) { + int64_t offsetZ = 0; + dim3 threads(32, 8); + int blocksH = std::max((int)(16L / totalZ), 1); + while (totalZ > 0) { + dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); + atomicadaptiveaveragegradinput<<>>( + gradInput_data, gradOutput_data, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW, + offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + totalZ -= 65535; + offsetZ += 65535; + } +} + +// 5D tensor B x D x T x H x w + +void adaptive_avg_pool3d_out_cuda_template( + Tensor& output, + const Tensor& input_, + IntArrayRef& output_size) { + TensorArg output_arg{output, "output", 1}; + TensorArg input_arg{input_, "input_", 2}; + + checkAllSameGPU("adaptive_avg_pool3d_cuda", {output_arg, input_arg}); + + for (int64_t i = 1; i < input_.ndimension(); i++) { + TORCH_CHECK( + input_.size(i) > 0, + "adaptive_avg_pool3d_cuda(): Expected input to have non-zero size for non-batch dimensions, " + "but input has sizes ", input_.sizes(), + " with dimension ", i, " being empty"); + } + + TORCH_CHECK( + (input_.ndimension() == 4 || input_.ndimension() == 5), + "adaptive_avg_pool3d_cuda(): Expected 4D or 5D tensor, but got ", input_.sizes()); + + // the jit sometimes passes output_size.size() == 1 + TORCH_CHECK( + output_size.size() == 1 || output_size.size() == 3, + "adaptive_avg_pool3d: internal error: output_size.size() must be 1 or 3"); + + int64_t osizeT = output_size[0]; + int64_t osizeH = output_size[1]; + int64_t osizeW = output_size[2]; + + int64_t sizeD, isizeT, isizeH, isizeW; + int64_t istrideB, istrideD, istrideT, istrideH, istrideW; + int64_t totalZ; + + const Tensor& input = input_.ndimension() == 4 ? input_ : input_.contiguous(); + + if (input.ndimension() == 4) { + sizeD = input.size(0); + isizeT = input.size(1); + isizeH = input.size(2); + isizeW = input.size(3); + + istrideB = 0; + istrideD = input.stride(0); + istrideT = input.stride(1); + istrideH = input.stride(2); + istrideW = input.stride(3); + + output.resize_({sizeD, osizeT, osizeH, osizeW}); + + totalZ = sizeD * osizeT; + } else { + int64_t sizeB = input.size(0); + sizeD = input.size(1); + isizeT = input.size(2); + isizeH = input.size(3); + isizeW = input.size(4); + + istrideB = input.stride(0); + istrideD = input.stride(1); + istrideT = input.stride(2); + istrideH = input.stride(3); + istrideW = input.stride(4); + + output.resize_({sizeB, sizeD, osizeT, osizeH, osizeW}); + + totalZ = sizeB * sizeD * osizeT; + } + + if (output.numel() == 0) { + return; + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_cuda", [&] { + using accscalar_t = at::acc_type; + const scalar_t* input_data = input.const_data_ptr(); + scalar_t* output_data = output.mutable_data_ptr(); + + adaptiveaveragepool_loop( + input_data, output_data, + totalZ, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW, + sizeD, istrideB, istrideD, istrideT, istrideH, istrideW); + }); +} + +void adaptive_avg_pool3d_backward_out_cuda_template( + Tensor& gradInput, + const Tensor& gradOutput_, + const Tensor& input) { + TensorArg grad_input_arg{gradInput, "gradInput", 1}; + TensorArg grad_output_arg{gradOutput_, "gradOutput_", 2}; + TensorArg input_arg{input, "input", 3}; + + adaptive_pool_empty_output_check(gradOutput_, "adaptive_avg_pool3d_backward"); + TORCH_CHECK(input.dim() == gradOutput_.dim(), + __func__, ": Expected dimensions ", input.dim(), " for `gradOutput_` but got dimensions ", gradOutput_.dim()); + + checkAllSameGPU( + "adaptive_avg_pool3d_out_cuda", + {grad_input_arg, grad_output_arg, input_arg}); + + const Tensor gradOutput = gradOutput_.contiguous(); + + gradInput.resize_as_(input); + if (gradInput.numel() == 0) { + return; + } + + gradInput.zero_(); + + int64_t sizeD, isizeT, isizeH, isizeW; + int64_t osizeT, osizeH, osizeW; + int64_t totalZ; + + if (input.ndimension() == 4) { + sizeD = input.size(0); + isizeT = input.size(1); + isizeH = input.size(2); + isizeW = input.size(3); + + osizeT = gradOutput.size(1); + osizeH = gradOutput.size(2); + osizeW = gradOutput.size(3); + } else { + sizeD = input.size(1); + isizeT = input.size(2); + isizeH = input.size(3); + isizeW = input.size(4); + + osizeT = gradOutput.size(2); + osizeH = gradOutput.size(3); + osizeW = gradOutput.size(4); + } + + bool atomic = (isizeW%osizeW != 0) || (isizeH%osizeH != 0) || (isizeT%osizeT != 0); + + if (input.ndimension() == 4) { + totalZ = atomic ? sizeD * osizeT : sizeD * isizeT; + } else { + int sizeB = input.size(0); + totalZ = atomic ? sizeB * sizeD * osizeT : sizeB * sizeD * isizeT; + } + + if (atomic) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_backward_cuda", [&] { + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput.const_data_ptr(); + + atomicadaptiveaveragegradinput_loop( + gradInput_data, gradOutput_data, + totalZ, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), "adaptive_avg_pool3d_backward_cuda", [&] { + using accscalar_t = at::acc_type; + + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput.const_data_ptr(); + + adaptiveaveragegradinput_loop( + gradInput_data, gradOutput_data, + totalZ, + isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW); + }); + } +} + +} // namespace + +Tensor& adaptive_avg_pool3d_out_cuda(const Tensor& input, + IntArrayRef output_size, + Tensor& output) { + adaptive_avg_pool3d_out_cuda_template(output, input, output_size); + return output; +} + +Tensor adaptive_avg_pool3d_cuda( + const Tensor& input, + IntArrayRef output_size) { + auto output = at::empty({0}, input.options()); + adaptive_avg_pool3d_out_cuda_template(output, input, output_size); + return output; +} + +Tensor& adaptive_avg_pool3d_backward_out_cuda(const Tensor& gradOutput_, + const Tensor& input, + Tensor& gradInput) { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("adaptive_avg_pool3d_backward_out_cuda"); + adaptive_avg_pool3d_backward_out_cuda_template(gradInput, gradOutput_, input); + return gradInput; +} + +Tensor adaptive_avg_pool3d_backward_cuda( + const Tensor& gradOutput_, + const Tensor& input) { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("adaptive_avg_pool3d_backward_cuda"); + auto gradInput = at::empty_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + adaptive_avg_pool3d_backward_out_cuda_template(gradInput, gradOutput_, input); + return gradInput; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu new file mode 100644 index 0000000000000000000000000000000000000000..ef1a46d4886ab39d3d882352461465f96392cb35 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu @@ -0,0 +1,478 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +#include +#include +#include + + +namespace at::native { + +namespace { + +__device__ inline int64_t start_index(int64_t a, int64_t b, int64_t c) { + return (a / b) * c + ((a % b) * c) / b; +} + +__device__ inline int64_t end_index(int64_t a, int64_t b, int64_t c) { + return 1 + ((a + 1) * c - 1) / b; +} + +// 4d tensor B x D x H x W + +/* + * Description: + * this function adaptively maxpools an input 4D tensor along dimensions 2 and 3 + * 4D input, 4D output, 4D argmax x and y + */ + template +__global__ void adaptivemaxpool(const T *input, T *output, int64_t *indices, + int isizeH, int isizeW, + int osizeH, int osizeW, + int64_t istrideD, int64_t istrideH, int64_t istrideW) +{ + // iterators + int oh, ow; + + // compute offsets based on thread/block ID + int o_plane = blockIdx.x; + int i_plane = o_plane; + + int ostartW = threadIdx.x; + int oendW = osizeW; + const int ostepW = blockDim.x; + + int ostartH = blockDim.y*blockIdx.y + threadIdx.y; + int oendH = osizeH; + const int ostepH = blockDim.y*gridDim.y; + // select input/output plane + output = output + o_plane*osizeH*osizeW; + input = input + i_plane*istrideD; + indices = indices + o_plane*osizeH*osizeW; + + // For all output pixels... + for(oh = ostartH; oh < oendH; oh += ostepH) { + + int istartH = start_index(oh, osizeH, isizeH); + int iendH = end_index(oh, osizeH, isizeH); + int kH = iendH - istartH; + + for(ow = ostartW; ow < oendW; ow += ostepW) { + int istartW = start_index(ow, osizeW, isizeW); + int iendW = end_index(ow, osizeW, isizeW); + + int kW = iendW - istartW; + + // Compute the mean of the input image... + const T *ptr_input = input + istartH*istrideH + istartW*istrideW; + T *ptr_output = output + oh*osizeW + ow; + int64_t *ptr_ind = indices + oh*osizeW + ow; + int argmax = istartH * isizeW + istartW; + T max = at::numeric_limits::lower_bound(); // -Infinity + int ih, iw; + for(ih = 0; ih < kH; ih++) { + for(iw = 0; iw < kW; iw++) { + T val = ptr_input[iw*istrideW]; + if ((val > max) || at::_isnan(val)) { + max = val; + argmax = (ih+istartH)*isizeW + iw+istartW; + } + } + ptr_input += istrideH; // next input line + } + // Update output and argmax + *ptr_output = max; + *ptr_ind = argmax; + } + } +} + +/* + * Description: + * this function computes the gradInput from weight and gradOutput + */ + template +__global__ void adaptivemaxgradinput(T *gradInput, const T *gradOutput, const int64_t *indices, + int isizeH, int isizeW, + int osizeH, int osizeW) +{ + // iterators + int oh, ow; + + // compute offsets based on thread/block ID + int o_plane = blockIdx.x; + int i_plane = o_plane; + //int k = blockIdx.x % sizeD; + + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + int ostartH = blockDim.y*blockIdx.y + threadIdx.y; + int oendH = osizeH; + int ostepH = blockDim.y*gridDim.y; + + // select input/output plane + gradOutput = gradOutput + o_plane*osizeH*osizeW; + gradInput = gradInput + i_plane*isizeH*isizeW; + indices = indices + o_plane*osizeH*osizeW; + + // compute gradInput + for(oh = ostartH; oh < oendH; oh += ostepH) { + + for(ow = ostartW; ow < oendW; ow += ostepW) { + + const T *ptr_gradOutput = gradOutput + oh*osizeW + ow; + const int64_t *ptr_ind = indices + oh*osizeW + ow; + T z = *ptr_gradOutput; + + int argmax = (*ptr_ind); + + gradInput[argmax] += z; + } + } +} + +/* + * Description: + * this function computes the gradInput from weight and gradOutput + * when kH != dH or kW != dW (uses atomic add) + */ + template +__global__ void atomicadaptivemaxgradinput( + T *gradInput, const T *gradOutput, const int64_t *indices, + int isizeH, int isizeW, int osizeH, int osizeW +) +{ + // iterators + int oh, ow; + + // compute offsets based on thread/block ID + int o_plane = blockIdx.x; + int i_plane = o_plane; + + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + int ostartH = blockDim.y*blockIdx.y + threadIdx.y; + int oendH = osizeH; + int ostepH = blockDim.y*gridDim.y; + + // select input/output plane + gradOutput = gradOutput + o_plane*osizeH*osizeW; + gradInput = gradInput + i_plane*isizeH*isizeW; + indices = indices + o_plane*osizeH*osizeW; + + // compute gradInput + for(oh = ostartH; oh < oendH; oh += ostepH) { + + for(ow = ostartW; ow < oendW; ow += ostepW) { + + const T *ptr_gradOutput = gradOutput + oh*osizeW + ow; + const int64_t *ptr_ind = indices + oh*osizeW + ow; + T z = *ptr_gradOutput; + + int argmax = (*ptr_ind); + + // atomic add since different threads could update same variable + gpuAtomicAddNoReturn(&(gradInput[argmax]), z); + } + } +} +} // namespace + +// 4d tensor B x D x H x W + +TORCH_IMPL_FUNC(adaptive_max_pool2d_out_cuda) +(const Tensor& input, +IntArrayRef output_size, +const Tensor& output, +const Tensor& indices) { + TensorArg output_arg{output, "output", 1}; + TensorArg indices_arg{indices, "indices", 2}; + TensorArg input_arg{input, "input", 3}; + + checkAllSameGPU( + __func__, {output_arg, indices_arg, input_arg}); + if (input.numel() == 0) { + return; + } + + int64_t osizeH = output_size[0]; + int64_t osizeW = output_size[1]; + + const at::Tensor output_c = output.is_contiguous() ? output : at::empty(output.sizes(), output.options()); + const at::Tensor indices_c = indices.is_contiguous() ? indices : at::empty(indices.sizes(), indices.options()); + + if (input.ndimension() == 3) { + int64_t sizeD = input.size(0); + int64_t isizeH = input.size(1); + int64_t isizeW = input.size(2); + + int64_t istrideD = input.stride(0); + int64_t istrideH = input.stride(1); + int64_t istrideW = input.stride(2); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, input.scalar_type(), "adaptive_max_pool2d_cuda", [&] { + const scalar_t* input_data = input.const_data_ptr(); + scalar_t* output_data = output_c.mutable_data_ptr(); + int64_t* indices_data = indices_c.mutable_data_ptr(); + + // cuda blocks & threads: + int blocksH = (int)(16L / sizeD); + blocksH = blocksH < 1 ? 1 : blocksH; + dim3 blocks(sizeD, blocksH); + dim3 threads(32, 8); + + // run maxpool kernel + adaptivemaxpool<<< + blocks, + threads, + 0, + at::cuda::getCurrentCUDAStream()>>>( + input_data, + output_data, + indices_data, + isizeH, + isizeW, + osizeH, + osizeW, + istrideD, + istrideH, + istrideW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + } else { + Tensor input_ = input.contiguous(); + int64_t sizeB = input_.size(0); + int64_t sizeD = input_.size(1); + int64_t isizeH = input_.size(2); + int64_t isizeW = input_.size(3); + + // In the kernel, the batch and channel dimensions are treated as if they + // are flattened and istrideD is used as the stride of this flattened dim + // Handle the edge case where input_.size(1) == 1, where despite passing the + // contiguity check the stride might not be H * W + int64_t istrideD = isizeH * isizeW; + int64_t istrideH = input_.stride(2); + int64_t istrideW = input_.stride(3); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + input_.scalar_type(), + "adaptive_max_pool2d_cuda", + [&] { + const scalar_t* input_data = input_.const_data_ptr(); + scalar_t* output_data = output_c.mutable_data_ptr(); + int64_t* indices_data = indices_c.mutable_data_ptr(); + + // cuda blocks & threads: + int blocksH = (int)(16L / sizeD); + blocksH = blocksH < 1 ? 1 : blocksH; + dim3 blocks(sizeB * sizeD, blocksH); + dim3 threads(32, 8); + + // run maxpool kernel + adaptivemaxpool<<< + blocks, + threads, + 0, + at::cuda::getCurrentCUDAStream()>>>( + input_data, + output_data, + indices_data, + isizeH, + isizeW, + osizeH, + osizeW, + istrideD, + istrideH, + istrideW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + } + + if (!output.is_contiguous()) { + output.copy_(output_c); + } + if (!indices.is_contiguous()) { + indices.copy_(indices_c); + } +} + +TORCH_IMPL_FUNC(adaptive_max_pool2d_backward_out_cuda) +(const Tensor& gradOutput, + const Tensor& input, + const Tensor& indices, + const Tensor& gradInput) { + globalContext().alertNotDeterministic( + "adaptive_max_pool2d_backward_cuda"); + + TensorArg grad_input_arg{gradInput, "gradInput", 1}; + TensorArg grad_output_arg{gradOutput, "gradOutput", 2}; + TensorArg input_arg{input, "input", 3}; + TensorArg indices_arg{indices, "indices", 4}; + + checkAllSameGPU( + __func__, + {grad_input_arg, grad_output_arg, input_arg, indices_arg}); + + if (gradOutput.numel() == 0) { + return; + } + + bool atomic = + true; // suboptimal, but without atomic it doesn't pass the tests + + const at::Tensor gradOutput_ = gradOutput.contiguous(); + const at::Tensor indices_ = indices.contiguous(); + const at::Tensor gradInput_c = gradInput.is_contiguous() ? gradInput : at::empty(gradInput.sizes(), gradInput.options()); + + if (input.ndimension() == 3) { + int64_t sizeD = input.size(0); + int64_t isizeH = input.size(1); + int64_t isizeW = input.size(2); + + int64_t osizeH = gradOutput_.size(1); + int64_t osizeW = gradOutput_.size(2); + + // bool atomic = (isizeH%osizeH != 0) || (isizeW%osizeW != 0); + + gradInput_c.zero_(); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + input.scalar_type(), + "adaptive_max_pool2d_backward_cuda", + [&] { + scalar_t* gradInput_data = gradInput_c.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput_.const_data_ptr(); + const int64_t* indices_data = indices_.const_data_ptr(); + + // cuda blocks & threads: + int blocksH = (int)(16L / sizeD); + blocksH = blocksH < 1 ? 1 : blocksH; + dim3 blocks(sizeD, blocksH); + dim3 threads(32, 8); + + if (atomic) { + // run updateGradInput kernel, accumulate gradients atomically + atomicadaptivemaxgradinput<<< + blocks, + threads, + 0, + at::cuda::getCurrentCUDAStream()>>>( + gradInput_data, + gradOutput_data, + indices_data, + isizeH, + isizeW, + osizeH, + osizeW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + // run updateGradInput kernel + adaptivemaxgradinput<<< + blocks, + threads, + 0, + at::cuda::getCurrentCUDAStream()>>>( + gradInput_data, + gradOutput_data, + indices_data, + isizeH, + isizeW, + osizeH, + osizeW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); + } else { + int64_t sizeB = input.size(0); + int64_t sizeD = input.size(1); + int64_t isizeH = input.size(2); + int64_t isizeW = input.size(3); + + int64_t osizeH = gradOutput_.size(2); + int64_t osizeW = gradOutput_.size(3); + + gradInput_c.zero_(); + + // bool atomic = (isizeH%osizeH != 0) || (isizeW%osizeW != 0); + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + input.scalar_type(), + "adaptive_max_pool2d_backward_cuda", + [&] { + scalar_t* gradInput_data = gradInput_c.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput_.const_data_ptr(); + const int64_t* indices_data = indices_.const_data_ptr(); + + // cuda blocks & threads: + int blocksH = (int)(16L / sizeD); + blocksH = blocksH < 1 ? 1 : blocksH; + dim3 blocks(sizeB * sizeD, blocksH); + dim3 threads(32, 8); + + if (atomic) { + // run updateGradInput kernel, accumulate gradients atomically + atomicadaptivemaxgradinput<<< + blocks, + threads, + 0, + at::cuda::getCurrentCUDAStream()>>>( + gradInput_data, + gradOutput_data, + indices_data, + isizeH, + isizeW, + osizeH, + osizeW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + // run updateGradInput kernel, accumulate gradients atomically + adaptivemaxgradinput<<< + blocks, + threads, + 0, + at::cuda::getCurrentCUDAStream()>>>( + gradInput_data, + gradOutput_data, + indices_data, + isizeH, + isizeW, + osizeH, + osizeW); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); + } + + if (!gradInput.is_contiguous()) { + gradInput.copy_(gradInput_c); + } + } +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveMaxPooling3d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveMaxPooling3d.cu new file mode 100644 index 0000000000000000000000000000000000000000..f9857de0de57ab53b083edaa2e9f3fe39e013791 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AdaptiveMaxPooling3d.cu @@ -0,0 +1,488 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +#include +#include +#include + + +namespace at::native { + +namespace { + +__device__ inline int64_t start_index(int64_t a, int64_t b, int64_t c) { + return (a / b) * c + ((a % b) * c) / b; +} + +__device__ inline int64_t end_index(int64_t a, int64_t b, int64_t c) { + return 1 + ((a + 1) * c - 1) / b; +} + +// 5d tensor B x D x T x H x W + +/* + * Description: + * this function adaptively maxpools an input 4D tensor along dimensions 2 and 3 + * 4D input, 4D output, 4D argmax x and y + */ + template +__global__ void adaptivemaxpool( + const T *input, T *output, int64_t *indices, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t istrideD, + int64_t istrideT, int64_t istrideH, int64_t istrideW, + int64_t offsetZ) +{ + // iterators on output pixels + int ot, oh, ow; + + // compute offsets based on thread/block ID + int ostartH = blockIdx.y * blockDim.y + threadIdx.y; + int oendH = osizeH; + int ostepH = gridDim.y * blockDim.y; + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + // select output plane + int64_t o_plane = blockIdx.x + offsetZ; + ot = o_plane % osizeT; // output frame/time + int d = o_plane / osizeT; // slice/feature + + // input frame/time ramge is fixed. + int istartT = start_index(ot, osizeT, isizeT); + int iendT = end_index(ot, osizeT, isizeT); + int kT = iendT - istartT; + + // input offset by slice/feature and earliest relevant frame/time + const T *input_dt = input + d*istrideD + istartT*istrideT; + // output offset by slice/feature and frame/time + T *output_dt = output + o_plane*osizeH*osizeW; + // indices offset by slice/feature and frame/time + int64_t *indices_dt = indices + o_plane*osizeH*osizeW; + + // For all output pixels... + for(oh = ostartH; oh < oendH; oh += ostepH) { + + int istartH = start_index(oh, osizeH, isizeH); + int iendH = end_index(oh, osizeH, isizeH); + int kH = iendH - istartH; + + for(ow = ostartW; ow < oendW; ow += ostepW) { + + int istartW = start_index(ow, osizeW, isizeW); + int iendW = end_index(ow, osizeW, isizeW); + int kW = iendW - istartW; + + // Compute the average pooling from corresponding input pixels + const T *ptr_input = input_dt + istartH*istrideH + istartW*istrideW; + T *ptr_output = output_dt + oh*osizeW + ow; + int64_t *ptr_ind = indices_dt + oh*osizeW + ow; + int64_t argmax = istartT*isizeH*isizeW + istartH*isizeW + istartW; + T max = at::numeric_limits::lower_bound(); // -Infinity + + int it, ih, iw; + for(it = 0; it < kT; ++it) { + for(ih = 0; ih < kH; ++ih) { + for(iw = 0; iw < kW; ++iw) { + T val = ptr_input[ih*istrideH + iw*istrideW]; + if ((val > max) || at::_isnan(val)) { + max = val; + argmax = (it+istartT)*isizeH*isizeW + (ih+istartH)*isizeW + iw+istartW; + } + } + } + ptr_input += istrideT; // next input frame + } + // Update output and argmax + *ptr_output = max; + *ptr_ind = argmax; + } + } +} + +template +void adaptivemaxpool_loop( + const scalar_t *input_data, + scalar_t *output_data, + int64_t *indices_data, + int64_t totalZ, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t istrideD, + int64_t istrideT, int64_t istrideH, int64_t istrideW) +{ + int64_t offsetZ = 0; + dim3 threads(32, 8); + // each H*W plane is processed by blocksH thread blocks + int blocksH = std::max((int)(16L / totalZ), 1); + while (totalZ > 0) { + dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); + adaptivemaxpool<<>>( + input_data, output_data, indices_data, isizeT, isizeH, isizeW, + osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW, offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + totalZ -= 65535; + offsetZ += 65535; + } +} + +/* + * Description: + * This function computes the gradInput from gradOutput. + * + * gridDim.y blocks work together on a single 2D output plane specified by + * (blockIdx.x + offsetZ). + * + * Assumes that input size can be perfectly divided by output size, i.e. + * each input pixel can only be argmax of one output pixel. + */ + template +__global__ void adaptivemaxgradinput( + T *gradInput, const T *gradOutput, const int64_t *indices, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t offsetZ +) +{ + // iterators on output pixels + int oh, ow; + + // compute offsets based on thread/block ID + int ostartH = blockIdx.y * blockDim.y + threadIdx.y; + int oendH = osizeH; + int ostepH = gridDim.y * blockDim.y; + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + // select output plane + int64_t o_plane = blockIdx.x + offsetZ; + int d = o_plane / osizeT; // output slice/feature + + // gradInput offset by slice/feature + T *gradInput_d = gradInput + d*isizeT*isizeH*isizeW; + // gradOutput offset by slice/feature and frame/otme + const T *gradOutput_dt = gradOutput + o_plane*osizeH*osizeW; + // indices offset by slice/feature and frame/otme + const int64_t *indices_dt = indices + o_plane*osizeH*osizeW; + + // For all output pixels... + for(oh = ostartH; oh < oendH; oh += ostepH) { + for(ow = ostartW; ow < oendW; ow += ostepW) { + // Compute the gradients for the argmax input pixel + const T *ptr_gradOutput = gradOutput_dt + oh*osizeW + ow; + const int64_t *ptr_ind = indices_dt + oh*osizeW + ow; + T grad_delta = *ptr_gradOutput; + int argmax = (*ptr_ind); + gradInput_d[argmax] += grad_delta; + } + } +} + +template +void adaptivemaxgradinput_loop( + scalar_t *gradInput_data, + const scalar_t *gradOutput_data, + const int64_t *indices_data, + int64_t totalZ, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW) +{ + int64_t offsetZ = 0; + dim3 threads(32, 8); + // each H*W plane is processed by blocksH thread blocks + int blocksH = std::max((int)(16L / totalZ), 1); + while (totalZ > 0) { + dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); + adaptivemaxgradinput<<>>( + gradInput_data, gradOutput_data, indices_data, + isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + totalZ -= 65535; + offsetZ += 65535; + } +} + +/* + * Description: + * This function computes the gradInput from gradOutput. + * + * gridDim.y blocks work together on a single 2D output plane specified by + * (blockIdx.x + offsetZ). + * + * Uses atomic add. + */ + template +__global__ void atomicadaptivemaxgradinput( + T *gradInput, const T *gradOutput, const int64_t *indices, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW, + int64_t offsetZ +) +{ + // iterators on output pixels + int oh, ow; + + // compute offsets based on thread/block ID + int ostartH = blockIdx.y * blockDim.y + threadIdx.y; + int oendH = osizeH; + int ostepH = gridDim.y * blockDim.y; + int ostartW = threadIdx.x; + int oendW = osizeW; + int ostepW = blockDim.x; + + // select output plane + int64_t o_plane = blockIdx.x + offsetZ; + int d = o_plane / osizeT; // output slice/feature + + // gradInput offset by slice/feature + T *gradInput_d = gradInput + d*isizeT*isizeH*isizeW; + // gradOutput offset by slice/feature and frame/otme + const T *gradOutput_dt = gradOutput + o_plane*osizeH*osizeW; + // indices offset by slice/feature and frame/otme + const int64_t *indices_dt = indices + o_plane*osizeH*osizeW; + + // For all output pixels... + for(oh = ostartH; oh < oendH; oh += ostepH) { + for(ow = ostartW; ow < oendW; ow += ostepW) { + // Compute the gradients for the argmax input pixel + const T *ptr_gradOutput = gradOutput_dt + oh*osizeW + ow; + const int64_t *ptr_ind = indices_dt + oh*osizeW + ow; + T grad_delta = *ptr_gradOutput; + int64_t argmax = (*ptr_ind); + gpuAtomicAddNoReturn(&(gradInput_d[argmax]), grad_delta); + } + } +} + +template +void atomicadaptivemaxgradinput_loop( + scalar_t *gradInput_data, + const scalar_t *gradOutput_data, + const int64_t *indices_data, + int64_t totalZ, + int isizeT, int isizeH, int isizeW, + int osizeT, int osizeH, int osizeW) +{ + int64_t offsetZ = 0; + dim3 threads(32, 8); + // each H*W plane is processed by blocksH thread blocks + int blocksH = std::max((int)(16L / totalZ), 1); + while (totalZ > 0) { + dim3 blocks(totalZ > 65535 ? 65535 : totalZ, blocksH); + atomicadaptivemaxgradinput<<>>( + gradInput_data, gradOutput_data, indices_data, + isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + totalZ -= 65535; + offsetZ += 65535; + } +} +} // namespace + +// 5d tensor B x D x T x H x W + +TORCH_IMPL_FUNC(adaptive_max_pool3d_out_cuda) +(const Tensor& input, + IntArrayRef output_size, + const Tensor& output, + const Tensor& indices) { + TensorArg output_arg{output, "output", 1}; + TensorArg indices_arg{indices, "indices", 2}; + TensorArg input_arg{input, "input", 3}; + + checkAllSameGPU( + __func__, {output_arg, indices_arg, input_arg}); + if (input.numel() == 0 || output.numel() == 0) { + return; + } + + int64_t osizeT = output_size[0]; + int64_t osizeH = output_size[1]; + int64_t osizeW = output_size[2]; + + int64_t sizeD, isizeT, isizeH, isizeW; + int64_t istrideD, istrideT, istrideH, istrideW; + int64_t totalZ; + + const Tensor& input_ = input.ndimension() == 4 ? input : input.contiguous(); + + if (input_.ndimension() == 4) { + sizeD = input_.size(0); + isizeT = input_.size(1); + isizeH = input_.size(2); + isizeW = input_.size(3); + + istrideD = input_.stride(0); + istrideT = input_.stride(1); + istrideH = input_.stride(2); + istrideW = input_.stride(3); + + totalZ = sizeD * osizeT; + } else { + int64_t sizeB = input_.size(0); + sizeD = input_.size(1); + isizeT = input_.size(2); + isizeH = input_.size(3); + isizeW = input_.size(4); + + // In the kernel, the batch and channel dimensions are treated as if they + // are flattened and istrideD is used as the stride of this flattened dim + // Handle the edge case where input_.size(1) == 1, where despite passing the + // contiguity check the stride might not be T * H * W + istrideD = isizeT * isizeH * isizeW; + istrideT = input_.stride(2); + istrideH = input_.stride(3); + istrideW = input_.stride(4); + + totalZ = sizeB * sizeD * osizeT; + } + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, input_.scalar_type(), "adaptive_max_pool3d_cuda", [&] { + const scalar_t* input_data = input_.const_data_ptr(); + scalar_t* output_data = output.mutable_data_ptr(); + int64_t* indices_data = indices.mutable_data_ptr(); + + adaptivemaxpool_loop( + input_data, + output_data, + indices_data, + totalZ, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW, + istrideD, + istrideT, + istrideH, + istrideW); + }); +} + +TORCH_IMPL_FUNC(adaptive_max_pool3d_backward_out_cuda) +(const Tensor& gradOutput, + const Tensor& input, + const Tensor& indices, + const Tensor& gradInput) { + TensorArg grad_input_arg{gradInput, "gradInput", 1}; + TensorArg grad_output_arg{gradOutput, "gradOutput", 2}; + TensorArg input_arg{input, "input", 3}; + TensorArg indices_arg{indices, "indices", 4}; + + checkAllSameGPU( + __func__, + {grad_input_arg, grad_output_arg, input_arg, indices_arg}); + if (gradOutput.numel() == 0) { + return; + } + + const Tensor gradOutput_ = gradOutput.contiguous(); + + gradInput.zero_(); + + int64_t sizeD, isizeT, isizeH, isizeW; + int64_t osizeT, osizeH, osizeW; + int64_t totalZ; + + if (input.ndimension() == 4) { + sizeD = input.size(0); + isizeT = input.size(1); + isizeH = input.size(2); + isizeW = input.size(3); + + osizeT = gradOutput_.size(1); + osizeH = gradOutput_.size(2); + osizeW = gradOutput_.size(3); + } else { + sizeD = input.size(1); + isizeT = input.size(2); + isizeH = input.size(3); + isizeW = input.size(4); + + osizeT = gradOutput_.size(2); + osizeH = gradOutput_.size(3); + osizeW = gradOutput_.size(4); + } + + bool atomic = (isizeW % osizeW != 0) || (isizeH % osizeH != 0) || + (isizeT % osizeT != 0); + + if (input.ndimension() == 4) { + totalZ = sizeD * osizeT; + } else { + int sizeB = input.size(0); + totalZ = sizeB * sizeD * osizeT; + } + + if (atomic) { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + input.scalar_type(), + "adaptive_max_pool3d_backward_cuda", + [&] { + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput_.const_data_ptr(); + const int64_t* indices_data = indices.const_data_ptr(); + + atomicadaptivemaxgradinput_loop( + gradInput_data, + gradOutput_data, + indices_data, + totalZ, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + input.scalar_type(), + "adaptive_max_pool3d_backward_cuda", + [&] { + scalar_t* gradInput_data = gradInput.mutable_data_ptr(); + const scalar_t* gradOutput_data = gradOutput_.const_data_ptr(); + const int64_t* indices_data = indices.const_data_ptr(); + + adaptivemaxgradinput_loop( + gradInput_data, + gradOutput_data, + indices_data, + totalZ, + isizeT, + isizeH, + isizeW, + osizeT, + osizeH, + osizeW); + }); + } + } +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AmpKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AmpKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..609e24809457015ff886d3edd0cf3116d1e536c2 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AmpKernels.cu @@ -0,0 +1,252 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#define _USE_MATH_DEFINES + +#include + +#include +#include +#include +#include +#include +#include +#include + + +namespace { +// Thin wrapper around https://docs.nvidia.com/cuda/cuda-math-api/cuda_math_api/group__CUDA__MATH__SINGLE.html, +// to ensure the Cuda math library's isfinite is actually what gets called in +// _amp_non_finite_check_and_unscale_cuda_'s gpu_kernel lambda. +// +// isfinite_ensure_cuda_math is defined outside at::native because: +// - A bare call to "isfinite(val)" inside at::native causes nvcc to prefer the unrelated +// Tensor at::native::isfinite(const Tensor&), resulting in an error: +// "no suitable constructor exists to convert from "float" to "at::Tensor"" +// - Unfortunately, the Cuda math library documentation doesn't say how (or if) you can provide a full namespace path +// to ensure that its version of a particular function is invoked. It only shows bare (not-namespaced) +// calls to its routines inside kernel or device functions. +// - "std::isfinite(val)" in the gpu_kernel lambda causes an "unspecified launch failure" at runtime with cuda 9 on Windows. +// +// isfinite_ensure_cuda_math, declared at file scope outside the at::native region, uses isfinite as math library docs +// suggest and allows disambiguated usage in the lambda within the at::native region. +// GPU_LAMBDA is defined as __host__ __device__ (see Loops.cuh), so I need the __host__ keyword or else nvcc complains that +// "calling a __device__ function("isfinite_ensure_cuda_math") from a __host__ __device__ function("operator()") is not allowed." +static __host__ __device__ __forceinline__ int isfinite_ensure_cuda_math(float val) { + return isfinite(val); +} +} + +namespace at::native { + +namespace { +// Single-tensor fallback for _amp_foreach_non_finite_check_and_unscale_cuda_. +// Handles individual tensors that are acceptable to unscale but not MTA-safe. +void _amp_non_finite_check_and_unscale_cuda_(Tensor& scaled_grad, + Tensor& found_inf, + const Tensor& inv_scale) +{ + // The only way we reach this function is through _amp_foreach_non_finite_check_and_unscale_cuda_, so no input checks. + + // It's not obvious gpu_kernel always guards onto its argument. Guarding here just in case. + const OptionalDeviceGuard device_guard(device_of(scaled_grad)); + + // Acts on scaled_grad in place. + auto iter = TensorIterator::unary_op(scaled_grad, scaled_grad); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + iter.dtype(), + "_amp_non_finite_check_and_unscale_cuda", + [&iter, &found_inf, &inv_scale] { + auto* found_inf_ptr = found_inf.mutable_data_ptr(); + auto* inv_scale_ptr = inv_scale.const_data_ptr(); + + using opmath_t = at::opmath_type; + + gpu_kernel(iter, + [found_inf_ptr, inv_scale_ptr] GPU_LAMBDA (scalar_t val_in) -> scalar_t { + auto val = static_cast(val_in); + if (!isfinite_ensure_cuda_math(val)) { + *found_inf_ptr = 1.f; + } + // Every thread accesses inv_scale, but it will hit in cache. + const auto inv_scale_val = *inv_scale_ptr; + return static_cast(inv_scale_val == 1.f ? val : val * inv_scale_val); + }); + }); +} +} // anonymous namespace + + +// Multiplies each tensor in scaled_grads by inv_scale in-place. +// If any element of any tensor in scaled_grads is inf or NaN, sets found_inf to 1.0. +// Uses multi tensor apply (MTA) to process all MTA-safe tensors. +// +// Args: +// scaled_grads: A TensorList of scaled gradient tensors. May contain infs or NaNs. +// found_inf: A single-element float tensor to which 1.0 will be written if any gradient contain infs/nans. +// Pre-zeroing found_inf, if appropriate, is the responsibility of the caller. +// inv_scale: The inverse of the scale factor by which scaled_grads are currently multiplied. +void _amp_foreach_non_finite_check_and_unscale_cuda_(TensorList scaled_grads, + Tensor& found_inf, + const Tensor& inv_scale) +{ + if (scaled_grads.empty()) { + return; + } + + TORCH_CHECK(inv_scale.is_cuda(), "inv_scale must be a CUDA tensor."); + TORCH_CHECK(found_inf.is_cuda(), "found_inf must be a CUDA tensor."); + TORCH_CHECK(inv_scale.numel() == 1, "inv_scale must be a 1-element tensor."); + TORCH_CHECK(found_inf.numel() == 1, "found_inf must be a 1-element tensor."); + TORCH_CHECK(inv_scale.scalar_type() == at::ScalarType::Float, "inv_scale must be a float tensor."); + TORCH_CHECK(found_inf.scalar_type() == at::ScalarType::Float, "found_inf must be a float tensor."); + + // Ensures client code (GradScaler) filtered scaled_grads by dtype. + check_foreach_api_restrictions(scaled_grads); + + std::vector> tensor_lists; + + // is_non_overlapping_and_dense() is not available in Python. + // GradScaler can't filter for it. We need to filter here. + if (can_use_fast_route(scaled_grads)) { + // Hopefully common case. + // can_use_fast_route is true, which confirms: + // - all scaled_grads are strided + // - all scaled_grads are non overlapping and dense + // - all scaled_grads are on the same device + // - all scaled_grads are of the same dtype + TORCH_CHECK(scaled_grads[0].is_cuda(), "scaled_grads must be CUDA tensors."); + // Sets up MTA launch to use scaled_grads as-is. + tensor_lists.emplace_back(scaled_grads.vec()); + } else { + // Hopefully uncommon case. + // can_use_fast_route is an all-or-nothing check. In this path it was false, + // so any of the above confirmations could have gone wrong. + // We filter MTA-safe tensors into an MTA-able list. + // If a tensor is acceptable but not MTA-safe, we fall back to the TensorIterator kernel. + // If a tensor is unacceptable, we throw an error to blame GradScaler. + tensor_lists.resize(1); + tensor_lists[0].reserve(scaled_grads.size()); + auto expected_device = scaled_grads[0].device(); + const auto expected_dtype = scaled_grads[0].scalar_type(); + for (const Tensor& t : scaled_grads) { + // Ensures GradScaler filtered scaled_grads by device. + TORCH_CHECK(t.is_cuda(), "one of scaled_grads was not a CUDA tensor."); + TORCH_CHECK(t.device() == expected_device, "scaled_grads must be on the same device."); + TORCH_CHECK(t.layout() == at::kStrided, "one of scaled_grads was not a strided tensor."); + if (!t.is_non_overlapping_and_dense() || t.scalar_type() != expected_dtype) { + // t is acceptable but not MTA-safe. Falls back to single-tensor TensorIterator kernel. + _amp_non_finite_check_and_unscale_cuda_(const_cast(t), + found_inf, + inv_scale); + } else { + tensor_lists[0].push_back(t); + } + } + if (tensor_lists[0].size() == 0) { + return; + } + } + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + tensor_lists[0][0].scalar_type(), + "_amp_foreach_non_finite_check_and_unscale_cuda", + [&tensor_lists, &found_inf, &inv_scale] { + auto* found_inf_ptr = found_inf.mutable_data_ptr(); + auto* inv_scale_ptr = inv_scale.const_data_ptr(); + + using opmath_t = at::opmath_type; + + // multi_tensor_apply guards onto tensor_lists[0][0], no need to guard explicitly. + multi_tensor_apply<1>(tensor_lists, + UnaryOpFunctor(), + [found_inf_ptr, inv_scale_ptr] GPU_LAMBDA (opmath_t val) -> opmath_t { + // There is a slight asymmetry here with the TensorIterator kernel above. + // MTA Functors ensure val comes in as opmath_t rather than scalar_t. + if (!isfinite_ensure_cuda_math(val)) { + *found_inf_ptr = 1.f; + } + // Every thread accesses inv_scale, but it will hit in cache. + const auto inv_scale_val = *inv_scale_ptr; + return static_cast(inv_scale_val == 1.f ? val : val * inv_scale_val); + }); + }); +} + + +// amp_update_scale_cuda_kernel is launched with a single thread to compute the new scale. +// The scale factor is maintained and updated on the GPU to avoid synchronization. +__global__ void amp_update_scale_cuda_kernel(float* current_scale, + int* growth_tracker, + const float* found_inf, + double growth_factor, + double backoff_factor, + int growth_interval) +{ + if (*found_inf) { + *current_scale = (*current_scale)*backoff_factor; + *growth_tracker = 0; + } else { + // Entering this branch means we just carried out a successful step, + // so growth_tracker is incremented before comparing to growth_interval. + auto successful = (*growth_tracker) + 1; + if (successful == growth_interval) { + auto new_scale = static_cast((*current_scale)*growth_factor); + // Do not grow the scale past fp32 bounds to inf. + if (isfinite_ensure_cuda_math(new_scale)) { + *current_scale = new_scale; + } + *growth_tracker = 0; + } else { + *growth_tracker = successful; + } + } +} + + +// _amp_update_scale_cuda asynchronously updates the scale tensor in place. +// +// Args: +// current_scale: A one-element cuda float tensor containing the scale value. +// growth_tracker: A one-element torch.cuda.IntTensor containing the number of recent consecutive unskipped steps. +// found_inf: A one-element cuda float tensor. If > 0, indicates that infs/nans were found by the relevant +// prior _amp_non_finite_check_and_unscale_cuda call, and 0 if no infs/nans were found. +// growth_factor: Multiplier if no infs/NaNs were found (typically slightly > 1). +// backoff_factor: Multiplier if infs/NaNs were found (typically 0.5). +// growth_interval: Number of consecutive unskipped steps that must occur for current_scale to be multiplied by +// growth_factor. +// +// Returns: +// current_scale +Tensor& _amp_update_scale_cuda_(Tensor& current_scale, + Tensor& growth_tracker, + const Tensor& found_inf, + double growth_factor, + double backoff_factor, + int64_t growth_interval) +{ + TORCH_CHECK(growth_tracker.is_cuda(), "growth_tracker must be a CUDA tensor."); + TORCH_CHECK(current_scale.is_cuda(), "current_scale must be a CUDA tensor."); + TORCH_CHECK(found_inf.is_cuda(), "found_inf must be a CUDA tensor."); + TORCH_CHECK(growth_tracker.numel() == 1, "growth_tracker must be a 1-element tensor."); + TORCH_CHECK(current_scale.numel() == 1, "current_scale must be a 1-element tensor."); + TORCH_CHECK(found_inf.numel() == 1, "found_inf must be a 1-element tensor."); + TORCH_CHECK(growth_tracker.scalar_type() == at::ScalarType::Int, "growth_tracker must be an int tensor."); + TORCH_CHECK(current_scale.scalar_type() == at::ScalarType::Float, "current_scale must be a float tensor."); + TORCH_CHECK(found_inf.scalar_type() == at::ScalarType::Float, "found_inf must be a float tensor."); + + amp_update_scale_cuda_kernel<<<1, 1, 0, at::cuda::getCurrentCUDAStream()>>>( + current_scale.mutable_data_ptr(), + growth_tracker.mutable_data_ptr(), + found_inf.const_data_ptr(), + growth_factor, + backoff_factor, + growth_interval); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + return current_scale; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AveragePool2d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AveragePool2d.cu new file mode 100644 index 0000000000000000000000000000000000000000..69f3aa49898b10999a45d0353af66a20a66bca6b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AveragePool2d.cu @@ -0,0 +1,470 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::native { +namespace { + +__device__ inline int min(int a, int b) { + return a <= b ? a : b; +} + +__device__ inline int max(int a, int b) { + return a >= b ? a : b; +} + +template +__global__ void avg_pool2d_out_cuda_frame(const int nthreads, + const scalar_t* const bottom_data, const int64_t channels, + const int64_t height, const int64_t width, const int64_t pooled_height, + const int pooled_width, const int kernel_h, const int kernel_w, + const int stride_h, const int stride_w, const int pad_h, const int pad_w, + scalar_t* const top_data, const int divisor_override, + const bool count_include_pad, const bool use_divisor) { + CUDA_KERNEL_LOOP(index, nthreads) { + const int pw = index % pooled_width; + const int ph = (index / pooled_width) % pooled_height; + const int c = (index / pooled_width / pooled_height) % channels; + const int n = index / pooled_width / pooled_height / channels; + int hstart = ph * stride_h - pad_h; + int wstart = pw * stride_w - pad_w; + int hend = min(hstart + kernel_h, height + pad_h); + int wend = min(wstart + kernel_w, width + pad_w); + const int pool_size = (hend - hstart) * (wend - wstart); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + hend = min(hend, height); + wend = min(wend, width); + + if (hstart >= hend || wstart >= wend) { + top_data[index] = scalar_t(0); + continue; + } + + accscalar_t aveval = accscalar_t(0); + const scalar_t* const bottom_slice = bottom_data + (n * channels + c) * height * width; + for (int h = hstart; h < hend; ++h) { + for (int w = wstart; w < wend; ++w) { + aveval += bottom_slice[h * width + w]; + } + } + int divide_factor; + if (use_divisor) { + divide_factor = divisor_override; + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (hend - hstart) * (wend - wstart); + } + } + top_data[index] = static_cast(aveval / divide_factor); + } +} + +template +__global__ void avg_pool2d_out_cuda_frame_nhwc(const int nthreads, + const scalar_t* const bottom_data, const int64_t channels, + const int64_t height, const int64_t width, const int pooled_height, + const int pooled_width, const int kernel_h, const int kernel_w, + const int stride_h, const int stride_w, const int pad_h, const int pad_w, + scalar_t* const top_data, const int divisor_override, + const bool count_include_pad, const bool use_divisor) { + CUDA_KERNEL_LOOP(index, nthreads) { + const int c = index % channels; + const int pw = (index / channels) % pooled_width; + const int ph = (index / channels / pooled_width) % pooled_height; + const int n = index / channels / pooled_width / pooled_height; + int hstart = ph * stride_h - pad_h; + int wstart = pw * stride_w - pad_w; + int hend = min(hstart + kernel_h, height + pad_h); + int wend = min(wstart + kernel_w, width + pad_w); + const int pool_size = (hend - hstart) * (wend - wstart); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + hend = min(hend, height); + wend = min(wend, width); + + if (hstart >= hend || wstart >= wend) { + top_data[index] = scalar_t(0); + continue; + } + + accscalar_t aveval = accscalar_t(0); + const scalar_t* const bottom_slice = bottom_data + n * channels * height * width + c; + for (int h = hstart; h < hend; ++h) { + for (int w = wstart; w < wend; ++w) { + aveval += bottom_slice[(h * width + w) * channels]; + } + } + int divide_factor; + if (use_divisor) { + divide_factor = divisor_override; + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (hend - hstart) * (wend - wstart); + } + } + top_data[index] = static_cast(aveval / divide_factor); + } +} + +template +__global__ void avg_pool2d_backward_out_cuda_frame(const index_t nthreads, const scalar_t* const top_diff, + const int64_t channels, const int64_t height, + const int64_t width, const int64_t pooled_height, const int64_t pooled_width, + const int kernel_h, const int kernel_w, const int stride_h, + const int stride_w, const int pad_h, const int pad_w, + scalar_t* const bottom_diff, const int divisor_override, + bool count_include_pad, bool use_divisor) { + CUDA_KERNEL_LOOP_TYPE(index, nthreads, index_t) { + // find out the local index + // find out the local offset + const int w = index % width + pad_w; + const int h = (index / width) % height + pad_h; + const int c = (index / width / height) % channels; + const int n = index / width / height / channels; + const int phstart = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1; + const int phend = min(h / stride_h + 1, pooled_height); + const int pwstart = (w < kernel_w) ? 0 : (w - kernel_w) / stride_w + 1; + const int pwend = min(w / stride_w + 1, pooled_width); + accscalar_t gradient = accscalar_t(0); + const scalar_t* const top_diff_slice = + top_diff + (n * channels + c) * pooled_height * pooled_width; + for (int ph = phstart; ph < phend; ++ph) { + for (int pw = pwstart; pw < pwend; ++pw) { + // figure out the pooling size + int hstart = ph * stride_h - pad_h; + int wstart = pw * stride_w - pad_w; + int hend = min(hstart + kernel_h, height + pad_h); + int wend = min(wstart + kernel_w, width + pad_w); + int pool_size = (hend - hstart) * (wend - wstart); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + hend = min(hend, height); + wend = min(wend, width); + + if (hstart >= hend || wstart >= wend) { + continue; + } + + int divide_factor; + if (use_divisor) { + divide_factor = divisor_override; + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (hend - hstart) * (wend - wstart); + } + } + gradient += top_diff_slice[ph * pooled_width + pw] / divide_factor; + } + } + bottom_diff[index] = static_cast(gradient); + } +} + +template +__global__ void avg_pool2d_backward_out_cuda_frame_nhwc(const index_t nthreads, + const scalar_t* const top_diff, + const int64_t channels, const int64_t height, + const int64_t width, const int pooled_height, const int pooled_width, + const int kernel_h, const int kernel_w, const int stride_h, + const int stride_w, const int pad_h, const int pad_w, + scalar_t* const bottom_diff, const int divisor_override, + bool count_include_pad, bool use_divisor) { + CUDA_KERNEL_LOOP_TYPE(index, nthreads, index_t) { + const int c = index % channels; + const int w = (index / channels) % width; + const int h = (index / channels / width) % height; + const int n = index / channels / width / height; + + const int phstart = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1; + const int phend = min(h / stride_h + 1, pooled_height); + const int pwstart = (w < kernel_w) ? 0 : (w - kernel_w) / stride_w + 1; + const int pwend = min(w / stride_w + 1, pooled_width); + accscalar_t gradient = accscalar_t(0); + const scalar_t* const top_diff_slice = top_diff + n * channels * pooled_height * pooled_width + c; + for (int ph = phstart; ph < phend; ++ph) { + for (int pw = pwstart; pw < pwend; ++pw) { + // figure out the pooling size + int hstart = ph * stride_h - pad_h; + int wstart = pw * stride_w - pad_w; + int hend = min(hstart + kernel_h, height + pad_h); + int wend = min(wstart + kernel_w, width + pad_w); + int pool_size = (hend - hstart) * (wend - wstart); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + hend = min(hend, height); + wend = min(wend, width); + + if (hstart >= hend || wstart >= wend) { + continue; + } + + int divide_factor; + if (use_divisor) { + divide_factor = divisor_override; + } else { + if(count_include_pad) { + divide_factor = pool_size; + } else { + divide_factor = (hend - hstart) * (wend - wstart); + } + } + gradient += top_diff_slice[(ph * pooled_width + pw) * channels] / divide_factor; + } + } + bottom_diff[index] = static_cast(gradient); + } +} + +} // anonymous namespace + +TORCH_IMPL_FUNC(avg_pool2d_out_cuda) +(const Tensor& input_, + int64_t kH_, + int64_t kW_, + int64_t dH_, + int64_t dW_, + int64_t padH_, + int64_t padW_, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& output) { + TensorArg output_arg{ output, "output", 1 }; + TensorArg input_arg{ input_, "input_", 2 }; + + checkAllSameGPU("avg_pool2d_out_cuda", {output_arg, input_arg}); + + const int kH = c10::checked_convert(kH_, "int"); + const int kW = c10::checked_convert(kW_, "int"); + + const int dH = c10::checked_convert(dH_, "int"); + const int dW = c10::checked_convert(dW_, "int"); + + const int padH = c10::checked_convert(padH_, "int"); + const int padW = c10::checked_convert(padW_, "int"); + + /* sizes */ + const int64_t nInputPlane = input_.size(-3); + const int64_t inputHeight = input_.size(-2); + const int64_t inputWidth = input_.size(-1); + + int64_t outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode); + int64_t outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode); + const auto memory_format = input_.suggest_memory_format(); + + Tensor input = input_.contiguous(memory_format); + + const auto count = c10::checked_convert(output.numel(), "int32_t"); + const uint32_t num_threads = std::min(at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, 1024); + const uint32_t num_blocks = ceil_div(count, num_threads); + + bool use_divisor = divisor_override.has_value(); + const auto divisor_override_value = use_divisor ? divisor_override.value() : 0; + + if (count != 0) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "avg_pool2d_out_cuda_frame", + [&] { + using accscalar_t = acc_type; + + scalar_t *output_data = output.mutable_data_ptr(); + const scalar_t *input_data = input.const_data_ptr(); + + switch (memory_format){ + case MemoryFormat::ChannelsLast: { + output.unsafeGetTensorImpl()->empty_tensor_restride(MemoryFormat::ChannelsLast); + avg_pool2d_out_cuda_frame_nhwc + <<>>( + count, + input_data, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + kH, + kW, + dH, + dW, + padH, + padW, + output_data, + divisor_override_value, + count_include_pad, + use_divisor); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + case MemoryFormat::Contiguous: { + avg_pool2d_out_cuda_frame + <<>>( + count, + input_data, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + kH, + kW, + dH, + dW, + padH, + padW, + output_data, + divisor_override_value, + count_include_pad, + use_divisor); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + default: TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + } + ); + } +} + +TORCH_IMPL_FUNC(avg_pool2d_backward_out_cuda) ( + const Tensor& gradOutput_, + const Tensor& input_, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& gradInput +) { + TensorArg gradInput_arg{ gradInput, "gradInput", 1 }; + TensorArg gradOutput_arg{ gradOutput_, "gradOutput_", 2 }; + TensorArg input_arg{ input_, "input_", 3 }; + + checkAllSameGPU("avg_pool2d_backward_out_cuda", + {gradInput_arg, gradOutput_arg, input_arg}); + + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + const auto memory_format = input_.suggest_memory_format(); + const Tensor input = input_.contiguous(memory_format); + const Tensor gradOutput = gradOutput_.contiguous(memory_format); + + const int64_t nInputPlane = input.size(-3); + const int64_t inputHeight = input.size(-2); + const int64_t inputWidth = input.size(-1); + + const int64_t outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode); + const int64_t outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode); + + + const auto count = input.numel(); + if (count == 0) { + return; + } + + bool use_divisor = divisor_override.has_value(); + const auto divisor_override_value = use_divisor ? divisor_override.value() : 0; + + cudaDeviceProp* properties = at::cuda::getCurrentDeviceProperties(); + const bool gesm10x = properties->major >= 10; + int double_threads = 1024; + if (gesm10x) { + double_threads = 768; + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "avg_pool2d_backward_out_cuda_frame", + [&] { + const uint32_t num_threads = std::min(at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, std::is_same_v ? double_threads : 1024); + const uint32_t num_blocks = ceil_div(count, num_threads); + + using accscalar_t = acc_type; + + const scalar_t *gradOutput_data = gradOutput.const_data_ptr(); + scalar_t *gradInput_data = gradInput.mutable_data_ptr(); + + AT_DISPATCH_INDEX_TYPES( + at::native::canUse32BitIndexMath(input, INT_MAX) ? ScalarType::Int : ScalarType::Long, + "avg_pool2d_backward_out_cuda_frame_launcher", + [&] { + switch (memory_format) { + + case MemoryFormat::ChannelsLast: { + gradInput.unsafeGetTensorImpl()->empty_tensor_restride(MemoryFormat::ChannelsLast); + avg_pool2d_backward_out_cuda_frame_nhwc + <<>>( + count, + gradOutput_data, + nInputPlane, + inputHeight, inputWidth, + outputHeight, outputWidth, + kH, kW, + dH, dW, + padH, padW, + gradInput_data, + divisor_override_value, + count_include_pad, use_divisor); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + case MemoryFormat::Contiguous: { + avg_pool2d_backward_out_cuda_frame + <<>>( + count, + gradOutput_data, + nInputPlane, + inputHeight, inputWidth, + outputHeight, outputWidth, + kH, kW, + dH, dW, + padH, padW, + gradInput_data, + divisor_override_value, + count_include_pad, use_divisor); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + default: TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + }); + }); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AveragePool3d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AveragePool3d.cu new file mode 100644 index 0000000000000000000000000000000000000000..46817cee838e9b033d6ac2c3350e8e50d17fa8e3 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/AveragePool3d.cu @@ -0,0 +1,601 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + + +namespace at::native { +namespace { + +__device__ inline int min(int a, int b) { + return a <= b ? a : b; +} + +__device__ inline int max(int a, int b) { + return a >= b ? a : b; +} + +template +__global__ void avg_pool3d_cuda_update_output( + PackedTensorAccessor64 input, + PackedTensorAccessor64 output, + int kT, int kH, int kW, + int dT, int dH, int dW, + int padT, int padH, int padW, + bool count_include_pad, + int offsetZ, int divisor_override) +{ + int oCol = blockIdx.x * blockDim.x + threadIdx.x; + int oRow = blockIdx.y * blockDim.y + threadIdx.y; + int oFrame = (blockIdx.z + offsetZ) % output.size(1); // output frame/time + int slice = (blockIdx.z + offsetZ) / output.size(1); // output slice/feature + + if (oRow < output.size(2) && oCol < output.size(3)) + { + accscalar_t sum = 0.0; + + int tstart = oFrame * dT - padT; + int hstart = oRow * dH - padH; + int wstart = oCol * dW - padW; + int tend = min(tstart + kT, input.size(1) + padT); + int hend = min(hstart + kH, input.size(2) + padH); + int wend = min(wstart + kW, input.size(3) + padW); + int pool_size = (tend - tstart) * (hend - hstart) * (wend - wstart); + tstart = max(tstart, 0); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + tend = min(tend, input.size(1)); + hend = min(hend, input.size(2)); + wend = min(wend, input.size(3)); + + if (tstart >= tend || hstart >= hend || wstart >= wend) { + output[slice][oFrame][oRow][oCol] = scalar_t(0); + return; + } + + accscalar_t divide_factor; + if (divisor_override) { + divide_factor = static_cast(divisor_override); + } else { + if(count_include_pad) { + divide_factor = static_cast(pool_size); + } else { + divide_factor = static_cast((tend - tstart) * (hend - hstart) * (wend - wstart)); + } + } + + int ti, hi, wi; + for (ti = tstart; ti < tend; ++ti) + { + for (hi = hstart; hi < hend; ++hi) + { + for (wi = wstart; wi < wend; ++wi) + { + const scalar_t val = input[slice][ti][hi][wi]; + sum += val; + } + } + } + + output[slice][oFrame][oRow][oCol] = static_cast(sum / divide_factor); + } +} + +// Inner-most loop size (kW) passed as template parameter for +// performance reasons. +// +template +__global__ void avg_pool3d_cuda_update_output( + PackedTensorAccessor64 input, + PackedTensorAccessor64 output, + int kT, int kH, + int dT, int dH, int dW, + int padT, int padH, int padW, + bool count_include_pad, + int offsetZ, int divisor_override) +{ + int oCol = blockIdx.x * blockDim.x + threadIdx.x; + int oRow = blockIdx.y * blockDim.y + threadIdx.y; + int oFrame = (blockIdx.z + offsetZ) % output.size(1); // output frame/time + int slice = (blockIdx.z + offsetZ) / output.size(1); // output slice/feature + + if (oRow < output.size(2) && oCol < output.size(3)) + { + accscalar_t sum = 0.0; + + int tstart = oFrame * dT - padT; + int hstart = oRow * dH - padH; + int wstart = oCol * dW - padW; + int tend = min(tstart + kT, input.size(1) + padT); + int hend = min(hstart + kH, input.size(2) + padH); + int wend = min(wstart + KERNEL_WIDTH, input.size(3) + padW); + int pool_size = (tend - tstart) * (hend - hstart) * (wend - wstart); + tstart = max(tstart, 0); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + tend = min(tend, input.size(1)); + hend = min(hend, input.size(2)); + wend = min(wend, input.size(3)); + + if (tstart >= tend || hstart >= hend || wstart >= wend) { + output[slice][oFrame][oRow][oCol] = scalar_t(0); + return; + } + + accscalar_t divide_factor; + if (divisor_override) { + divide_factor = static_cast(divisor_override); + } else { + if(count_include_pad) { + divide_factor = static_cast(pool_size); + } else { + divide_factor = static_cast((tend - tstart) * (hend - hstart) * (wend - wstart)); + } + } + + int ti, hi, wi; + for (ti = tstart; ti < tend; ++ti) + { + for (hi = hstart; hi < hend; ++hi) + { + for (wi = wstart; wi < wend; ++wi) + { + const scalar_t val = input[slice][ti][hi][wi]; + sum += val; + } + } + } + + output[slice][oFrame][oRow][oCol] = static_cast(sum / divide_factor); + } +} + +template +__global__ void avg_pool3d_single_backward_out_frame_stride1( + PackedTensorAccessor64 gradOutput, + PackedTensorAccessor64 gradInput, + int kT, int kH, int kW, + accscalar_t normFactor, + int offsetZ) +{ + int iCol = blockIdx.x * blockDim.x + threadIdx.x; + int iRow = blockIdx.y * blockDim.y + threadIdx.y; + int iFrame = (blockIdx.z + offsetZ) % gradInput.size(1); // input frame/time + int slice = (blockIdx.z + offsetZ) / gradInput.size(1); // input slice/feature + + // guard against over-tiled threads + if (iRow < gradInput.size(2) && iCol < gradInput.size(3)) + { + accscalar_t sum = 0.0; + const scalar_t *gOut = &gradOutput[slice][max(0, iFrame - kT + 1)] + [max(0, iRow - kH + 1)][max(0, iCol - kW + 1)]; + int frameOffset = 0; + for (int oFrame = max(0, iFrame - kT + 1); + oFrame < min(iFrame + 1, gradOutput.size(1)); + ++oFrame) + { + int rowOffset = frameOffset; + for (int oRow = max(0, iRow - kH + 1); + oRow < min(iRow + 1, gradOutput.size(2)); + ++oRow) + { + int colOffset = rowOffset; + for (int oCol = max(0, iCol - kW + 1); + oCol < min(iCol + 1, gradOutput.size(3)); + ++oCol) + { + sum += gOut[colOffset]; + ++colOffset; + } + rowOffset += gradOutput.size(3); + } + frameOffset += gradOutput.size(2) * gradOutput.size(3); + } + gradInput[slice][iFrame][iRow][iCol] = static_cast(sum * normFactor); + } +} + +template +__global__ void avg_pool3d_cuda_update_grad_input_atomic( + PackedTensorAccessor64 gradOutput, + PackedTensorAccessor64 gradInput, + int kT, int kH, int kW, + int dT, int dH, int dW, + int padT, int padH, int padW, + bool count_include_pad, + int offsetZ, int divisor_override, const int gradInput_numel) +{ + int oCol = blockIdx.x * blockDim.x + threadIdx.x; + int oRow = blockIdx.y * blockDim.y + threadIdx.y; + int oFrame = (blockIdx.z + offsetZ) % gradOutput.size(1); // gradOutput frame/time + int slice = (blockIdx.z + offsetZ) / gradOutput.size(1); // gradOutput slice/feature + + // guard against over-tiled threads + if (oRow < gradOutput.size(2) && oCol < gradOutput.size(3)) + { + int tstart = oFrame * dT - padT; + int hstart = oRow * dH - padH; + int wstart = oCol * dW - padW; + int tend = min(tstart + kT, gradInput.size(1) + padT); + int hend = min(hstart + kH, gradInput.size(2) + padH); + int wend = min(wstart + kW, gradInput.size(3) + padW); + int pool_size = (tend - tstart) * (hend - hstart) * (wend - wstart); + tstart = max(tstart, 0); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + tend = min(tend, gradInput.size(1)); + hend = min(hend, gradInput.size(2)); + wend = min(wend, gradInput.size(3)); + + accscalar_t divide_factor; + if (divisor_override) { + divide_factor = static_cast(divisor_override); + } else { + if(count_include_pad) { + divide_factor = static_cast(pool_size); + } else { + divide_factor = static_cast((tend - tstart) * (hend - hstart) * (wend - wstart)); + } + } + + scalar_t val = static_cast( + static_cast(gradOutput[slice][oFrame][oRow][oCol]) / divide_factor); + for (int iFrame = tstart; iFrame < tend; ++iFrame) + { + for (int iRow = hstart; iRow < hend; ++iRow) + { + for (int iCol = wstart; iCol < wend; ++iCol) + { + const int index = slice * gradInput.stride(0) + iFrame * gradInput.stride(1) + iRow * gradInput.stride(2) + iCol * gradInput.stride(3); + fastAtomicAdd(gradInput.data(), index, gradInput_numel, val, true); + } + } + } + } +} + +template +__global__ void avg_pool3d_cuda_update_grad_input( + PackedTensorAccessor64 gradOutput, + PackedTensorAccessor64 gradInput, + int kT, int kH, int kW, + int dT, int dH, int dW, + int padT, int padH, int padW, + bool count_include_pad, int offsetZ, int divisor_override) +{ + int oCol = blockIdx.x * blockDim.x + threadIdx.x; + int oRow = blockIdx.y * blockDim.y + threadIdx.y; + int oFrame = (blockIdx.z + offsetZ) % gradOutput.size(1); // gradOutput frame/time + int slice = (blockIdx.z + offsetZ) / gradOutput.size(1); // gradOutput slice/feature + + // guard against over-tiled threads + if (oRow < gradOutput.size(2) && oCol < gradOutput.size(3)) + { + int tstart = oFrame * dT - padT; + int hstart = oRow * dH - padH; + int wstart = oCol * dW - padW; + int tend = min(tstart + kT, gradInput.size(1) + padT); + int hend = min(hstart + kH, gradInput.size(2) + padH); + int wend = min(wstart + kW, gradInput.size(3) + padW); + int pool_size = (tend - tstart) * (hend - hstart) * (wend - wstart); + tstart = max(tstart, 0); + hstart = max(hstart, 0); + wstart = max(wstart, 0); + tend = min(tend, gradInput.size(1)); + hend = min(hend, gradInput.size(2)); + wend = min(wend, gradInput.size(3)); + + accscalar_t divide_factor; + if (divisor_override) { + divide_factor = static_cast(divisor_override); + } else { + if(count_include_pad) { + divide_factor = static_cast(pool_size); + } else { + divide_factor = static_cast((tend - tstart) * (hend - hstart) * (wend - wstart)); + } + } + + scalar_t val = static_cast( + static_cast(gradOutput[slice][oFrame][oRow][oCol]) / divide_factor); + for (int iFrame = tstart; iFrame < tend; ++iFrame) + { + for (int iRow = hstart; iRow < hend; ++iRow) + { + for (int iCol = wstart; iCol < wend; ++iCol) + { + gradInput[slice][iFrame][iRow][iCol] = val; + } + } + } + } +} + +} // anonymous namespace + +#define LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(KW) case KW: \ + avg_pool3d_cuda_update_output \ + <<>>( \ + work_input.packed_accessor64(), \ + work_output.packed_accessor64(), \ + kT, kH, \ + dT, dH, dW, \ + padT, padH, padW, \ + count_include_pad, \ + offsetZ, divisor); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + break + + +TORCH_IMPL_FUNC(avg_pool3d_out_cuda) ( + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& output +) { + TensorArg output_arg{ output, "output", 1 }; + TensorArg input_arg{ input, "input", 2 }; + + checkAllSameGPU(__func__, {output_arg, input_arg}); + + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + const int padT = c10::checked_convert(padding[0], "int"); + const int padH = padding.size() == 1 ? padT : c10::checked_convert(padding[1], "int"); + const int padW = padding.size() == 1 ? padT : c10::checked_convert(padding[2], "int"); + + // if divisor==0 then we will ignore it + int64_t divisor = 0; + if (divisor_override.has_value()) { + divisor = divisor_override.value(); + } + + const int64_t nbatch = input.ndimension() == 5 ? input.size(-5) : 1; + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + const int64_t otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode); + const int64_t oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode); + const int64_t owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode); + + Tensor work_input = input.contiguous(); + Tensor work_output = output; + if (input.ndimension() == 5) { + // Collapse batch and feature dimensions. + work_input = work_input.reshape({nbatch * nslices, itime, iheight, iwidth}); + work_output = work_output.reshape({nbatch * nslices, otime, oheight, owidth}); + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), + "avg_pool3d_out_cuda", + [&] { + using accscalar_t = acc_type; + int64_t totalZ = otime * nslices * nbatch; + int64_t offsetZ = 0; + dim3 block(32, 8); + + while (totalZ > 0) { + dim3 grid(ceil_div(owidth, static_cast(block.x)), + ceil_div(oheight, static_cast(block.y)), + totalZ > 65535 ? 65535 : totalZ); + + switch (kW) { + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(1); + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(2); + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(3); + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(4); + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(5); + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(6); + LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH(7); + default: + avg_pool3d_cuda_update_output + <<>>( + work_input.packed_accessor64(), + work_output.packed_accessor64(), + kT, kH, kW, + dT, dH, dW, + padT, padH, padW, + count_include_pad, + offsetZ, divisor); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + + totalZ -= 65535; + offsetZ += 65535; + } + } + ); +} + +#undef LAUNCH_UPDATE_OUTPUT_KERNEL_WIDTH + + +TORCH_IMPL_FUNC(avg_pool3d_backward_out_cuda) ( + const Tensor& gradOutput, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + bool ceil_mode, + bool count_include_pad, + std::optional divisor_override, + const Tensor& gradInput +) { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("avg_pool3d_backward_cuda"); + + TensorArg gradInput_arg{ gradInput, "gradInput", 1 }; + TensorArg gradOutput_arg{ gradOutput, "gradOutput", 2 }; + TensorArg input_arg{ input, "input", 3 }; + + checkAllSameGPU(__func__, + {gradInput_arg, gradOutput_arg, input_arg}); + + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + const int padT = c10::checked_convert(padding[0], "int"); + const int padH = padding.size() == 1 ? padT : c10::checked_convert(padding[1], "int"); + const int padW = padding.size() == 1 ? padT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK((gradOutput.ndimension() == 4 || gradOutput.ndimension() == 5), + "non-empty 4D or 5D (batch mode) tensor expected for gradOutput"); + + // if divisor==0 then we will ignore it + int64_t divisor = 0; + if (divisor_override.has_value()) { + divisor = divisor_override.value(); + } + + gradInput.zero_(); + + const int64_t nbatch = input.ndimension() == 5 ? input.size(-5) : 1; + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + const int64_t otime = gradOutput.size(-3); + const int64_t oheight = gradOutput.size(-2); + const int64_t owidth = gradOutput.size(-1); + + const bool kernelsOverlap = (dT < kT) || (dH < kH) || (dW < kW); + + Tensor work_grad_input = gradInput; + Tensor work_grad_output = gradOutput.contiguous(); + + if (input.ndimension() == 5) { + // Collapse batch and feature dimensions. + work_grad_input = work_grad_input.reshape({nbatch * nslices, itime, iheight, iwidth}); + work_grad_output = work_grad_output.reshape({nbatch * nslices, otime, oheight, owidth}); + } + + + // Optimizing for stride 1 is probably only of limited value, but this + // specialization yields 3x speedup over the gpuAtomicAdd implementation. + // Padding must be 0, otherwise, pool size may change. + if (dT == 1 && dH == 1 && dW == 1 && padT == 0 && padH == 0 && padW == 0) { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "avg_pool3d_backward_out_frame_stride1", + [&] { + using accscalar_t = acc_type; + int64_t totalZ = itime * nslices * nbatch; + int64_t offsetZ = 0; + dim3 block(32, 8); + + accscalar_t divide_factor; + if (divisor) { + divide_factor = static_cast(divisor); + } else { + divide_factor = static_cast(kT * kH * kW); + } + + while (totalZ > 0) { + dim3 grid(ceil_div(iwidth, static_cast(block.x)), + ceil_div(iheight, static_cast(block.y)), + totalZ > 65535 ? 65535 : totalZ); + + avg_pool3d_single_backward_out_frame_stride1 + <<>>( + work_grad_output.packed_accessor64(), + work_grad_input.packed_accessor64(), + kT, kH, kW, + 1.0f/divide_factor, + offsetZ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + totalZ -= 65535; + offsetZ += 65535; + } + } + ); + } + else { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "avg_pool3d_backward_out_frame", + [&] { + using accscalar_t = acc_type; + int64_t totalZ = otime * nslices * nbatch; + int64_t offsetZ = 0; + dim3 block(32, 8); + + while (totalZ > 0) { + dim3 grid(ceil_div(owidth, static_cast(block.x)), + ceil_div(oheight, static_cast(block.y)), + totalZ > 65535 ? 65535 : totalZ); + + if (kernelsOverlap) { + avg_pool3d_cuda_update_grad_input_atomic + <<>>( + work_grad_output.packed_accessor64(), + work_grad_input.packed_accessor64(), + kT, kH, kW, + dT, dH, dW, + padT, padH, padW, + count_include_pad, + offsetZ, divisor, work_grad_input.numel()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + else { + avg_pool3d_cuda_update_grad_input + <<>>( + work_grad_output.packed_accessor64(), + work_grad_input.packed_accessor64(), + kT, kH, kW, + dT, dH, dW, + padT, padH, padW, + count_include_pad, + offsetZ, divisor); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + + totalZ -= 65535; + offsetZ += 65535; + } + } + ); + } +} + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BatchLinearAlgebraEig.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BatchLinearAlgebraEig.cu new file mode 100644 index 0000000000000000000000000000000000000000..63c96b95f2fdc5f0734d84ca6af49d510165755a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BatchLinearAlgebraEig.cu @@ -0,0 +1,119 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS + +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ linalg_eig_make_complex_eigenvectors ~~~~~~~~~~~~~~~~~~~~~~~ + +// Processes all columns in parallel. For complex conjugate pairs, each thread +// reads from neighboring columns but writes only to its own column. +template +__global__ void linalg_eig_make_complex_eigenvectors_kernel( + c10::complex* __restrict__ result, + const c10::complex* __restrict__ eigenvalues, + const scalar_t* __restrict__ vectors, + const int64_t batch_size, + const int64_t n, + const int64_t matrix_stride) { + + const int64_t idx = blockIdx.x * blockDim.x + threadIdx.x; + const int64_t total_elements = batch_size * n * n; + + if (idx >= total_elements) return; + + const int64_t batch_idx = idx / (n * n); + const int64_t local_idx = idx % (n * n); + const int64_t col = local_idx / n; + const int64_t row = local_idx % n; + + const auto* batch_eigenvalues = eigenvalues + batch_idx * n; + const auto* batch_vectors = vectors + batch_idx * matrix_stride; + auto* batch_result = result + batch_idx * matrix_stride; + + const auto eigenvalue = batch_eigenvalues[col]; + + if (eigenvalue.imag() == scalar_t(0)) { + batch_result[col * n + row] = c10::complex( + batch_vectors[col * n + row], + scalar_t(0)); + } else if (eigenvalue.imag() > scalar_t(0)) { + batch_result[col * n + row] = c10::complex( + batch_vectors[col * n + row], + batch_vectors[(col + 1) * n + row]); + } else { + batch_result[col * n + row] = c10::complex( + batch_vectors[(col - 1) * n + row], + -batch_vectors[col * n + row]); + } +} + +template +void linalg_eig_make_complex_eigenvectors_cuda_impl( + const Tensor& complex_vectors, + const Tensor& complex_values, + const Tensor& real_vectors) { + + const auto n = real_vectors.size(-1); + const auto matrix_stride = matrixStride(real_vectors); + const auto batch_size = batchCount(real_vectors); + + if (batch_size == 0 || n == 0) return; + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(complex_vectors.mT().is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(complex_values.is_contiguous()); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(real_vectors.mT().is_contiguous()); + + const int64_t total_elements = batch_size * n * n; + + const int threads = 256; + const int blocks = (total_elements + threads - 1) / threads; + + auto* result_ptr = complex_vectors.data_ptr>(); + const auto* eigenvalues_ptr = complex_values.const_data_ptr>(); + const auto* vectors_ptr = real_vectors.const_data_ptr(); + + linalg_eig_make_complex_eigenvectors_kernel + <<>>( + result_ptr, + eigenvalues_ptr, + vectors_ptr, + batch_size, + n, + matrix_stride); + + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +void linalg_eig_make_complex_eigenvectors_cuda( + const Tensor& complex_vectors, + const Tensor& complex_values, + const Tensor& real_vectors) { + + TORCH_INTERNAL_ASSERT(complex_vectors.is_cuda()); + TORCH_INTERNAL_ASSERT(complex_values.is_cuda()); + TORCH_INTERNAL_ASSERT(real_vectors.is_cuda()); + + c10::cuda::CUDAGuard device_guard(real_vectors.device()); + + AT_DISPATCH_V2( + real_vectors.scalar_type(), + "linalg_eig_make_complex_eigenvectors_cuda", + AT_WRAP([&] { + linalg_eig_make_complex_eigenvectors_cuda_impl( + complex_vectors, complex_values, real_vectors); + }), + AT_EXPAND(AT_FLOATING_TYPES)); +} + +} // anonymous namespace + +REGISTER_CUDA_DISPATCH(linalg_eig_make_complex_eigenvectors_stub, &linalg_eig_make_complex_eigenvectors_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryBitwiseOpsKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryBitwiseOpsKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..d898eccc94f3301de76ad599f4d7231d44f9c762 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryBitwiseOpsKernels.cu @@ -0,0 +1,81 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +template +struct BitwiseAndFunctor { + __device__ __forceinline__ scalar_t operator()(scalar_t a, scalar_t b) const { + return a & b; + } +}; + +template<> +struct BitwiseAndFunctor { + __device__ __forceinline__ bool operator()(bool a, bool b) const { + return a && b; + } +}; + +void bitwise_and_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES_AND(kBool, iter.dtype(), "bitwise_and_cuda", [&]() { + BitwiseAndFunctor f; + opmath_symmetric_gpu_kernel_with_scalars(iter, f); + }); +} + +template +struct BitwiseOrFunctor { + __device__ __forceinline__ scalar_t operator()(scalar_t a, scalar_t b) const { + return a | b; + } +}; + +template<> +struct BitwiseOrFunctor { + __device__ __forceinline__ bool operator()(bool a, bool b) const { + return a || b; + } +}; + +void bitwise_or_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES_AND(kBool, iter.dtype(), "bitwise_or_cuda", [&]() { + BitwiseOrFunctor f; + opmath_symmetric_gpu_kernel_with_scalars(iter, f); + }); +} + +template +struct BitwiseXorFunctor { + __device__ __forceinline__ scalar_t operator()(scalar_t a, scalar_t b) const { + return a ^ b; + } +}; + +template<> +struct BitwiseXorFunctor { + __device__ __forceinline__ bool operator()(bool a, bool b) const { + return a != b; + } +}; + +void bitwise_xor_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES_AND(kBool, iter.dtype(), "bitwise_xor_cuda", [&]() { + BitwiseXorFunctor f; + opmath_symmetric_gpu_kernel_with_scalars(iter, f); + }); +} + +REGISTER_DISPATCH(bitwise_and_stub, &bitwise_and_kernel_cuda) +REGISTER_DISPATCH(bitwise_or_stub, &bitwise_or_kernel_cuda) +REGISTER_DISPATCH(bitwise_xor_stub, &bitwise_xor_kernel_cuda) + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivFloorKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivFloorKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..b2ae2ce4b5155b6eadb93ee836bed1dd5e403f84 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivFloorKernel.cu @@ -0,0 +1,82 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native { +namespace binary_internal { + +void div_floor_kernel_cuda(TensorIteratorBase& iter) { + // See NOTE: [Floor Division in Python] + const auto dtype = iter.common_dtype(); + if (dtype == kByte) { + // In the special case of unsigned integer division, floor division is + // equivalent to truncation division (since the signs of the divisor and + // dividend are always the same) + return div_trunc_kernel_cuda(iter); + } else if (isIntegralType(dtype, /*includeBool*/ false)) { + AT_DISPATCH_INTEGRAL_TYPES(dtype, "div_floor_cuda", [&]() { + gpu_kernel_with_scalars( + iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return c10::div_floor_integer(a, b); + }); + }); + } else if (iter.is_cpu_scalar(2)) { + // optimization for floating-point types: if the second operand is a CPU + // scalar, compute a * reciprocal(b). Note that this may lose one bit of + // precision compared to computing the division. + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, dtype, "div_floor_cuda", [&]() { + using accscalar_t = at::acc_type; + auto b = iter.scalar_value(2); + if (C10_UNLIKELY(b == 0)) { + return div_true_kernel_cuda(iter); + } + + auto inv_b = accscalar_t(1.0) / b; + iter.remove_operand(2); + gpu_kernel(iter, [b, inv_b] GPU_LAMBDA(scalar_t a) -> scalar_t { + auto mod = std::fmod(a, b); + auto div = (a - mod) * inv_b; + if ((mod != 0) && (b < 0) != (mod < 0)) { + div -= scalar_t(1); + } + + scalar_t floordiv; + if (div != 0) { + floordiv = std::floor(div); + if (div - floordiv > scalar_t(0.5)) { + floordiv += scalar_t(1.0); + } + } else { + floordiv = c10::cuda::compat::copysign(scalar_t(0), a * inv_b); + } + return floordiv; + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, dtype, "div_floor_cuda", [&]() { + gpu_kernel_with_scalars( + iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return c10::div_floor_floating(a, b); + }); + }); + } +} +} // namespace binary_internal + +REGISTER_DISPATCH(div_floor_stub, &binary_internal::div_floor_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..54519972edbbe71e94a6111104349aad7542d9ff --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu @@ -0,0 +1,65 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native { +namespace binary_internal { + +constexpr char div_name[] = "div_kernel"; +void div_true_kernel_cuda(TensorIteratorBase& iter) { + auto common_dtype = iter.common_dtype(); + if (iter.common_dtype() == kComplexHalf) { + using scalar_t = c10::complex; +#if AT_USE_JITERATOR() + static const auto div_string = jiterator_stringify( + template T div_kernel(T a, T b) { return a / b; }); + opmath_jitted_gpu_kernel_with_scalars( + iter, div_string); +#else + using opmath_t = at::opmath_type; + opmath_gpu_kernel_with_scalars(iter, DivFunctor()); +#endif + return; + } + if (iter.is_cpu_scalar(2)) { + // optimization for floating-point types: if the second operand is a CPU + // scalar, compute a * reciprocal(b). Note that this may lose one bit of + // precision compared to computing the division. + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + kHalf, kBFloat16, common_dtype, "div_true_cuda", [&]() { + using opmath_t = at::opmath_type; + using high_prec_t = std::conditional_t< + c10::is_complex::value, + c10::complex, + double>; + auto inv_b = static_cast(high_prec_t(1.0) / iter.scalar_value(2)); + iter.remove_operand(2); + gpu_kernel( + iter, + BUnaryFunctor>( + MulFunctor(), inv_b)); + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + kHalf, kBFloat16, common_dtype, "div_true_cuda", [&]() { + DivFunctor f; + gpu_kernel_with_scalars(iter, f); + }); + } +} +} // namespace binary_internal + +REGISTER_DISPATCH(div_true_stub, &binary_internal::div_true_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivTruncKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivTruncKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..f1379d282ba9573c82a996a58b3fce58a9cb5f5b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryDivTruncKernel.cu @@ -0,0 +1,53 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native { +namespace binary_internal { + +void div_trunc_kernel_cuda(TensorIteratorBase& iter) { + auto dtype = iter.common_dtype(); + if (isIntegralType(dtype, /*includeBool*/ false)) { + AT_DISPATCH_INTEGRAL_TYPES(dtype, "div_trunc_cuda", [&]() { + gpu_kernel_with_scalars( + iter, + [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return a / b; }); + }); + } else if (iter.is_cpu_scalar(2)) { + // optimization for floating-point types: if the second operand is a CPU + // scalar, compute a * reciprocal(b). Note that this may lose one bit of + // precision compared to computing the division. + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, dtype, "div_trunc_cuda", [&]() { + using accscalar_t = at::acc_type; + auto inv_b = accscalar_t(1.0) / iter.scalar_value(2); + iter.remove_operand(2); + gpu_kernel(iter, [inv_b] GPU_LAMBDA(scalar_t a) -> scalar_t { + return std::trunc(a * inv_b); + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, kBFloat16, dtype, "div_trunc_cuda", [&]() { + gpu_kernel_with_scalars( + iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return std::trunc(a / b); + }); + }); + } +} +} // namespace binary_internal + +REGISTER_DISPATCH(div_trunc_stub, &binary_internal::div_trunc_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryGeometricKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryGeometricKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..1cbe9a087b7addf6f0c5970dc426ee59b329faa0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryGeometricKernels.cu @@ -0,0 +1,39 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +void atan2_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, at::ScalarType::BFloat16, + iter.common_dtype(), "atan2_cuda", + [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return ::atan2(a, b); + }); + }); +} + +void hypot_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, at::ScalarType::BFloat16, + iter.common_dtype(), "hypot_cuda", + [&]() { + opmath_symmetric_gpu_kernel_with_scalars( + iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return ::hypot(a, b); + }); + }); +} + +REGISTER_DISPATCH(atan2_stub, &atan2_kernel_cuda) +REGISTER_DISPATCH(hypot_stub, &hypot_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryInternal.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryInternal.h new file mode 100644 index 0000000000000000000000000000000000000000..e288f7d9ad74529d111776bd1c0a16572bee57eb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryInternal.h @@ -0,0 +1,44 @@ +// DON'T include this except from Binary*.cu files. It should not leak into +// headers. +#pragma once +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace at::native::binary_internal { + +template +struct DivFunctor { + __device__ scalar_t operator()(scalar_t a, scalar_t b) const { + return a / b; + } +}; + +template +struct MulFunctor { + __device__ T operator()(T a, T b) const { + return a * b; + } +}; + +// Workaround for the error: '*' in boolean context, suggest '&&' instead +// [-Werror=int-in-bool-context] +template <> +struct MulFunctor { + __device__ bool operator()(bool a, bool b) const { + return a && b; + } +}; +void div_true_kernel_cuda(TensorIteratorBase& iter); +void div_trunc_kernel_cuda(TensorIteratorBase& iter); +} // namespace at::native::binary_internal diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryLogicalOpsKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryLogicalOpsKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..53dd87b8afa825a1fa4ecc21869389326cf2ae84 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryLogicalOpsKernels.cu @@ -0,0 +1,128 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +constexpr char logical_and_name[] = "logical_and_kernel"; +void logical_and_kernel_cuda(TensorIterator& iter) { + auto dtype = iter.common_dtype(); + if (at::isComplexType(dtype)) { +#if AT_USE_JITERATOR() + static const auto logical_and_string = jiterator_stringify( + template + bool logical_and_kernel(T a, T b) { + return a && b; + } + ); // logical_and_string + AT_DISPATCH_COMPLEX_TYPES(dtype, "logical_and_cuda", [&]() { + jitted_gpu_kernel< + /*name=*/ logical_and_name, + /*return_dtype=*/ scalar_t, + /*common_dtype=*/ scalar_t, + /*arity=*/ 2>(iter, logical_and_string); + }); // logical_and_string +#else + AT_DISPATCH_COMPLEX_TYPES(dtype, "logical_and_cuda", [&]() { + opmath_symmetric_gpu_kernel_with_scalars( + iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> bool { + return a && b; + }); + }); +#endif + } else { + AT_DISPATCH_ALL_TYPES_AND3(kHalf, kBool, ScalarType::BFloat16, + dtype, "logical_and_cuda", [&]() { + opmath_symmetric_gpu_kernel_with_scalars( + iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> bool { + return a && b; + }); + }); + } +} + +constexpr char logical_or_name[] = "logical_or_kernel"; +void logical_or_kernel_cuda(TensorIterator& iter) { + auto dtype = iter.common_dtype(); + if (at::isComplexType(dtype)) { +#if AT_USE_JITERATOR() + static const auto logical_or_string = jiterator_stringify( + template + bool logical_or_kernel(T a, T b) { + return a || b; + } + ); // logical_or_string + AT_DISPATCH_COMPLEX_TYPES(dtype, "logical_or_cuda", [&]() { + jitted_gpu_kernel< + /*name=*/ logical_or_name, + /*return_dtype=*/ scalar_t, + /*common_dtype=*/ scalar_t, + /*arity=*/ 2>(iter, logical_or_string); + }); +#else + AT_DISPATCH_COMPLEX_TYPES(dtype, "logical_or_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> bool { + return a || b; + }); + }); +#endif + } else { + AT_DISPATCH_ALL_TYPES_AND3(kHalf, kBool, ScalarType::BFloat16, + dtype, "logical_or_cuda", [&]() { + opmath_symmetric_gpu_kernel_with_scalars( + iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> bool { + return a || b; + }); + }); + } +} + +constexpr char logical_xor_name[] = "logical_xor_kernel"; +void logical_xor_kernel_cuda(TensorIterator& iter) { + auto dtype = iter.common_dtype(); + if (at::isComplexType(dtype)) { +#if AT_USE_JITERATOR() + static const auto logical_xor_string = jiterator_stringify( + template + bool logical_xor_kernel(T a, T b) { + return bool(a) != bool(b); + } + ); + AT_DISPATCH_COMPLEX_TYPES(dtype, "logical_xor_cuda", [&]() { + jitted_gpu_kernel< + /*name=*/ logical_xor_name, + /*return_dtype=*/ scalar_t, + /*common_dtype=*/ scalar_t, + /*arity=*/ 2>(iter, logical_xor_string); + }); // logical_xor_string +#else + AT_DISPATCH_COMPLEX_TYPES(dtype, "logical_xor_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> bool { + return bool(a) != bool(b); + }); + }); +#endif + } else { + AT_DISPATCH_ALL_TYPES_AND3(kHalf, kBool, ScalarType::BFloat16, + dtype, "logical_xor_cuda", [&]() { + opmath_symmetric_gpu_kernel_with_scalars( + iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> bool { + return bool(a) != bool(b); + }); + }); + } +} + +REGISTER_DISPATCH(logical_and_stub, &logical_and_kernel_cuda) +REGISTER_DISPATCH(logical_or_stub, &logical_or_kernel_cuda) +REGISTER_DISPATCH(logical_xor_stub, &logical_xor_kernel_cuda) + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMiscBackwardOpsKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMiscBackwardOpsKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..5cbaa89580dfe9aa0c06a591027a3d9bf9cd5381 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMiscBackwardOpsKernels.cu @@ -0,0 +1,131 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include + +#include + +#include +#include +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +constexpr char sigmoid_backward_name[] = "sigmoid_backward"; +void sigmoid_backward_kernel_cuda(TensorIteratorBase& iter) { + auto dtype = iter.dtype(); + if(isComplexType(dtype)) { +#if AT_USE_JITERATOR() + static const auto sigmoid_backward_string = jiterator_stringify( + template + T sigmoid_backward(T a, T b) { + return a * std::conj((T{1.} - b) * b); + } + ); // sigmoid_backward_string + AT_DISPATCH_COMPLEX_TYPES_AND(kComplexHalf, dtype, "sigmoid_backward_cuda", [&]() { + jitted_gpu_kernel< + /*name=*/ sigmoid_backward_name, + /*return_dtype=*/ scalar_t, + /*common_dtype=*/ scalar_t, + /*arity=*/ 2>(iter, sigmoid_backward_string); + }); +#else + AT_DISPATCH_COMPLEX_TYPES_AND(kComplexHalf, dtype, "sigmoid_backward_cuda", [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + using comp_t = at::opmath_type; + const auto one = comp_t{1.}; + const auto comp_b = static_cast(b); + const auto comp_a = static_cast(a); + return static_cast(comp_a * std::conj((one - comp_b) * comp_b)); + }); + }); +#endif + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, dtype, "sigmoid_backward_cuda", [&]() { + gpu_kernel(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return a * (scalar_t(1.) - b) * b; + }); + }); + } +} + +void logit_backward_kernel_cuda(TensorIteratorBase& iter, const Scalar& eps_scalar) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + iter.dtype(), + "logit_cuda", + [&]() { + using T_ACC = acc_type; + const T_ACC eps = eps_scalar.to(); + if (eps < T_ACC(0)) { + gpu_kernel( + iter, [] GPU_LAMBDA(scalar_t dy, scalar_t x) -> scalar_t { + const T_ACC dy_acc = static_cast(dy); + const T_ACC x_acc = static_cast(x); + return (x_acc < T_ACC(0) || x_acc > T_ACC(1)) + ? std::numeric_limits::quiet_NaN() + : dy_acc / (x_acc * (T_ACC(1) - x_acc)); + }); + } else { + const T_ACC lo = eps; + const T_ACC hi = T_ACC(1) - eps; + gpu_kernel( + iter, [lo, hi] GPU_LAMBDA(scalar_t dy, scalar_t x) -> scalar_t { + const T_ACC dy_acc = static_cast(dy); + const T_ACC x_acc = static_cast(x); + return (x_acc < lo || x_acc > hi) + ? T_ACC(0) + : dy_acc / (x_acc * (T_ACC(1) - x_acc)); + }); + } + }); +} + +constexpr char tanh_backward_name[] = "tanh_backward"; +void tanh_backward_kernel_cuda(TensorIteratorBase& iter) { + auto dtype = iter.dtype(); + if(isComplexType(dtype)) { +#if AT_USE_JITERATOR() + static const auto tanh_backward_string = jiterator_stringify( + template + T tanh_backward(T a, T b) { + return a * std::conj(T{1.} - b * b); + } + ); // tanh_backward_string + AT_DISPATCH_COMPLEX_TYPES_AND(kComplexHalf, dtype, "tanh_backward_complex_cuda", [&]() { + jitted_gpu_kernel< + /*name=*/ tanh_backward_name, + /*return_dtype=*/ scalar_t, + /*common_dtype=*/ scalar_t, + /*arity=*/ 2>(iter, tanh_backward_string); + }); +#else + AT_DISPATCH_COMPLEX_TYPES_AND(kComplexHalf, dtype, "tanh_backward_complex_cuda", [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + using comp_t = at::opmath_type; + const auto one = comp_t{1.}; + const auto comp_b = static_cast(b); + const auto comp_a = static_cast(a); + return static_cast(comp_a * std::conj(one - comp_b * comp_b)); + }); + }); +#endif + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, dtype, "tanh_backward_cuda", [&]() { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return a * (scalar_t{1.} - b * b); + }); + }); + } +} + +REGISTER_DISPATCH(sigmoid_backward_stub, &sigmoid_backward_kernel_cuda) +REGISTER_DISPATCH(logit_backward_stub, &logit_backward_kernel_cuda) +REGISTER_DISPATCH(tanh_backward_stub, &tanh_backward_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMiscOpsKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMiscOpsKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..ac424d714dee03cfc0b5a7a0b3768e97f4f606ef --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMiscOpsKernels.cu @@ -0,0 +1,90 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +void smooth_l1_kernel_cuda(TensorIteratorBase& iter, double beta) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "smooth_l1_cuda", [&iter, beta]() { + scalar_t beta_val(beta); + gpu_kernel(iter, [beta_val] GPU_LAMBDA (scalar_t a, scalar_t b) -> scalar_t { + auto z = ::abs(a - b); + return z < beta_val ? scalar_t(0.5) * z * z / beta_val : z - scalar_t(0.5) * beta_val; + }); + }); +} + +void huber_kernel_cuda(TensorIterator& iter, double delta) { + AT_DISPATCH_FLOATING_TYPES_AND2(kBFloat16, kHalf, iter.dtype(), "huber_cuda", [&iter, delta] { + scalar_t delta_val(delta); + gpu_kernel(iter, [delta_val] GPU_LAMBDA (scalar_t a, scalar_t b) -> scalar_t { + auto z = ::abs(a - b); + return z < delta_val ? scalar_t(0.5) * z * z : delta_val * (z - scalar_t(0.5) * delta_val); + }); + }); +} + +void mse_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "mse_cuda", [&]() { + gpu_kernel(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + auto diff = a - b; + return diff * diff; + }); + }); +} + +void xlogy_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.common_dtype(), "xlogy_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t x, scalar_t y) -> scalar_t { + if (at::_isnan(y)){ + return NAN; + } + if (x == 0){ + return 0; + } + return x * std::log(y); + }); + }); +} + +void xlog1py_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.common_dtype(), "xlog1py_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t x, scalar_t y) -> scalar_t { + if (at::_isnan(y)){ + return NAN; + } + if (x == 0){ + return 0; + } + return x * std::log1p(y); + }); + }); +} + +void ldexp_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(0), "ldexp_cuda", [&] { + gpu_kernel(iter, []GPU_LAMBDA(scalar_t x, int exp) -> scalar_t { + return ::ldexp(x, exp); + }); + }); +} + +REGISTER_DISPATCH(smooth_l1_stub, &smooth_l1_kernel_cuda) +REGISTER_DISPATCH(huber_stub, &huber_kernel_cuda) +REGISTER_DISPATCH(mse_stub, &mse_kernel_cuda) +REGISTER_DISPATCH(xlogy_stub, &xlogy_kernel_cuda) +REGISTER_DISPATCH(xlog1py_stub, &xlog1py_kernel_cuda) +REGISTER_DISPATCH(ldexp_stub, &ldexp_kernel_cuda) + +// DO NOT ADD ANY NEW KERNELS HERE +// CUDA compilation times grow quickly. It's perfectly acceptable to have a file per kernel. + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMulKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMulKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..8fb596df70c4fbc88adfaed65d19db33e30ff37f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryMulKernel.cu @@ -0,0 +1,48 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +constexpr char mul_name[] = "mul_kernel"; +void mul_kernel_cuda(TensorIteratorBase& iter) { + auto common_dtype = iter.common_dtype(); + if (common_dtype == kComplexHalf) { + using scalar_t = c10::complex; +#if AT_USE_JITERATOR() + static const auto mul_string = jiterator_stringify( + template T mul_kernel(T a, T b) { return a * b; }); + opmath_jitted_gpu_kernel_with_scalars( + iter, mul_string); +#else + using opmath_t = at::opmath_type; + opmath_symmetric_gpu_kernel_with_scalars( + iter, binary_internal::MulFunctor()); +#endif + } else { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3( + kHalf, kBFloat16, kBool, iter.common_dtype(), "mul_cuda", [&]() { + using opmath_t = at::opmath_type; + opmath_symmetric_gpu_kernel_with_scalars( + iter, binary_internal::MulFunctor()); + }); + } +} + +REGISTER_DISPATCH(mul_stub, &mul_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryRemainderKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryRemainderKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..2adcd968757d02c60a92650df3fe2166d9ad804d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryRemainderKernel.cu @@ -0,0 +1,82 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include + +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +void remainder_kernel_cuda(TensorIteratorBase& iter) { + if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { +#ifndef USE_ROCM + // Guard uint8 div-by-zero: NVIDIA hardware returns all-1s (255) for + // integer mod by zero, while ROCm returns the dividend unchanged, so + // we only need this explicit guard on the CUDA path. + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "remainder_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + if constexpr (std::is_same_v) { + if (b == 0) { + return std::numeric_limits::max(); + } + } + scalar_t r = a % b; + if (r != 0 && c10::signs_differ(r, b)) { + r += b; + } + return r; + }); + }); +#else + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "remainder_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + scalar_t r = a % b; + if (r != 0 && c10::signs_differ(r, b)) { + r += b; + } + return r; + }); + }); +#endif + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.common_dtype(), "remainder_cuda", [&]() { + gpu_kernel_with_scalars(iter, + []GPU_LAMBDA(scalar_t a, scalar_t b) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + auto mod = ::fmod(a, b); + if (mod != 0 && c10::signs_differ(b, mod)) { + mod += b; + } + return mod; + }); + }); + } +} + +void fmod_kernel_cuda(TensorIteratorBase& iter) { + if (isIntegralType(iter.common_dtype(), /*includeBool*/ false)) { + AT_DISPATCH_INTEGRAL_TYPES(iter.common_dtype(), "fmod_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return a % b; + }); + }); + } else { + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, iter.common_dtype(), "fmod_cuda", [&]() { + gpu_kernel_with_scalars(iter, + []GPU_LAMBDA(scalar_t a, scalar_t b) __ubsan_ignore_float_divide_by_zero__ -> scalar_t { + return ::fmod(a, b); + }); + }); + } +} + +REGISTER_DISPATCH(remainder_stub, &remainder_kernel_cuda) +REGISTER_DISPATCH(fmod_stub, &fmod_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryShiftOpsKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryShiftOpsKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..7de8f7151dfdc9fb40126aa83131dccd4ff688ae --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/BinaryShiftOpsKernels.cu @@ -0,0 +1,44 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + + +void lshift_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "lshift_cuda", [&]() { + gpu_kernel_with_scalars(iter, + []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + constexpr scalar_t max_shift = sizeof(scalar_t) * CHAR_BIT; + if ((static_cast>(b) < 0) || (b >= max_shift)) { + return 0; + } + return static_cast>(a) << b; + }); + }); +} + +void rshift_kernel_cuda(TensorIteratorBase& iter) { + AT_DISPATCH_INTEGRAL_TYPES(iter.dtype(), "rshift_cuda", [&]() { + gpu_kernel_with_scalars(iter, + []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + // right shift value to retain sign bit for signed and no bits for unsigned + constexpr scalar_t max_shift = sizeof(scalar_t) * CHAR_BIT - std::is_signed_v; + if ((static_cast>(b) < 0) || (b >= max_shift)) { + return a >> max_shift; + } + return a >> b; + }); + }); +} + +REGISTER_DISPATCH(lshift_stub, &lshift_kernel_cuda) +REGISTER_DISPATCH(rshift_stub, &rshift_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Blas.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Blas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..165ef9f1de6f5c5e350df4d7f78d6b2d797516df --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Blas.cpp @@ -0,0 +1,1013 @@ +#include +#include +#include +#include +#include +#include +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_MSLK +#include +#endif + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +using at::blas::ScalingType; +using at::blas::SwizzleType; + +c10::MaybeOwned prepare_batch_matrix_for_cublas(const Tensor& tensor, bool& transpose_tensor, int64_t& ld_tensor, bool transpose_result, int64_t m, int64_t n) { + IntArrayRef tensor_strides = tensor.strides(); + c10::MaybeOwned tensor_; + int fast_dim = transpose_result ? 2 : 1; + int leading_dim = transpose_result ? 1 : 2; + + if (tensor_strides[fast_dim] == 1 && + (tensor_strides[leading_dim] >= std::max(1, m))) { + transpose_tensor = false; + tensor_ = resolve_conj_if_indicated(tensor, true); + ld_tensor = tensor_->strides()[leading_dim]; + } else if ((tensor_strides[leading_dim] == 1) && + (tensor_strides[fast_dim] >= std::max(1, n))) { + transpose_tensor = true; + tensor_ = resolve_conj_if_indicated(tensor, false); + ld_tensor = tensor_->strides()[fast_dim]; + } else { + transpose_tensor = !transpose_result; + // gemm call requires leading dimension and stride parameters to be non-zero + bool is_stride_non_zero = tensor.strides()[1] != 0 && tensor.strides()[2] != 0; + if (tensor.is_contiguous() && is_stride_non_zero) { + tensor_ = resolve_conj_if_indicated(tensor, transpose_result); + } else { + tensor_ = c10::MaybeOwned::owned(tensor.clone(at::MemoryFormat::Contiguous)); + } + ld_tensor = tensor_->strides()[1]; + } + + return tensor_; +} + +namespace { + +enum class Activation { + None, + RELU, + GELU, +}; + +cuda::blas::GEMMAndBiasActivationEpilogue activation_to_gemm_and_blas_arg(Activation a) { + switch (a) { + case Activation::None: + return cuda::blas::GEMMAndBiasActivationEpilogue::None; + case Activation::RELU: + return cuda::blas::GEMMAndBiasActivationEpilogue::RELU; + case Activation::GELU: + return cuda::blas::GEMMAndBiasActivationEpilogue::GELU; + default: + TORCH_CHECK(false, "Unknown activation epologue type"); + } +} + +/* + * Checks whether DISABLE_ADDMM_CUDA_LT is set. + * Additionally, for ROCM we test whether the architecture supports the Lt. + */ +static bool isGloballyDisabledAddmmCudaLt(const at::Device& device) { + /* On ROCM, we have the following order of precedence: + - When hipBLASLt is NOT supported on the architecture, return true. + - If and only if the environment is set, then return the value that it set to. + - If the environment variable is NOT set, treturn a value based on the preferred BLAS backend. + */ + static const auto is_addmm_cuda_lt_disabled = c10::utils::get_env("DISABLE_ADDMM_CUDA_LT"); + #ifdef USE_ROCM + const auto& archs = at::detail::getCUDAHooks().getHipblasltSupportedArchs(); + const auto is_hipblas_lt_arch_supported = at::detail::getCUDAHooks().isGPUArch(archs, device.index()); + if (!is_hipblas_lt_arch_supported) { + return true; + } + + // If environment variable is explicitly set, respect it + if (is_addmm_cuda_lt_disabled.has_value()) { + return is_addmm_cuda_lt_disabled == "1"; + } + + // The available BLAS backends on ROCm are: rocBLAS, hipBLASLt, and CK. + const auto preferred_backend = at::globalContext().blasPreferredBackend(); + if (preferred_backend == at::BlasBackend::Cublaslt) { + return false; + } else { + return true; + } + + #else + if (is_addmm_cuda_lt_disabled == "1") { + return true; + } + + return false; + #endif +} +/* + * Check whether for the given input we want to enable the Lt interface + */ +static bool isInputCompliesAddmmCudaLt( + Tensor& result, + const Tensor& self, + const Tensor& mat1, + const Tensor& mat2, + const Scalar& beta, + const Scalar& alpha, + Activation activation +) { + #ifdef USE_ROCM + // Implies 2D bias which we currently not send through Lt. + // TODO: this check is done pre col-major input preparation, + // so, this condition can be ralexed in cases when a col-major + // copy of result is needed. + if (self.is_same(result) || self.dim() == 2) { + return false; + } + #endif + + #if defined(USE_ROCM) && ROCM_VERSION == 60400 + // hipblaslt TT fp32 regression on ROCm 6.4, cannot use + const auto args = cublasCommonArgs(mat1, mat2, result); + if (args.transa == 't' && args.transb == 't') { + return false; + } + #endif + + const auto mat1_sizes = mat1.sizes(); + const auto mat2_sizes = mat2.sizes(); + const auto scalar_type = mat1.scalar_type(); + return (beta.toComplexDouble() == 1.0 + // NOTE: row-major result is important when bias is 1D. + // This is because Lt broadcasts 1D bias over the columns + // while the aten::addmm API broadcasts it over the rows, + // and this is in conjunction with the data preparation + // procedure that does not transpose arguments with + // col-major result. For col-major result we need + // to explicitly transpose the problem so that bias is + // correctly applied. + // TODO: enable col-major result if needed. + // TODO: no need to check result's layout when + // !result.is_same(self) and self.dim() == 2, because + // self needs to be copied into result and the bias ptr + // will be ignored. + && result.dim() == 2 && result.is_contiguous() + && ( + ( // Conditions for bias to be fusable -- implies direct Lt path without copies. + self.is_contiguous() && + // NOTE: fine to have 1-len dims to the left from the right-most one + (self.dim() == 1 || self.squeeze().dim() == 1) && + self.sizes().back() == mat2_sizes[1] + ) + || ( // 2D bias restrictions. self.is_contiguous() is implicit when result.is_same(self), + // and we need to copy self into result otherwise, so the self's layout becomes irrelevant. + // See also TODO from above. + activation != Activation::None && // Lt is faster when activation is fused + (self.dim() == 2 && at::is_expandable_to(self.sizes(), {mat1_sizes[0], mat2_sizes[1]})) + ) + ) + && ( // some dtype restrictions + #ifndef USE_ROCM + scalar_type == at::ScalarType::Double || + #endif + scalar_type == at::ScalarType::Float || + scalar_type == at::ScalarType::Half || + scalar_type == at::ScalarType::BFloat16 + ) + && ( // some shape/stride restrictions + // Strangely, if mat2 has only 1 row or column, we get + // CUBLAS_STATUS_INVALID_VALUE error from cublasLtMatmulAlgoGetHeuristic. + mat2_sizes[0] > 1 && mat2_sizes[1] > 1 + ) + ); +} + +template +void launchTunableGemmAndBias(cublasCommonArgs &args, const Scalar& alpha, const scalar_t* bias, cuda::blas::GEMMAndBiasActivationEpilogue activation) { + bool transa_ = ((args.transa != 'n') && (args.transa != 'N')); + bool transb_ = ((args.transb != 'n') && (args.transb != 'N')); + at::cuda::tunable::GemmAndBiasParams params; + params.transa = args.transa; + params.transb = args.transb; + params.m = args.m; + params.n = args.n; + params.k = args.k; + params.alpha = alpha.to>(); + params.a = args.mata->const_data_ptr(); + params.lda = args.lda; + params.b = args.matb->const_data_ptr(); + params.ldb = args.ldb; + params.c = args.result->data_ptr(); + params.ldc = args.result_ld; + params.bias = bias; + params.activation = activation; + if (transa_ && transb_) { + static at::cuda::tunable::GemmAndBiasTunableOp gemm{}; + gemm(¶ms); + } + else if (transa_ && !transb_) { + static at::cuda::tunable::GemmAndBiasTunableOp gemm{}; + gemm(¶ms); + } + else if (!transa_ && transb_) { + static at::cuda::tunable::GemmAndBiasTunableOp gemm{}; + gemm(¶ms); + } + else if (!transa_ && !transb_) { + static at::cuda::tunable::GemmAndBiasTunableOp gemm{}; + gemm(¶ms); + } + else { + TORCH_CHECK(false, "unreachable"); + } +} + +template +bool launchGemmAndBiasCublasLt( + // args contains result which is modified + cublasCommonArgs& args, + const std::optional& self, + const Scalar& alpha, + Activation activation = Activation::None +) { + // We apply bias in the epilogue only when it is 1D, + // or when it can be squeezed to 1D. + // self_ptr == nullptr implies ignore bias epilogue + // and use standard gemm-like API. + const auto* self_ptr = self.has_value() ? self.value().const_data_ptr() : static_cast(nullptr); + + + const auto tuning_ctx = at::cuda::tunable::getTuningContext(); + if (tuning_ctx->IsTunableOpEnabled()) { + // TODO: maybe also return some success state? + launchTunableGemmAndBias( + args, alpha, self_ptr, activation_to_gemm_and_blas_arg(activation) + ); + return true; + } + + return at::cuda::blas::gemm_and_bias( + args.transa == 't', + args.transb == 't', + args.m, + args.n, + args.k, + alpha.to>(), + args.mata->const_data_ptr(), + args.lda, + args.matb->const_data_ptr(), + args.ldb, + self_ptr, + args.result->data_ptr(), + args.result_ld, + activation_to_gemm_and_blas_arg(activation) + ); +} + +template +bool launchGemmCublas( + // args contains result which is modified + cublasCommonArgs& args, + const Scalar& alpha, + const Scalar& beta +) { + at::cuda::blas::gemm( + args.transa, + args.transb, + args.m, + args.n, + args.k, + alpha.to>(), + args.mata->const_data_ptr(), + args.lda, + args.matb->const_data_ptr(), + args.ldb, + beta.to>(), + args.result->data_ptr(), + args.result_ld + ); + return true; // success! +} + +Tensor& addmm_out_cuda_impl(Tensor& result, const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha, Activation activation=Activation::None, bool disable_addmm_cuda_lt_override=false) { + // Shape checks { + // Make sure to keep addmm_cuda below in sync with this code; it + // preflights a check to try to avoid actually needing to call + // expand(). + TORCH_CHECK(mat1.dim() == 2 && mat2.dim() == 2, "tensors must be 2-D"); + TORCH_CHECK( + mat1.dtype() == mat2.dtype(), + "expected mat1 and mat2 to have the same dtype, but got: ", mat1.dtype(), " != ", mat2.dtype() + ) + + if (result.is_same(self)) { + TORCH_CHECK(result.dim() == 2, "tensors must be 2-D"); + TORCH_CHECK(self.sizes()[0] == mat1.sizes()[0], "self dim 0 must match mat1 dim 0"); + TORCH_CHECK(self.sizes()[1] == mat2.sizes()[1], "self dim 1 must match mat2 dim 1"); + } + // } Shape checks + + // NOLINTNEXTLINE(*c-array*) + TensorArg targs[]{{result, "out", 0}, {self, "self", 1}, {mat1, "mat1", 2}, {mat2, "mat2", 3}}; + checkAllSameGPU(__func__, targs); + + // Handle whether to use the Lt interface { + static bool persistent_disable_addmm_cuda_lt = isGloballyDisabledAddmmCudaLt(self.device()); + // if lt path fails, we recurse back into this function here and force the lt path to off + // we cannot update variable disable_addmm_cuda_lt from above since it is static and would be permanent + bool disable_addmm_cuda_lt = persistent_disable_addmm_cuda_lt || disable_addmm_cuda_lt_override; + #ifdef USE_ROCM + // Conditioned on the device index, which is not persistent + disable_addmm_cuda_lt = disable_addmm_cuda_lt || isGloballyDisabledAddmmCudaLt(self.device()); + #endif + // Condition on the input + disable_addmm_cuda_lt = disable_addmm_cuda_lt || !isInputCompliesAddmmCudaLt(result, self, mat1, mat2, beta, alpha, activation); + + at::ScalarType scalar_type = mat1.scalar_type(); + bool is_float_output_with_half_input = (scalar_type == at::ScalarType::Half || scalar_type == at::ScalarType::BFloat16) && result.scalar_type() == at::ScalarType::Float; + + #ifdef USE_ROCM + disable_addmm_cuda_lt = disable_addmm_cuda_lt || is_float_output_with_half_input; + #endif + + bool use_bias_ptr_lt = (self.dim() == 1) && !disable_addmm_cuda_lt; + // for float output with half input cublasLT with bias produces wrong results + use_bias_ptr_lt &= !is_float_output_with_half_input; + + // Handle result/self shapes + if (!result.is_same(self)) { + at::native::resize_output(result, {mat1.sizes()[0], mat2.sizes()[1]}); + + // We do not copy bias only when we need the bias ptr + if (beta.toComplexDouble() != 0.0 && !use_bias_ptr_lt) { + // NOTE: self should broadcast over result + at::native::copy_(result, *expand_size(self, result.sizes(), "addmm")); + } + } + + // Short circuit on empty result + if (result.numel() == 0) { + return result; + } + + // Short circuit if the reduction dim is empty + if (mat1.sizes()[1] == 0) { + // By definition, when beta==0, values in self should be ignored. nans and infs + // should not propagate + if (beta.toComplexDouble() == 0.) { + return result.zero_(); + } + // TODO: We could squeeze some perf by calling at::cuda::mul_out here instead, to bypass the dispatcher. + // That requires some fixing some internal build dependencies though. + return at::mul_out( + result, + self.expand(result.sizes()), + at::native::scalar_tensor( + beta, + self.scalar_type(), + std::nullopt /* layout */, + at::kCPU, + std::nullopt /* pin_memory */ + ) + ); + } + + cublasCommonArgs args(mat1, mat2, result); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!args.result->is_conj()); + + // The Lt path + if (!disable_addmm_cuda_lt) { + bool lt_success = false; + if (is_float_output_with_half_input) { + #ifdef USE_ROCM + TORCH_CHECK(false, "float output with half input is not enabled for ROCm"); + #else + if (at::cuda::tunable::getTuningContext()->IsTunableOpEnabled()) { + TORCH_CHECK(false, "Tunable GEMM is not supported for float output with reduced float input"); + } + AT_DISPATCH_REDUCED_FLOATING_TYPES( + scalar_type, + "addmm_cuda_lt", + [&] { + lt_success = launchGemmAndBiasCublasLt(args, use_bias_ptr_lt ? std::make_optional(self) : std::nullopt, alpha, activation); + } + ); + #endif + } else { + // !is_float_output_with_half_input + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + scalar_type, + "addmm_cuda_lt", + [&] { + lt_success = launchGemmAndBiasCublasLt(args, use_bias_ptr_lt ? std::make_optional(self) : std::nullopt, alpha, activation); + } + ); + } // end is_float_output_with_half_input + + if (!lt_success) { + // lt path failed; recurse but disable lt path + return addmm_out_cuda_impl(result, self, mat1, mat2, beta, alpha, activation, true); + } + // end Lt path + } else { + // No Lt, we use a GEMM instead + if (is_float_output_with_half_input) { + AT_DISPATCH_REDUCED_FLOATING_TYPES( + scalar_type, + "addmm_cuda", + [&] { + launchGemmCublas(args, alpha, beta); + } + ); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + scalar_type, + "addmm_cuda", + [&] { + launchGemmCublas(args, alpha, beta); + } + ); + } + + // Apply epilogue + switch (activation) { + case Activation::RELU: + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + at::relu_(const_cast(*args.result)); + break; + case Activation::GELU: + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + at::gelu_(const_cast(*args.result), "tanh"); + break; + default: break; + } + } // end GEMM path + +// Preprocessor gate here needs to match the inverse of the check +// gating activation_to_gemm_and_blas_arg above; here we are manually +// performing a post-GELU because we weren't able to use the GELU +// epilogue above. +#if !defined(CUDA_VERSION) && !defined(USE_ROCM) + if (!disable_addmm_cuda_lt && activation == Activation::GELU) { + at::gelu_(const_cast(*args.result), "tanh"); + } +#endif + + if (!result.is_same(*args.result)) { + result.copy_(*args.result); + } + return result; +} + +const Tensor& baddbmm_out_cuda_impl(const Tensor& result, const Tensor& self, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha) { + // handle pathological cases that blas may not like + if (result.numel() == 0) { + return result; + } else if (batch1.size(2) == 0) { + if (beta.to>() == 0.0) { + return result.zero_(); + } else { + return result.mul_(beta); + } + } + + bool transpose_result = false; + c10::MaybeOwned result_; + IntArrayRef result_strides = result.strides(); + IntArrayRef result_sizes = result.sizes(); + + if ((result_strides[1] == 1) && + ((result_sizes[2] == 1) || (result_strides[2] >= std::max(1, result_sizes[1])))) { + result_ = resolve_conj_if_indicated(result, true); + } else if ((result_strides[2] == 1) && + (result_sizes[1] == 1 || (result_strides[1] >= std::max(1, result_sizes[2])))) { + transpose_result = true; + result_ = resolve_conj_if_indicated(result, true); + } else { + result_ = c10::MaybeOwned::owned(result.transpose(1, 2).clone(at::MemoryFormat::Contiguous).transpose(1, 2)); + } + + int leading_dim = transpose_result ? 1 : 2; + + int64_t m = result_sizes[transpose_result ? 2 : 1]; + int64_t n = result_sizes[leading_dim]; + int64_t k = (transpose_result ? batch2 : batch1).sizes()[leading_dim]; + + int64_t lda = 0, ldb = 0, ldc = 0; + bool transpose_batch1 = false, transpose_batch2 = false; + auto batch1_ = prepare_batch_matrix_for_cublas(transpose_result ? batch2 : batch1, transpose_batch1, lda, transpose_result, m, k); + auto batch2_ = prepare_batch_matrix_for_cublas(transpose_result ? batch1 : batch2, transpose_batch2, ldb, transpose_result, k, n); + + ldc = result_->strides()[leading_dim]; + int64_t num_batches = result_->sizes()[0]; + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!result_->is_conj()); + bool is_float_output_with_half_input = (batch1.scalar_type() == at::ScalarType::Half || batch1.scalar_type() == at::ScalarType::BFloat16) && result.scalar_type() == at::ScalarType::Float; + + if (is_float_output_with_half_input) { + AT_DISPATCH_REDUCED_FLOATING_TYPES(batch1.scalar_type(), "baddbmm_cuda", [&] { + using opmath_t = at::opmath_type; + opmath_t alpha_val = alpha.to(); + opmath_t beta_val = beta.to(); + const scalar_t* batch1_ptr = batch1_->const_data_ptr(); + const scalar_t* batch2_ptr = batch2_->const_data_ptr(); + const auto transa = transpose_batch1 ? batch1_->is_conj() ? 'c' : 't' : 'n'; + const auto transb = transpose_batch2 ? batch2_->is_conj() ? 'c' : 't' : 'n'; + + float* result_ptr = result_->mutable_data_ptr(); + + // If batch is 1 call gemm rather than bgemm + if (num_batches == 1) { + at::cuda::blas::gemm( + transa, transb, + m, n, k, + alpha_val, + batch1_ptr, lda, + batch2_ptr, ldb, + beta_val, + result_ptr, ldc); + } else { + at::cuda::blas::bgemm( + transa, transb, + m, n, k, + alpha_val, + batch1_ptr, lda, batch1_->strides()[0], + batch2_ptr, ldb, batch2_->strides()[0], + beta_val, + result_ptr, ldc, result_->strides()[0], + num_batches + ); + } + }); + } else { + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, batch1.scalar_type(), "baddbmm_cuda", [&] { + using opmath_t = at::opmath_type; + opmath_t alpha_val = alpha.to(); + opmath_t beta_val = beta.to(); + const scalar_t* batch1_ptr = batch1_->const_data_ptr(); + const scalar_t* batch2_ptr = batch2_->const_data_ptr(); + const auto transa = transpose_batch1 ? batch1_->is_conj() ? 'c' : 't' : 'n'; + const auto transb = transpose_batch2 ? batch2_->is_conj() ? 'c' : 't' : 'n'; + scalar_t* result_ptr = result_->mutable_data_ptr(); + // If batch is 1 call gemm rather than bgemm + if (num_batches == 1) { + at::cuda::blas::gemm( + transa, transb, + m, n, k, + alpha_val, + batch1_ptr, lda, + batch2_ptr, ldb, + beta_val, + result_ptr, ldc); + } else { + at::cuda::blas::bgemm( + transa, transb, + m, n, k, + alpha_val, + batch1_ptr, lda, batch1_->strides()[0], + batch2_ptr, ldb, batch2_->strides()[0], + beta_val, + result_ptr, ldc, result_->strides()[0], + num_batches + ); + } + }); + } + if (!result.is_same(*result_)) { + result.copy_(*result_); + } + return result; +} + +} // anonymous namespace + +TORCH_IMPL_FUNC(addmm_out_cuda)(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha, const Tensor& result) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + addmm_out_cuda_impl(const_cast(result), self, mat1, mat2, beta, alpha); +} + +TORCH_IMPL_FUNC(addmm_activation_out_cuda)(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const Scalar& beta, const Scalar& alpha, bool use_gelu, const Tensor& result) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + addmm_out_cuda_impl(const_cast(result), self, mat1, mat2, beta, alpha, use_gelu ? Activation::GELU : Activation::RELU); +} + +TORCH_IMPL_FUNC(mm_out_cuda)(const Tensor& self, const Tensor& mat2, const Tensor& result) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + addmm_out_cuda_impl(const_cast(result), result, self, mat2, 0, 1); +} + +TORCH_IMPL_FUNC(baddbmm_out_cuda)(const Tensor& self, const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha, const Tensor& result) { + { + baddbmm_out_cuda_impl(result, self, batch1, batch2, beta, alpha); + } +} + +TORCH_IMPL_FUNC(bmm_out_cuda)(const Tensor& batch1, const Tensor& batch2, const Tensor &result) { + Scalar beta(0.0); + Scalar alpha(1.0); + { + baddbmm_out_cuda_impl(result, result, batch1, batch2, beta, alpha); + } +} + +namespace { + +inline void dot_check(const Tensor& self, const Tensor& other) { + TORCH_CHECK( + self.dim() == 1 && other.dim() == 1, + "1D tensors expected, but got ", + self.dim(), + "D and ", + other.dim(), + "D tensors"); + TORCH_CHECK( + self.scalar_type() == other.scalar_type(), + "dot : expected both vectors to have same dtype, but found ", + self.scalar_type(), + " and ", + other.scalar_type()); + TORCH_CHECK( + self.numel() == other.numel(), + "inconsistent tensor size, expected tensor [", + self.numel(), + "] and src [", + other.numel(), + "] to have the same number of elements, but got ", + self.numel(), + " and ", + other.numel(), + " elements respectively"); + TORCH_CHECK( + (self.numel() <= INT_MAX) && (self.stride(0) <= INT_MAX) && + (other.stride(0) <= INT_MAX), + "dot only supports n, incx, incy with the bound [val] <= %d", + INT_MAX); +} + +} // anonymous namespace + +Tensor dot_cuda(const Tensor& self, const Tensor& other) { + if (self.is_complex()) { + if (self.is_conj()) { + if (other.is_conj()) { + return (dot_cuda(self.conj(), other.conj())).conj(); + } else { + return vdot_cuda(self.conj(), other); + } + } else if (other.is_conj()) { + return vdot_cuda(other.conj(), self); + } + } + + dot_check(self, other); + + const int n = static_cast(self.numel()); + int incx = static_cast(self.stride(0)); + int incy = static_cast(other.stride(0)); + if (n == 1) { + incx = 1; + incy = 1; + } + + if (self._is_zerotensor() || other._is_zerotensor()) { + return at::_efficientzerotensor({}, self.options()); + } + + return AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2( + ScalarType::Half, ScalarType::BFloat16, + self.scalar_type(), "dot", + [&] { + Tensor result = at::empty({}, self.options()); + + auto handle = at::cuda::getCurrentCUDABlasHandle(); + at::cuda::blas::PointerModeGuard pointerModeGuard(handle, CUBLAS_POINTER_MODE_DEVICE); + at::cuda::blas::dot( + handle, + n, + self.const_data_ptr(), + incx, + other.const_data_ptr(), + incy, + result.mutable_data_ptr()); + + return result; + }); +} + +Tensor vdot_cuda(const Tensor& self, const Tensor& other) { + if (!self.is_complex()) { + return dot_cuda(self, other); + } + + if (self.is_conj()) { + if (other.is_conj()) { + return vdot_cuda(other.conj(), self.conj()); + } else { + return dot_cuda(self.conj(), other); + } + } else if (other.is_conj()) { + return (dot_cuda(self, other.conj())).conj(); + } + + dot_check(self, other); + + if (self._is_zerotensor() || other._is_zerotensor()) { + return at::_efficientzerotensor({}, self.options()); + } + + const int n = static_cast(self.numel()); + int incx = static_cast(self.stride(0)); + int incy = static_cast(other.stride(0)); + if (n == 1) { + incx = 1; + incy = 1; + } + + return AT_DISPATCH_COMPLEX_TYPES(self.scalar_type(), "vdot", [&] { + Tensor result = at::empty({}, self.options()); + + auto handle = at::cuda::getCurrentCUDABlasHandle(); + at::cuda::blas::PointerModeGuard pointerModeGuard( + handle, CUBLAS_POINTER_MODE_DEVICE); + at::cuda::blas::vdot( + handle, + n, + self.const_data_ptr(), + incx, + other.const_data_ptr(), + incy, + result.mutable_data_ptr()); + + return result; + }); +} + +TORCH_IMPL_FUNC(addmv_out_cuda)(const Tensor &self, const Tensor &mat, const Tensor &vec, const Scalar& beta_, const Scalar& alpha_, const Tensor& result) { + c10::MaybeOwned self_ = expand_size(self, {mat.size(0)}); + auto betaval = beta_.toComplexDouble(); + if (mat.numel() == 0) { + // shortcut for an empty matrix + // By definition, when beta==0, values in self should be ignored. nans and infs + // should not propagate + if (betaval == 0.0) { + result.zero_(); + } else { + at::mul_out( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + const_cast(result), + self, + at::native::scalar_tensor( + beta_, self.scalar_type(), std::nullopt /* layout */, at::kCPU, std::nullopt /* pin_memory */)); + } + } else { + if (!result.is_same(*self_) && betaval != 0.0) { //if beta is 0, result contents will be zeroed later + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) + at::native::copy_(const_cast(result), *self_); + } + if (result.numel() != 0) { + auto r_stride = result.stride(0); + auto vec_stride = vec.stride(0); + + // Check for contiguity of `vec` and update `vec_stride` accordingly + const auto vec_contiguous = vec_stride == 0 ? vec.contiguous() : vec; + // A vector can be contiguous and have a stride of zero if it has it is of length 1 + vec_stride = std::max(vec_contiguous.stride(0), 1LL); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, mat.scalar_type(), "addmv_impl_cuda", [&] { + auto beta = beta_.to(); + auto alpha = alpha_.to(); + if (mat.stride(0) == 1 && mat.stride(1) >= std::max(1, mat.size(0))) { + at::cuda::blas::gemv('n', + mat.size(0), mat.size(1), alpha, mat.const_data_ptr(), mat.stride(1), vec_contiguous.const_data_ptr(), + vec_stride, beta, result.mutable_data_ptr(), r_stride); + } + else if (mat.stride(1) == 1 && mat.stride(0) >= std::max(1, mat.size(1))) { + at::cuda::blas::gemv('t', + mat.size(1), mat.size(0), alpha, mat.const_data_ptr(), mat.stride(0), + vec_contiguous.const_data_ptr(), vec_stride, beta, result.mutable_data_ptr(), r_stride); + } + else { + Tensor cmat = mat.contiguous(); + at::cuda::blas::gemv('t', + mat.size(1), mat.size(0), alpha, cmat.const_data_ptr(), cmat.stride(0), + vec_contiguous.const_data_ptr(), vec_stride, beta, result.mutable_data_ptr(), r_stride); + } + }); + } + } +} + +Tensor& _int_mm_out_cuda(const Tensor& self, const Tensor& mat2, Tensor& result) { + // NOTE: cuBLAS is currently broken for some combination of transposed inputs. + TORCH_CHECK(self.dim() == 2, "Expected self to be of dimension 2 but got ", self.dim()); + TORCH_CHECK(mat2.dim() == 2, "Expected mat2 to be of dimension 2 but got ", mat2.dim()); + TORCH_CHECK(self.size(0) > 16, "self.size(0) needs to be greater than 16, but got ", self.size(0)); + TORCH_CHECK(self.size(1) > 0 && self.size(1) % 8 == 0, "self.size(1) needs to be greater than 0 and a multiple of 8, but got ", self.size(1)); + TORCH_CHECK(self.size(1) == mat2.size(0), "self.size(1) needs to match mat2.size(0) but got ", self.size(1), " and ", mat2.size(0)); + TORCH_CHECK(mat2.size(1) > 0 && mat2.size(1) % 8 == 0, "mat2.size(1) needs to be greater than 0 and a multiple of 8, but got ", mat2.size(1)); + + TORCH_CHECK(result.dtype() == at::kInt, "Expected result dtype to be of type kInt but got ", result.dtype()); + TORCH_CHECK(result.size(0) == self.size(0), "Expected result.size(0) to be ", self.size(0), " but got ", result.size(0)); + TORCH_CHECK(result.size(1) == mat2.size(1), "Expected result.size(1) to be ", mat2.size(1), " but got ", result.size(1)); + + TORCH_CHECK(result.dim() == 2, "Expected result to be of dimension 2 but got ", result.dim()); + + TORCH_CHECK(result.is_contiguous(), "Expected result to be contiguous."); + + cublasCommonArgs args(self, mat2, result); + + at::cuda::blas::int8_gemm( + args.transa == 't', + args.transb == 't', + args.m, + args.n, + args.k, + args.mata->data_ptr(), + args.lda, + args.matb->data_ptr(), + args.ldb, + args.result->data_ptr(), + args.result_ld); + + if (!result.is_same(*args.result)) { + result.copy_(*args.result); + } + return result; +} + +Tensor _int_mm_cuda(const Tensor& self, const Tensor& mat2) { + Tensor result = at::empty({self.size(0), mat2.size(1)}, self.options().dtype(at::kInt)); + return _int_mm_out_cuda(self, mat2, result); +} + +static void baddbmm_bmm_out_dtype_checks(const Tensor& batch1, const Tensor& batch2, const Scalar& beta, const Scalar& alpha, const at::ScalarType out_dtype, const std::optional& self_baddbmm = std::nullopt) { + // ref ATen/native/LinearAlgebra.cpp common_checks_baddbmm_bmm + TORCH_CHECK(batch1.dim() == 3, "batch1 must be a 3D tensor"); + TORCH_CHECK(batch2.dim() == 3, "batch2 must be a 3D tensor"); + + const auto batch1_sizes = batch1.sizes(); + const auto batch2_sizes = batch2.sizes(); + + int64_t bs = batch1_sizes[0]; + int64_t contraction_size = batch1_sizes[2]; + int64_t res_rows = batch1_sizes[1]; + int64_t res_cols = batch2_sizes[2]; + std::vector output_size {bs, res_rows, res_cols}; + + TORCH_CHECK(batch2_sizes[0] == bs && batch2_sizes[1] == contraction_size, + "Expected size for first two dimensions of batch2 tensor to be: [", + bs, ", ", contraction_size, "] but got: [", batch2_sizes[0], ", ", batch2_sizes[1], "]."); + + TORCH_CHECK(batch1.scalar_type() == batch2.scalar_type(), "batch1 and batch2 must have the same dtype"); + + TORCH_CHECK(out_dtype == batch1.scalar_type() || + (out_dtype == at::ScalarType::Float && (batch1.scalar_type() == at::ScalarType::Half || batch1.scalar_type() == at::ScalarType::BFloat16)), + "out_dtype must be the same as input dtype or fp32 for fp16/bf16 inputs"); + + if (self_baddbmm.has_value()) { + const auto& self = self_baddbmm.value(); + TORCH_CHECK(self.dim() == 3, "self must be a 3D tensor"); + TORCH_CHECK(self.sizes() == output_size, "self must have the same shape as the output"); + } +} + +Tensor _bmm_dtype_cuda(const Tensor& batch1, const Tensor& batch2, const at::ScalarType out_dtype) { + Tensor out = at::empty({batch1.size(0), batch1.size(1), batch2.size(2)}, batch1.options().dtype(out_dtype)); + return _bmm_out_dtype_cuda(batch1, batch2, out_dtype, out); +} + +Tensor& _bmm_out_dtype_cuda(const Tensor& batch1, const Tensor& batch2, const at::ScalarType out_dtype, Tensor &out) { + baddbmm_bmm_out_dtype_checks(batch1, batch2, 0.0, 1.0, out_dtype); + Scalar beta(0.0); + Scalar alpha(1.0); + { + baddbmm_out_cuda_impl(out, out, batch1, batch2, beta, alpha); + } + + return out; +} + +Tensor _baddbmm_dtype_cuda(const Tensor& self, const Tensor& batch1, const Tensor& batch2, const at::ScalarType out_dtype, const Scalar& beta, const Scalar& alpha) { + TORCH_CHECK(self.scalar_type() == out_dtype || self.scalar_type() == batch1.dtype(), + "self dtype must match either out_dtype or batch1 dtype"); + Tensor out = at::empty({batch1.size(0), batch1.size(1), batch2.size(2)}, batch1.options().dtype(out_dtype)); + return _baddbmm_out_dtype_cuda(self, batch1, batch2, out_dtype, beta, alpha, out); +} + +Tensor& _baddbmm_out_dtype_cuda(const Tensor& self, const Tensor& batch1, const Tensor& batch2, const at::ScalarType out_dtype, const Scalar& beta, const Scalar& alpha, Tensor &out) { + baddbmm_bmm_out_dtype_checks(batch1, batch2, beta, alpha, out_dtype, out); + // We need to copy the tensor + out.copy_(self); + { + baddbmm_out_cuda_impl(out, out, batch1, batch2, beta, alpha); + } + + return out; +} + +Tensor _mm_dtype_cuda(const Tensor& self, const Tensor& mat2, const at::ScalarType out_dtype) { + Tensor result = at::empty({self.size(0), mat2.size(1)}, self.options().dtype(out_dtype)); + return _mm_dtype_out_cuda(self, mat2, out_dtype, result); +} + +Tensor& _mm_dtype_out_cuda(const Tensor& self, const Tensor& mat2, const at::ScalarType out_dtype, Tensor &out) { + TORCH_CHECK(self.dim() == 2, "self must be a matrix, got ", self.dim(), "-D tensor"); + TORCH_CHECK(mat2.dim() == 2, "mat2 must be a matrix, got ", mat2.dim(), "-D tensor"); + TORCH_CHECK( + self.sizes()[1] == mat2.sizes()[0], "mat1 and mat2 shapes cannot be multiplied (", + self.sizes()[0], "x", self.sizes()[1], " and ", mat2.sizes()[0], "x", mat2.sizes()[1], ")"); + + TORCH_CHECK(out_dtype == out.scalar_type(), "out_dtype must be the same as the dtype of the provided out tensor"); + TORCH_CHECK(self.scalar_type() == mat2.scalar_type(), "input dtypes must be the same"); + TORCH_CHECK(out_dtype == self.scalar_type() || + (out_dtype == at::ScalarType::Float && (self.scalar_type() == at::ScalarType::Half || self.scalar_type() == at::ScalarType::BFloat16)), + "out_dtype must be the same as input dtype or fp32 for fp16/bf16 inputs"); + TORCH_CHECK(out_dtype == out.scalar_type(), "out_dtype must be the same as the dtype of the provided out tensor"); + + + addmm_out_cuda_impl(out, out, self, mat2, 0, 1); + + return out; +} + +Tensor _addmm_dtype_cuda(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const at::ScalarType out_dtype, const Scalar& beta, const Scalar& alpha) { + TORCH_CHECK(mat1.dim() == 2, "mat1 must be a matrix, got ", mat1.dim(), "-D tensor"); + TORCH_CHECK(mat2.dim() == 2, "mat2 must be a matrix, got ", mat2.dim(), "-D tensor"); + Tensor result = at::empty({mat1.size(0), mat2.size(1)}, self.options().dtype(out_dtype)); + return _addmm_dtype_out_cuda(self, mat1, mat2, out_dtype, beta, alpha, result); +} + +Tensor& _addmm_dtype_out_cuda(const Tensor& self, const Tensor& mat1, const Tensor& mat2, const at::ScalarType out_dtype, const Scalar& beta, const Scalar& alpha, Tensor &out) { +// repeat dimensionality checks for direct calls to `out` overload + TORCH_CHECK(mat1.dim() == 2, "mat1 must be a matrix, got ", mat1.dim(), "-D tensor"); + TORCH_CHECK(mat2.dim() == 2, "mat2 must be a matrix, got ", mat2.dim(), "-D tensor"); + TORCH_CHECK( + mat1.sizes()[1] == mat2.sizes()[0], "mat1 and mat2 shapes cannot be multiplied (", + mat1.sizes()[0], "x", mat1.sizes()[1], " and ", mat2.sizes()[0], "x", mat2.sizes()[1], ")"); + TORCH_CHECK(mat1.scalar_type() == mat2.scalar_type(), "mat1 and mat2 must have the same dtype, but got ", mat1.scalar_type(), " and ", mat2.scalar_type()); + TORCH_CHECK(out_dtype == mat1.scalar_type() || + (out_dtype == at::ScalarType::Float && (mat1.scalar_type() == at::ScalarType::Half || mat1.scalar_type() == at::ScalarType::BFloat16)), + "out_dtype must be the same as input dtype or fp32 for fp16/bf16 inputs"); + + TORCH_CHECK(out_dtype == out.scalar_type(), "out_dtype must be the same as the dtype of the provided out tensor"); + TORCH_CHECK(out_dtype == self.scalar_type() || self.scalar_type() == mat1.scalar_type(), + "self dtype must match either out_dtype or mat1 dtype"); + + addmm_out_cuda_impl(out, self, mat1, mat2, beta, alpha); + + return out; +} + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Bucketization.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Bucketization.cu new file mode 100644 index 0000000000000000000000000000000000000000..057d46f15e3a0340aee3c43fc1dd0c6a81601a84 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Bucketization.cu @@ -0,0 +1,233 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { + +// Implement a numpy like searchsorted and a TF like bucketize function running on cuda +// See details in ATen/native/Bucketization.cpp + +namespace { + +template +__device__ int64_t lower_bound(const input_t *data_ss, int64_t start, int64_t end, const input_t val, const int64_t *data_sort) { + // sorter gives relative ordering for ND tensors, so we need to save and add the non-updated start as an offset + // i.e. the second row of a 3x3 tensors starts at element 3 but sorter's second row only contains 0, 1, or 2 + const int64_t orig_start = start; + while (start < end) { + const int64_t mid = start + ((end - start) >> 1); + const input_t mid_val = data_sort ? data_ss[orig_start + data_sort[mid]] : data_ss[mid]; + if (!(mid_val >= val)) { + start = mid + 1; + } + else { + end = mid; + } + } + return start; +} + +template +__device__ int64_t upper_bound(const input_t *data_ss, int64_t start, int64_t end, const input_t val, const int64_t *data_sort) { + // sorter gives relative ordering for ND tensors, so we need to save and add the non-updated start as an offset + // i.e. the second row of a 3x3 tensors starts at element 3 but sorter's second row only contains 0, 1, or 2 + const int64_t orig_start = start; + while (start < end) { + const int64_t mid = start + ((end - start) >> 1); + const input_t mid_val = data_sort ? data_ss[orig_start + data_sort[mid]] : data_ss[mid]; + if (!(mid_val > val)) { + start = mid + 1; + } + else { + end = mid; + } + } + return start; +} + +template +__global__ void searchsorted_cuda_kernel( + output_t *data_out, + const input_t *data_in, + const input_t *data_bd, + const int64_t *data_sort, + int64_t idim_in, + int64_t idim_bd, + int64_t numel_in, + bool right, + bool is_1d_boundaries) { + + for (int64_t tid = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x; tid < numel_in; tid += blockDim.x * gridDim.x) { + // If boundaries tensor is 1d, we always search the entire boundary tensor + int64_t start_bd = is_1d_boundaries ? 0 : tid / idim_in * idim_bd; + int64_t end_bd = start_bd + idim_bd; + + int64_t pos = !right ? + lower_bound(data_bd, start_bd, end_bd, data_in[tid], data_sort) - start_bd : + upper_bound(data_bd, start_bd, end_bd, data_in[tid], data_sort) - start_bd; + + // type conversion might happen here + data_out[tid] = pos; + } +} + +template +void searchsorted_cuda_contiguous(Tensor& result, const Tensor& input, const Tensor& boundaries, const bool& right, const Tensor& sorter) { + int64_t numel_in = input.numel(); + bool is_scalar_input = input.dim() == 0 && numel_in == 1; + // inner most dim size of input and boundaries + int64_t idim_in = is_scalar_input ? 1 : input.sizes().back(); + int64_t idim_bd = boundaries.sizes().back(); + + const input_t *data_in = input.const_data_ptr(); + const input_t *data_bd = boundaries.const_data_ptr(); + const int64_t *data_sort = sorter.defined() ? sorter.const_data_ptr() : nullptr; + output_t *data_out = result.mutable_data_ptr(); + + int64_t maxThread = at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock; + int64_t maxGrid = 1024; + dim3 block = dim3(std::min(maxThread, numel_in)); + dim3 grid = dim3(std::min(maxGrid, ceil_div(numel_in, block.x))); + at::cuda::CUDAStream stream = at::cuda::getCurrentCUDAStream(); + + searchsorted_cuda_kernel<<>>( + data_out, data_in, data_bd, data_sort, idim_in, idim_bd, numel_in, right, boundaries.dim() == 1); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +void dispatch( + Tensor& result, + const Tensor& input, + const Tensor& boundaries, + bool out_int32, + bool right, + const Tensor& sorter) { + if (!out_int32) { + AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, input.scalar_type(), "searchsorted_out_cuda", [&] { + searchsorted_cuda_contiguous(result, input, boundaries, right, sorter); + }); + } + else { + AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, input.scalar_type(), "searchsorted_out_cuda", [&] { + searchsorted_cuda_contiguous(result, input, boundaries, right, sorter); + }); + } +} + +} + +Tensor& searchsorted_out_cuda( + const Tensor& sorted_sequence, + const Tensor& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter_opt, + Tensor& result) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned sorter_maybe_owned = at::borrow_from_optional_tensor(sorter_opt); + const Tensor& sorter = *sorter_maybe_owned; + searchsorted_pre_check(sorted_sequence, self, result, out_int32, right, side_opt, sorter); + resize_output(result, self.sizes()); + + // we have two inputs to set right, pre_check checks that they aren't set to opposites + bool is_right = (side_opt && *side_opt == "right") || right; + if (self.numel() == 0) { + return result; + } + + // for non-contiguous result tensors, we write the output to a contiguous copy so we can later copy back, maintaining the original result tensor + Tensor out = result; + if (!result.is_contiguous()) { + out = result.contiguous(); + } + if (sorted_sequence.is_contiguous() && self.is_contiguous() && sorted_sequence.dtype() == self.dtype() && sorter.is_contiguous()) { + dispatch(out, self, sorted_sequence, out_int32, is_right, sorter); + } + else { + Tensor trimmed_input; + Tensor trimmed_boundaries; + Tensor trimmed_sorter; + searchsorted_maybe_trim_input_tensors(trimmed_input, trimmed_boundaries, trimmed_sorter, self, sorted_sequence, sorter); + const Tensor& final_input = trimmed_input.defined() ? trimmed_input : self; + const Tensor& final_boundaries = trimmed_boundaries.defined() ? trimmed_boundaries : sorted_sequence; + const Tensor& final_sorter = trimmed_sorter.defined() ? trimmed_sorter : sorter; + dispatch(out, final_input, final_boundaries, out_int32, is_right, final_sorter); + } + + // if result is non-contiguous, we wrote the answer to a copied version, so we copy back to the original result tensor + if (!result.is_contiguous()) { + result.copy_(out); + } + return result; +} + +Tensor& searchsorted_out_cuda( + const Tensor& sorted_sequence, + const Scalar& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter_opt, + Tensor& result) { + const Tensor& scalar_tensor = searchsorted_scalar_tensor(self, sorted_sequence.device()); + return searchsorted_out_cuda(sorted_sequence, scalar_tensor, out_int32, right, side_opt, sorter_opt, result); +} + +Tensor searchsorted_cuda( + const Tensor& sorted_sequence, + const Tensor& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter) { + ScalarType scalar_type = out_int32 ? ScalarType::Int : ScalarType::Long; + c10::TensorOptions options = TensorOptions().device(self.options().device()).dtype(scalar_type); + Tensor result = at::empty({0}, options, MemoryFormat::Contiguous); + at::native::searchsorted_out_cuda(sorted_sequence, self, out_int32, right, side_opt, sorter, result); + return result; +} + +Tensor searchsorted_cuda( + const Tensor& sorted_sequence, + const Scalar& self, + bool out_int32, + bool right, + const std::optional side_opt, + const std::optional& sorter) { + const Tensor& scalar_tensor = searchsorted_scalar_tensor(self, sorted_sequence.device()); + return searchsorted_cuda(sorted_sequence, scalar_tensor, out_int32, right, side_opt, sorter); +} + +Tensor& bucketize_out_cuda(const Tensor& self, const Tensor& boundaries, bool out_int32, bool right, Tensor& result) { + TORCH_CHECK(boundaries.dim() == 1, "boundaries tensor must be 1 dimension, but got dim(", boundaries.dim(), ")"); + at::native::searchsorted_out_cuda(boundaries, self, out_int32, right, std::nullopt, std::nullopt, result); + return result; +} + +Tensor bucketize_cuda(const Tensor& self, const Tensor& boundaries, bool out_int32, bool right) { + ScalarType scalar_type = out_int32 ? ScalarType::Int : ScalarType::Long; + c10::TensorOptions options = TensorOptions().device(self.options().device()).dtype(scalar_type); + Tensor result = at::empty({0}, options, MemoryFormat::Contiguous); + at::native::bucketize_out_cuda(self, boundaries, out_int32, right, result); + return result; +} + +Tensor bucketize_cuda(const Scalar& self, const Tensor& boundaries, bool out_int32, bool right) { + return bucketize_cuda(searchsorted_scalar_tensor(self, boundaries.device()), boundaries, out_int32, right); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDAJitLoops.cuh b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDAJitLoops.cuh new file mode 100644 index 0000000000000000000000000000000000000000..e63111277b64748bffc4277996b20015abad904d --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDAJitLoops.cuh @@ -0,0 +1,327 @@ +#pragma once +#include + +// Jiterator functions are guarded behind this macro +#if AT_USE_JITERATOR() + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace at::native { + +template +// warning : unused parameter when tuple is empty. +constexpr auto tuple_to_array_helper(const Tuple& t [[maybe_unused]], std::index_sequence seq) { + constexpr auto size = seq.size(); + return std::array{static_cast(&std::get(t))...}; +} + +// Helper function convert tuple to std::array +// for passing the arguments to CUDA Kernel +// NOTE: We capture tuple by reference, +// so the pointers in returned array are only valid +// till tuple is alive. +template +constexpr auto tuple_to_array(const std::tuple& extra_args) { + constexpr auto tuple_size = sizeof...(Args); + return tuple_to_array_helper(extra_args, std::make_index_sequence{}); +} + +struct JittedVecKernelCache { + // Different kernels are compiled depending on what we're vectorizing up to (1, 2 or 4 elements) + at::cuda::jit::NvrtcFunction vec1; + at::cuda::jit::NvrtcFunction vec2; + at::cuda::jit::NvrtcFunction vec4; + at::cuda::jit::NvrtcFunction vec8; +#ifdef USE_ROCM + at::cuda::jit::NvrtcFunction vec16; +#endif + +}; + +struct JittedKernelVariantCache { + JittedVecKernelCache vec; + at::cuda::jit::NvrtcFunction noncontiguous; + at::cuda::jit::NvrtcFunction dynamic_contiguous; + at::cuda::jit::NvrtcFunction dynamic_noncontiguous; +}; + +inline c10::SmallBuffer pack_kernel_args( + std::initializer_list args, + c10::ArrayRef extra_args) { + c10::SmallBuffer ret(args.size() + extra_args.size()); + std::copy(args.begin(), args.end(), ret.data()); + std::copy(extra_args.begin(), extra_args.end(), ret.data() + args.size()); + return ret; +} + +template +void launch_jitted_unrolled_kernel( + std::mutex &jiterator_mutex, + at::cuda::jit::NvrtcFunction &fn_cache, + const at::cuda::jit::KernelDescriptor &desc, + int64_t N, + array_t data, + inp_calc_t ic, + out_calc_t oc, + loader_t l, + storer_t s, + bool contiguous, + at::cuda::jit::BinaryFuncVariant scalar_pos, + const void* scalar_val, + c10::ArrayRef extra_args) { + + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + + int tws = at::cuda::jit::calc_thread_work_size(desc.nInputs, desc.nOutputs, desc.f_inputs_type, desc.result_type); + int bws = tws * num_threads(); + //casting result to int is always safe, intermediate is int64 and won't overflow + const uint32_t grid = (N + bws - 1) / bws; + + if (!fn_cache.function) { + const std::lock_guard lock{jiterator_mutex}; + if (!fn_cache.function) { + constexpr bool dynamic_casting = !std::is_same() || + !std::is_same(); + auto code = at::cuda::jit::generate_code( + desc, contiguous, dynamic_casting, scalar_pos, tws); + fn_cache = at::cuda::jit::jit_pwise_function(code, desc.name); + } + } + + auto args = pack_kernel_args({&N, &data, &ic, &oc, &l, &s, scalar_val}, extra_args); + at::cuda::jit::launch_jitted_pwise_function(fn_cache, args.data(), {grid, 1u, 1u}, + {num_threads(), 1u, 1u}); +} + +template +void launch_jitted_vectorized_kernel( + std::mutex &jiterator_mutex, JittedVecKernelCache &fn_cache, + const at::cuda::jit::KernelDescriptor &desc, int64_t N, array_t data, + at::cuda::jit::BinaryFuncVariant scalar_pos, + const void *scalar_val, c10::ArrayRef extra_args) { + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + + int tws = at::cuda::jit::calc_thread_work_size(desc.nInputs, desc.nOutputs, desc.f_inputs_type, desc.result_type); + int bws = tws * num_threads(); + // N is still int64_t for the computation, but it's always safe to cast result to int + const uint32_t grid = (N + bws - 1) / bws; + + int vec_size = at::cuda::jit::can_vectorize_up_to( + desc, c10::ArrayRef(data.data(), data.size())); + +#ifndef USE_ROCM + const auto input_size = c10::scalarTypeToTypeMeta(desc.f_inputs_type).itemsize(); + const int optimal_vec_size = 16 / static_cast(input_size); + vec_size = std::min(optimal_vec_size, vec_size); + // Here we purposely omit vec8 for 1-byte data because of a bug in NVCC + // that causes some numerical mismatches with uint8 on sm80 and sm90. + // TODO: Revisit this after CUDA 12.8 update. + if (input_size < 2) { + vec_size = std::min(vec_size, 4); + } +#endif + + // Different kernels are compiled depending on what we're vectorizing up to (1, 2 or 4 elements) + // fn_ptr is set to the appropriate function based on the vec size and GPU used + at::cuda::jit::NvrtcFunction* fn_ptr = nullptr; + +#ifdef USE_ROCM + if (vec_size == 16) { + fn_ptr = &fn_cache.vec16; + } else +#endif + if (vec_size == 8) { + fn_ptr = &fn_cache.vec8; + } else if (vec_size == 4) { + fn_ptr = &fn_cache.vec4; + } else if (vec_size == 2) { + fn_ptr = &fn_cache.vec2; + } else if (vec_size ==1) { + fn_ptr = &fn_cache.vec1; + } else { + TORCH_INTERNAL_ASSERT(false, "unexpected vec_size for jitter vectorized kernel"); + } + + bool vectorized = vec_size > 1; + + if (!fn_ptr->function) { + const std::lock_guard lock{jiterator_mutex}; + if (!fn_ptr->function) { // cache miss! + + // Generates program + auto code = at::cuda::jit::generate_code( + desc, /*contiguous=*/true, /*dynamic_casting=*/false, + scalar_pos, tws, vectorized, vec_size); + std::string kernel_name = vectorized ? desc.name + "_vectorized" + std::to_string(vec_size) : desc.name; + + // Acquires the program + *fn_ptr = at::cuda::jit::jit_pwise_function(code, kernel_name); + } + } + + if (vectorized) { + auto args = pack_kernel_args({&N, &data, scalar_val}, extra_args); + at::cuda::jit::launch_jitted_pwise_function( + *fn_ptr, args.data(), {grid, 1u, 1u}, {num_threads(), 1u, 1u}); + } else { +// NVCC complains about unused variables l and s. +// It should be false positive in most cases, so we suppress the warnings. +#pragma nv_diagnostic push +#pragma nv_diag_suppress 177 + auto ic = TrivialOffsetCalculator(); + auto oc = TrivialOffsetCalculator<1>(); + auto l = memory::LoadWithoutCast(); + auto s = memory::StoreWithoutCast(); + + auto args = pack_kernel_args( + {&N, &data, &ic, &oc, &l, &s, scalar_val}, extra_args); + at::cuda::jit::launch_jitted_pwise_function( + *fn_ptr, args.data(), {grid, 1u, 1u}, {num_threads(), 1u, 1u}); +#pragma nv_diagnostic pop + } +} + +template +void jitted_gpu_kernel_generic( + std::mutex &jiterator_mutex, + JittedKernelVariantCache &cache, + const at::cuda::jit::KernelDescriptor &desc, + at::cuda::jit::BinaryFuncVariant scalar_pos, + c10::ArrayRef extra_args, + TensorIteratorBase& iter, + const bool dynamic_casting, + const void *scalar_val) { + TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing()); + TORCH_INTERNAL_ASSERT(iter.ninputs() == arity); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + + constexpr int ntensors = arity + 1; + std::array data; + for (auto i : c10::irange(ntensors)) { + data[i] = (char*)iter.data_ptr(i); + } + + int64_t numel = iter.numel(); + bool contiguous = iter.is_contiguous(); + + // Decides which of 4 kernel types to launch + // Variations are: + // - Case 1: no dynamic casting and contiguous + // - Case 2: no dynamic casting and noncontiguous + // - Case 3: dynamic casting and contiguous + // - Case 4: dynamic casting and noncontiguous + // These cases align with the non-jitted CUDALoops.cuh cases in gpu_kernel_impl + + if (!dynamic_casting) { + if (contiguous) { + // Case 1: no dynamic casting and contiguous + launch_jitted_vectorized_kernel( + jiterator_mutex, cache.vec, desc, + numel, data, scalar_pos, scalar_val, extra_args); + return; + } + + // Case 2: no dynamic casting and noncontiguous + auto input_offset_calculator = make_input_offset_calculator(iter); + auto output_offset_calculator = make_output_offset_calculator(iter); + auto loader = memory::LoadWithoutCast(); + auto storer = memory::StoreWithoutCast(); + launch_jitted_unrolled_kernel( + jiterator_mutex, cache.noncontiguous, desc, numel, data, + input_offset_calculator, output_offset_calculator, loader, + storer, contiguous, scalar_pos, scalar_val, extra_args); + return; + } + + // Cases 3 and 4 are handled below + // Both require construction of a storer (this asserts 1 output) and one or more loaders + + // Creates store cast to output (the zeroth tensor in TensorIterator) + auto storer = memory::StoreWithCast<1>(iter); + + // Creates load casts from inputs (note offset indexing into the iterators 1...n tensors) + auto loader = memory::LoadWithCast(iter); + + if (contiguous) { + // Case 3: dynamic casting and contiguous + auto input_offset_calculator = TrivialOffsetCalculator(); + auto output_offset_calculator = TrivialOffsetCalculator<1>(); + launch_jitted_unrolled_kernel( + jiterator_mutex, cache.dynamic_contiguous, desc, numel, data, input_offset_calculator, + output_offset_calculator, loader, storer, contiguous, scalar_pos, scalar_val, extra_args); + return; + } + + // Case 4: dynamic casting and noncontiguous + auto input_offset_calculator = make_input_offset_calculator(iter); + auto output_offset_calculator = make_output_offset_calculator(iter); + launch_jitted_unrolled_kernel( + jiterator_mutex, cache.dynamic_noncontiguous, desc, numel, data, input_offset_calculator, + output_offset_calculator, loader, storer, contiguous, scalar_pos, scalar_val, extra_args); +} + +// NOTE: static to reduce chances of name collision. +template < + char const* name, + typename result_type, + typename f_inputs_type, + int arity, + at::cuda::jit::BinaryFuncVariant scalar_pos = + at::cuda::jit::BinaryFuncVariant::NoScalar, + typename... ExtraArgs> +static void jitted_gpu_kernel_impl( + TensorIteratorBase& iter, + const std::string &f, + const bool dynamic_casting, + at::opmath_type scalar_val, + const std::tuple& extra_args) { + + // TODO: Memory use can probably be optimized by reusing kernels across GPUs with + // the same compute capability + static std::mutex jiterator_mutex; + static std::vector device_caches(c10::cuda::device_count()); + + constexpr int nInputs = arity; + constexpr int nOutputs = 1; // TODO: Support more than 1 output + static const auto desc = at::cuda::jit::make_kernel_descriptor< + result_type, f_inputs_type, ExtraArgs...>(name, f, nInputs, nOutputs); + + auto &cache = device_caches[iter.device().index()]; + auto extra_args_array = tuple_to_array(extra_args); + return jitted_gpu_kernel_generic( + jiterator_mutex, + cache, + desc, + scalar_pos, + extra_args_array, + iter, + dynamic_casting, + &scalar_val + ); +} + +} // at::native + +#endif // AT_USE_JITERATOR() diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDALoops.cuh b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDALoops.cuh new file mode 100644 index 0000000000000000000000000000000000000000..ef4a40cd08ea4b63cf28c3aa41eba97bacb66b01 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDALoops.cuh @@ -0,0 +1,1141 @@ +#pragma once + +// This file provides two functions to help write GPU elementwise kernels: +// +// gpu_kernel(TensorIterator iter, ) +// gpu_kernel_with_scalars(TensorIterator iter, ) +// +// The gpu_kernel_with_scalars generates specializations that support a +// single scalar CPU argument, such as from `cuda_tensor + 5`. The CPU scalar +// is lifted to a kernel parameter instead of copying to device memory. +// This should be used in conjunction with TensorIterator::allow_cpu_scalars_, +// which is the default for TensorIterator::binary_op. Otherwise, all inputs +// and the output must be on the GPU. +// +// For example, to write a reciprocal kernel for GPU float Tensors: +// +// gpu_kernel(iter, []GPU_LAMBDA(float a) { +// return 1.0f / a; +// }); +// +// To write a multiplication kernel for GPU float Tensors where one argument +// may be a CPU scalar: +// +// gpu_kernel_with_scalars(iter, []GPU_LAMBDA(float a, float b) { +// return a * b; +// }); +// +// See BinaryOpsKernel.cu for the complete implementation +// + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __NVCC__ +#define ASSERT_HOST_DEVICE_LAMBDA(type) \ + static_assert( \ + __nv_is_extended_host_device_lambda_closure_type(type), \ + #type " must be a __host__ __device__ lambda") +#else +#define ASSERT_HOST_DEVICE_LAMBDA(type) +#endif + +namespace at::native { + +#ifdef USE_ROCM +// Custom configuration for vectorized elementwise kernel +// with template instantiation. +namespace vectorized_templated_config { +constexpr int num_threads() { + return 512; +} + +constexpr int elems_per_thread() { + return 32; +} + +constexpr int block_work_size() { + return elems_per_thread() * num_threads(); +} +} // namespace vectorized_templated_config +#endif + +template +constexpr auto sum_of_sizes(args_t args, std::index_sequence) { + if constexpr (sizeof...(Is) == 0) { + return 0; + } else { + return (sizeof(std::tuple_element_t) + ...); + } +} + +#ifdef USE_ROCM +template +constexpr auto elems_per_thread(){ + if constexpr (io_sizes == 1) { + return 16; + } else if constexpr (io_sizes < 4) { + return 8; + } else { + return 4; + } +} +#else +template +constexpr auto elems_per_thread(){ + if constexpr (io_sizes == 1) { + return 16; + } else { + return 8; + } +} +#endif + + +//thread work size of 8 regresses the perf of elementwise kernel on cuda +//this doesn't change ROCm behavior as thread_work_size is already 4 on ROCm +constexpr int elementwise_thread_work_size() {return 4;} +constexpr int elementwise_block_work_size() { + return elementwise_thread_work_size() * num_threads(); +} + +template +constexpr auto io_block_work_size() { + return num_threads() * elems_per_thread(); +} + +#ifdef USE_ROCM +template +constexpr auto input_size(args_t args, std::index_sequence) { + if constexpr (sizeof...(Is) == 0) { + return 0; + } else { + return sizeof(std::tuple_element_t<0, args_t>); + } +} + +template +constexpr auto calc_optimal_vec_size() { + static_assert(vec_size != 0); + static_assert(io_size != 0); + if constexpr (io_size == 1 && vec_size >= 16) { + return 16; + } else if constexpr (io_size <= 2 && vec_size >= 8) { + return 8; + } else if constexpr (io_size <= 4 && vec_size >= 4) { + return 4; + } else if constexpr (vec_size >= 4) { + return 4; + } else if constexpr (vec_size >= 2) { + return 2; + } else { + return 1; + } +} +#endif + +template +constexpr auto calc_io_size(){ + using traits = function_traits; + using args_t = typename traits::ArgsTuple; +#ifdef USE_ROCM + constexpr auto input_size = at::native::input_size(args_t{}, std::make_index_sequence>{}); + constexpr auto output_size = sizeof(typename traits::result_type); + return (input_size > 0) ? ((input_size < output_size) ? input_size : output_size) : output_size; +#else + constexpr auto input_size = at::native::sum_of_sizes(args_t{}, std::make_index_sequence>{}); + constexpr auto output_size = sizeof(typename traits::result_type); + return input_size + output_size; +#endif +} + +#ifndef USE_ROCM +// To save on binary size of libtorch_cuda.so, we split the vectorized_elementwise_kernel +// into two: one for vec_size=8 and one for vec_size=[2, 4], since vec8 is going to be +// used on sm_90 and sm_10x exclusively. +template +C10_LAUNCH_BOUNDS_1(num_threads()) +__global__ void vectorized_elementwise_kernel(int N, func_t f, array_t data) { + if constexpr (vec_size == 8) { +#if __CUDA_ARCH__ / 100 == 9 || __CUDA_ARCH__ / 100 == 10 + using traits = function_traits; + constexpr auto io_size = calc_io_size(); + int remaining = N - io_block_work_size() * blockIdx.x; + + // note: unless the compiler has a good reason to move code, it won't. + // Thus, the if-condition typically comes first in SASS, so the "hot" path + // should go first, improving instruction cache use. + if (remaining >= io_block_work_size()) { // if this block has a full `block_work_size` data to handle, use + // vectorized memory access + elementwise_kernel_helper( + f, memory::policies::vectorized()>(data)); + } else { // if this block handles the reminder, + // just do a naive unrolled loop + auto input_calc = TrivialOffsetCalculator(); + auto output_calc = TrivialOffsetCalculator<1>(); + auto loader = memory::LoadWithoutCast(); + auto storer = memory::StoreWithoutCast(); + auto policy = memory::policies::unroll< + array_t, + decltype(input_calc), + decltype(output_calc), + memory::LoadWithoutCast, + memory::StoreWithoutCast, + elems_per_thread()>( + data, remaining, input_calc, output_calc, loader, storer); + elementwise_kernel_helper(f, policy); + } +#else + CUDA_KERNEL_ASSERT(false && "Fatal! vectorized_elementwise_kernel<8,...> supports only sm_90 and sm_10x. Please report an issue on GitHub."); +#endif // __CUDA_ARCH__ / 100 == 9 || __CUDA_ARCH__ / 100 == 10 + } else { + using traits = function_traits; + constexpr auto io_size = calc_io_size(); + int remaining = N - io_block_work_size() * blockIdx.x; + + if (remaining >= io_block_work_size()) { // if this block has a full `block_work_size` data to handle, use + // vectorized memory access + elementwise_kernel_helper( + f, memory::policies::vectorized()>(data)); + } else { // if this block handles the reminder, + // just do a naive unrolled loop + auto input_calc = TrivialOffsetCalculator(); + auto output_calc = TrivialOffsetCalculator<1>(); + auto loader = memory::LoadWithoutCast(); + auto storer = memory::StoreWithoutCast(); + auto policy = memory::policies::unroll< + array_t, + decltype(input_calc), + decltype(output_calc), + memory::LoadWithoutCast, + memory::StoreWithoutCast, + elems_per_thread()>( + data, remaining, input_calc, output_calc, loader, storer); + elementwise_kernel_helper(f, policy); + } + } +} + +#else // USE_ROCM +template +__forceinline__ __device__ void vectorized_elementwise_kernel_impl(int N, func_t f, array_t data) { + using traits = function_traits; + constexpr auto io_size = calc_io_size(); + constexpr int bws = tws * num_threads(); + int remaining = N - bws * blockIdx.x; + + if (remaining < bws) { // if this block handles the reminder, + // just do a naive unrolled loop + auto input_calc = TrivialOffsetCalculator(); + auto output_calc = TrivialOffsetCalculator<1>(); + auto loader = memory::LoadWithoutCast(); + auto storer = memory::StoreWithoutCast(); + auto policy = memory::policies::unroll< + array_t, + decltype(input_calc), + decltype(output_calc), + memory::LoadWithoutCast, + memory::StoreWithoutCast, + tws>( + data, remaining, input_calc, output_calc, loader, storer); + elementwise_kernel_helper(f, policy); + } else { // if this block has a full `block_work_size` data to handle, use + // vectorized memory access + constexpr auto optimal_vec_size = calc_optimal_vec_size(); + elementwise_kernel_helper( + f, memory::policies::vectorized(data)); + } +} + +template +C10_LAUNCH_BOUNDS_1(num_threads()) +__global__ void vectorized_elementwise_kernel(int N, func_t f, array_t data) { + constexpr auto io_size = calc_io_size(); + constexpr auto tws_942 = 16; + constexpr auto tws = elems_per_thread(); + if (__builtin_amdgcn_processor_is("gfx942")) + return vectorized_elementwise_kernel_impl(N, f, data); + + vectorized_elementwise_kernel_impl(N, f, data); +} +#endif // USE_ROCM + +template < + typename func_t, + typename array_t, + int elems_per_thread, + typename inp_calc_t, + typename out_calc_t, + typename loader_t, + typename storer_t> +C10_LAUNCH_BOUNDS_1(num_threads()) +__global__ void unrolled_elementwise_kernel( + int N, + func_t f, + array_t data, + inp_calc_t ic, + out_calc_t oc, + loader_t l, + storer_t s) { + int remaining = N - elems_per_thread * num_threads() * blockIdx.x; + auto policy = memory::policies:: + unroll( + data, remaining, ic, oc, l, s); + elementwise_kernel_helper(f, policy); +} + +// this function assume trivial 1d and no dynamic casting +template +static inline void launch_vectorized_kernel( + int64_t N, + const func_t& f, + array_t data) { + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + using traits = function_traits; + constexpr auto io_size = calc_io_size(); + auto stream = at::cuda::getCurrentCUDAStream(); +#ifdef USE_ROCM + int vec_size = memory::can_vectorize_up_to(data); + c10::DeviceIndex curDevice = -1; + AT_CUDA_CHECK(c10::cuda::GetDevice(&curDevice)); + // Similar check in vectorized_elementwise_kernel() as well. Both should be in sync. + int tws = at::detail::getCUDAHooks().isGPUArch({"gfx942"}, curDevice) ? 16 : elems_per_thread(); +#else + using cpp_type = typename function_traits::result_type; + const uint16_t max_vec_size = memory::can_vectorize_up_to(data); + uint16_t vec_size = 16 / static_cast(sizeof(cpp_type)); + vec_size = std::min(vec_size, max_vec_size); + // due to excessive binary size the `vectorized_elementwise_kernel` of + // the size 8 is compiled for sm_90 and sm_10x only. + // TODO: Lift this limitation when CUDA 12.x support is fully dropped + cudaDeviceProp* p = at::cuda::getDeviceProperties(stream.device().index()); + if (p->major != 9 && p->major != 10) { + vec_size = std::min(vec_size, 4); + } +#if !defined(CUDA_VERSION) || CUDA_VERSION < 12080 + if constexpr (sizeof(cpp_type) < 2) { + vec_size = std::min(vec_size, 4); + } +#endif + int tws = elems_per_thread(); +#endif + int bws = tws * num_threads(); + int64_t grid = (N + bws - 1) / bws; + switch (vec_size) { +#ifdef USE_ROCM + case 16: + vectorized_elementwise_kernel<16, func_t, array_t> + <<>>(N, f, data); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; +#endif + case 8: + vectorized_elementwise_kernel<8, func_t, array_t> + <<>>(N, f, data); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 4: + vectorized_elementwise_kernel<4, func_t, array_t> + <<>>(N, f, data); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 2: + vectorized_elementwise_kernel<2, func_t, array_t> + <<>>(N, f, data); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 1: { + auto input_calc = TrivialOffsetCalculator(); + auto output_calc = TrivialOffsetCalculator<1>(); + auto loader = memory::LoadWithoutCast(); + auto storer = memory::StoreWithoutCast(); + int64_t grid_unrolled = (N + elementwise_block_work_size() - 1) / elementwise_block_work_size(); + unrolled_elementwise_kernel + <<>>( + N, f, data, input_calc, output_calc, loader, storer); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + default: + TORCH_INTERNAL_ASSERT(false, "Unexpected vectorization size"); + } +} + +#ifdef USE_ROCM +template < + int vec_size, + typename func_t, + typename array_t, + typename inp_calc_t, + typename out_calc_t, + typename loader_t, + typename storer_t, + typename OutputType, + typename... InputTypes> +C10_LAUNCH_BOUNDS_1(vectorized_templated_config::num_threads()) +__global__ void vectorized_templated_elementwise_kernel( + int N, + func_t f, + array_t data, + inp_calc_t inp_calc, + out_calc_t out_calc, + loader_t loader, + storer_t storer) { + int remaining = N - + vectorized_templated_config::block_work_size() * + (gridDim.x - blockIdx.x - 1); + constexpr bool reverted_idx = true; + + if (remaining < + vectorized_templated_config::block_work_size()) { // if this block handles + // the reminder, + // just do a naive unrolled loop + auto policy = memory::policies::unroll_base< + vectorized_templated_config::num_threads(), + array_t, + inp_calc_t, + out_calc_t, + loader_t, + storer_t, + vectorized_templated_config::elems_per_thread()>( + data, remaining, inp_calc, out_calc, loader, storer); + elementwise_kernel_helper(f, policy); + } else { // if this block has a full `block_work_size` data to handle, use + // vectorized memory access + auto policy = memory::policies::vectorized_templated< + vec_size, + array_t, + vectorized_templated_config::elems_per_thread(), + vectorized_templated_config::num_threads(), + OutputType, + InputTypes...>(data); + elementwise_kernel_helper(f, policy); + } +} + +// This function assume trivial 1d and supports template specialization +// to avoid dynamic casting. +// Input vectorization size is based on runtime information, i.e. +// the actual data types of the input and output tensor and cannot +// be determined using the functor type, as in regular non-templated +// vectorized kernels. The caller is in charge of selecting the correct input +// vectorization length. +template < + typename func_t, + typename array_t, + typename inp_calc_t, + typename out_calc_t, + typename loader_t, + typename storer_t, + typename OutputType, + typename... InputTypes> +static inline void launch_vectorized_templated_kernel( + int64_t N, + const func_t& f, + array_t data, + inp_calc_t ic, + out_calc_t oc, + loader_t l, + storer_t s) { + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + int64_t grid = (N + vectorized_templated_config::block_work_size() - 1) / + vectorized_templated_config::block_work_size(); + auto stream = at::cuda::getCurrentCUDAStream(); + int vec_size = memory::can_vectorize_up_to(data); + switch (vec_size) { + case 8: + vectorized_templated_elementwise_kernel< + 8, + func_t, + array_t, + inp_calc_t, + out_calc_t, + loader_t, + storer_t, + OutputType, + InputTypes...> + <<>>( + N, f, data, ic, oc, l, s); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 4: + vectorized_templated_elementwise_kernel< + 4, + func_t, + array_t, + inp_calc_t, + out_calc_t, + loader_t, + storer_t, + OutputType, + InputTypes...> + <<>>( + N, f, data, ic, oc, l, s); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 2: + vectorized_templated_elementwise_kernel< + 2, + func_t, + array_t, + inp_calc_t, + out_calc_t, + loader_t, + storer_t, + OutputType, + InputTypes...> + <<>>( + N, f, data, ic, oc, l, s); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + default: + // vector size 1 is not handled as part of vectorize_templated kernel + TORCH_INTERNAL_ASSERT(false, "Unexpected vectorization size"); + } +} +#endif + +template < + typename func_t, + typename array_t, + typename inp_calc_t, + typename out_calc_t, + typename loader_t, + typename storer_t> +static inline void launch_unrolled_kernel( + int64_t N, + const func_t& f, + array_t data, + inp_calc_t ic, + out_calc_t oc, + loader_t l, + storer_t s) { + TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits::max()); + + int64_t grid = (N + elementwise_block_work_size() - 1) / elementwise_block_work_size(); + auto stream = at::cuda::getCurrentCUDAStream(); + unrolled_elementwise_kernel + <<>>(N, f, data, ic, oc, l, s); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +template +C10_LAUNCH_BOUNDS_2(nt, 4) +__global__ void elementwise_kernel(int N, func_t f) { + int tid = threadIdx.x; + int nv = nt * vt; + int idx = nv * blockIdx.x + tid; +#pragma unroll + for (int i = 0; i < vt; i++) { + if (idx < N) { + f(idx); + idx += nt; + } + } +} + +template +static void launch_legacy_kernel(int64_t N, const func_t& f) { + TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits::max()); + if (N == 0) { + return; + } + dim3 block(nt); + dim3 grid((N + block.x * vt - 1) / (block.x * vt)); + auto stream = at::cuda::getCurrentCUDAStream(); + elementwise_kernel<<>>(N, f); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} + +#ifdef USE_ROCM +template +C10_LAUNCH_BOUNDS_2(nt, 4) +__global__ void elementwise_kernel_manual_unroll(int N, func_t f) { + int tid = threadIdx.x; + constexpr int nv = nt * vt; + int idx = nv * blockIdx.x + tid; + if ((idx + nt*(vt-1)) < N) { + f(idx, true); + } else { +#pragma unroll + for (int i = 0; i < vt; i++) { + if (idx < N) { + f(idx, false); + idx += nt; + } + } + } +} + +template +static void launch_legacy_kernel_manual_unroll(int64_t N, const func_t& f) { + TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits::max()); + if (N == 0) { + return; + } + dim3 block(nt); + dim3 grid((N + block.x * vt - 1) / (block.x * vt)); + auto stream = at::cuda::getCurrentCUDAStream(); + elementwise_kernel_manual_unroll<<>>(N, f); + C10_CUDA_KERNEL_LAUNCH_CHECK(); +} +#endif + +template +C10_HOST_DEVICE typename traits::result_type invoke_impl( + const func_t& f, + char* const C10_RESTRICT data[], + const index_t strides[], + int i, + std::index_sequence) { + (void)strides; + (void)i; + return f(c10::load::type>( + data[INDEX] + i * strides[INDEX])...); +} + +template < + typename func_t, + typename index_t, + typename traits = function_traits> +C10_HOST_DEVICE typename traits::result_type invoke( + const func_t& f, + char* const C10_RESTRICT data[], + const index_t strides[], + int i) { + using Indices = std::make_index_sequence; + return invoke_impl(f, data, strides, i, Indices{}); +} + +template +C10_HOST_DEVICE typename traits::result_type invoke_impl( + const func_t& f, + char* const C10_RESTRICT data[], + const index_t strides[], + const ScalarType dtypes[], + int i, + std::index_sequence) { + (void)strides; + (void)i; + return f(c10::fetch_and_cast::type>( + dtypes[I], data[I] + i * strides[I])...); +} + +template < + typename func_t, + typename index_t, + typename traits = function_traits> +C10_HOST_DEVICE typename traits::result_type invoke( + const func_t& f, + char* const C10_RESTRICT data[], + const index_t strides[], + const ScalarType dtypes[], + int i) { + using Indices = std::make_index_sequence; + return invoke_impl(f, data, strides, dtypes, i, Indices{}); +} + +template +void gpu_kernel_impl_nocast(TensorIteratorBase& iter, const func_t& f) { + using traits = function_traits; + using arg0_t = typename traits::result_type; + constexpr int ntensors = traits::arity + 1; + + TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing()); + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + + std::array data; + for (int i = 0; i < ntensors; i++) { + data[i] = (char*)iter.data_ptr(i); + } + + int64_t numel = iter.numel(); + + bool contiguous = iter.is_contiguous(); + + if (contiguous) { + return launch_vectorized_kernel(numel, f, data); + } + auto offset_calc = ::make_offset_calculator(iter); +#ifndef USE_ROCM + constexpr int unroll_factor = sizeof(arg0_t) >= 4 ? 2 : 4; + launch_legacy_kernel<128, unroll_factor>(numel, [=] GPU_LAMBDA(int idx) { + auto offsets = offset_calc.get(idx); + arg0_t* out = (arg0_t*)(data[0] + offsets[0]); + *out = invoke(f, &data[1], &offsets[1], 1); + }); +#else + constexpr int unroll_factor = sizeof(arg0_t) >= 4 ? 4 : 8; + constexpr int grp_sz = 128; + launch_legacy_kernel_manual_unroll(numel, [=] GPU_LAMBDA(int idx, bool unrl) { + if (unrl) { + if constexpr (unroll_factor == 4) { + auto offsets0 = offset_calc.get(idx); + auto offsets1 = offset_calc.get(idx+grp_sz); + auto offsets2 = offset_calc.get(idx+grp_sz*2); + auto offsets3 = offset_calc.get(idx+grp_sz*3); + arg0_t* out0 = (arg0_t*)(data[0] + offsets0[0]); + arg0_t* out1 = (arg0_t*)(data[0] + offsets1[0]); + arg0_t* out2 = (arg0_t*)(data[0] + offsets2[0]); + arg0_t* out3 = (arg0_t*)(data[0] + offsets3[0]); + auto tmp0 = invoke(f, &data[1], &offsets0[1], 1); + auto tmp1 = invoke(f, &data[1], &offsets1[1], 1); + auto tmp2 = invoke(f, &data[1], &offsets2[1], 1); + auto tmp3 = invoke(f, &data[1], &offsets3[1], 1); + *out0 = tmp0; + *out1 = tmp1; + *out2 = tmp2; + *out3 = tmp3; + } else { + auto offsets0 = offset_calc.get(idx); + auto offsets1 = offset_calc.get(idx+grp_sz); + auto offsets2 = offset_calc.get(idx+grp_sz*2); + auto offsets3 = offset_calc.get(idx+grp_sz*3); + auto offsets4 = offset_calc.get(idx+grp_sz*4); + auto offsets5 = offset_calc.get(idx+grp_sz*5); + auto offsets6 = offset_calc.get(idx+grp_sz*6); + auto offsets7 = offset_calc.get(idx+grp_sz*7); + arg0_t* out0 = (arg0_t*)(data[0] + offsets0[0]); + arg0_t* out1 = (arg0_t*)(data[0] + offsets1[0]); + arg0_t* out2 = (arg0_t*)(data[0] + offsets2[0]); + arg0_t* out3 = (arg0_t*)(data[0] + offsets3[0]); + arg0_t* out4 = (arg0_t*)(data[0] + offsets4[0]); + arg0_t* out5 = (arg0_t*)(data[0] + offsets5[0]); + arg0_t* out6 = (arg0_t*)(data[0] + offsets6[0]); + arg0_t* out7 = (arg0_t*)(data[0] + offsets7[0]); + auto tmp0 = invoke(f, &data[1], &offsets0[1], 1); + auto tmp1 = invoke(f, &data[1], &offsets1[1], 1); + auto tmp2 = invoke(f, &data[1], &offsets2[1], 1); + auto tmp3 = invoke(f, &data[1], &offsets3[1], 1); + auto tmp4 = invoke(f, &data[1], &offsets4[1], 1); + auto tmp5 = invoke(f, &data[1], &offsets5[1], 1); + auto tmp6 = invoke(f, &data[1], &offsets6[1], 1); + auto tmp7 = invoke(f, &data[1], &offsets7[1], 1); + *out0 = tmp0; + *out1 = tmp1; + *out2 = tmp2; + *out3 = tmp3; + *out4 = tmp4; + *out5 = tmp5; + *out6 = tmp6; + *out7 = tmp7; + } + } else { + auto offsets = offset_calc.get(idx); + arg0_t* out = (arg0_t*)(data[0] + offsets[0]); + *out = invoke(f, &data[1], &offsets[1], 1); + } + }); +#endif +} + +#ifdef USE_ROCM +namespace { +template < + typename TupleLike, + typename FirstParamTy, + typename SecondParamTy, + size_t arity, + size_t arg_num = 0> +struct check_binary_functor_types_for_specialization { + constexpr static inline bool check() { + if constexpr (arity != 2) + return false; + if constexpr (arg_num == 0) { + using SelectedType = std::tuple_element_t; + if constexpr (std::is_same_v) + return check_binary_functor_types_for_specialization< + TupleLike, + FirstParamTy, + SecondParamTy, + arity, + arg_num + 1>::check(); + } else if constexpr (arg_num == 1) { + using SelectedType2 = std::tuple_element_t; + if constexpr (std::is_same_v) + return check_binary_functor_types_for_specialization< + TupleLike, + FirstParamTy, + SecondParamTy, + arity, + arg_num + 1>::check(); + } + return false; + } +}; + +// Bottom case: if we got this far, assume correct type matching except +// when there are no arguments (arity == 0). +template < + typename TupleLike, + typename FirstParamTy, + typename SecondParamTy, + size_t arity> +struct check_binary_functor_types_for_specialization< + TupleLike, + FirstParamTy, + SecondParamTy, + arity, + arity> { + constexpr static inline bool check() { + if constexpr (arity != 0) + return true; + return false; + } +}; + +template +struct check_binary_functor_types_for_specialization< + TupleLike, + FirstParamTy, + SecondParamTy, + 0, + 0> { + constexpr static inline bool check() { + return false; + } +}; + +// The following is a list of type specializations for vectorized_templated +// elementwise kernel. The three types refer to runtime types of the output +// tensor, first tensor argument, and the second tensor argument used for a +// binary functor. +constexpr std::array rt_binary_specializations = { + std::array( + {c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value}), + std::array( + {c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value}), + std::array( + {c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value}), + std::array( + {c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value}), + std::array( + {c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value}), + std::array( + {c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value, + c10::CppTypeToScalarType::value})}; + +bool check_binary_rt_types_for_specialization(TensorIteratorBase& iter) { + if (iter.ninputs() != 2) + return false; + for (auto spec : rt_binary_specializations) + if (iter.dtype(0) == spec[0] && iter.input_dtype(0) == spec[1] && + iter.input_dtype(1) == spec[2]) + return true; + return false; +} + +template +struct type_specialized_kernel_launcher { + template < + typename func_t, + typename array_t, + typename inp_calc_t, + typename out_calc_t, + typename loader_t, + typename storer_t> + static void apply( + ScalarType ret_t, + ScalarType arg0_t, + ScalarType arg1_t, + int64_t numel, + func_t f, + array_t data, + inp_calc_t input_offset_calculator, + out_calc_t output_offset_calculator, + loader_t loader, + storer_t storer) { + constexpr ScalarType sret_t = rt_binary_specializations[arg_index][0]; + constexpr ScalarType sarg0_t = rt_binary_specializations[arg_index][1]; + constexpr ScalarType sarg1_t = rt_binary_specializations[arg_index][2]; + if (ret_t == sret_t && arg0_t == sarg0_t && arg1_t == sarg1_t) { + using cret_t = c10::impl::ScalarTypeToCPPTypeT; + using carg0_t = c10::impl::ScalarTypeToCPPTypeT; + using carg1_t = c10::impl::ScalarTypeToCPPTypeT; + launch_vectorized_templated_kernel< + func_t, + array_t, + inp_calc_t, + out_calc_t, + loader_t, + storer_t, + cret_t, + carg0_t, + carg1_t>( + numel, + f, + data, + input_offset_calculator, + output_offset_calculator, + loader, + storer); + } + } +}; + +template +struct type_specialized_broadcast_kernel_launcher { + template < + typename func_t, + typename array_t, + typename dtypes_t, + typename calc_t> + static void apply( + int64_t numel, + func_t f, + array_t data, + dtypes_t dtypes, + calc_t offset_calc) { + using traits = function_traits; + using ret_t = typename traits::result_type; + using arg0_t = typename traits::template arg<0>::type; + using arg1_t = typename traits::template arg<1>::type; + if (dtypes[0] == rt_binary_specializations[arg_index][0] && + dtypes[1] == rt_binary_specializations[arg_index][1] && + dtypes[2] == rt_binary_specializations[arg_index][2]) { + using ret_cpp_t = c10::impl::ScalarTypeToCPPTypeT; + using arg0_cpp_t = c10::impl::ScalarTypeToCPPTypeT; + using arg1_cpp_t = c10::impl::ScalarTypeToCPPTypeT; + constexpr int grp_sz = 128; + launch_legacy_kernel_manual_unroll(numel, [=] GPU_LAMBDA(int idx, bool unrl) { + if (unrl) { + auto offsets0 = offset_calc.get(idx); + auto offsets1 = offset_calc.get(idx + grp_sz); + auto offsets2 = offset_calc.get(idx + grp_sz * 2); + auto offsets3 = offset_calc.get(idx + grp_sz * 3); + void* out0 = data[0] + offsets0[0]; + void* out1 = data[0] + offsets1[0]; + void* out2 = data[0] + offsets2[0]; + void* out3 = data[0] + offsets3[0]; + auto u = c10::load(data[1] + offsets0[1]); + auto v = c10::load(data[2] + offsets0[2]); + ret_t result0 = f(c10::convert(u), c10::convert(v)); + auto u1 = c10::load(data[1] + offsets1[1]); + auto v1 = c10::load(data[2]+ offsets1[2]); + ret_t result1 = f(c10::convert(u1), c10::convert(v1)); + auto u2 = c10::load(data[1] + offsets2[1]); + auto v2 = c10::load(data[2] + offsets2[2]); + ret_t result2 = f(c10::convert(u2), c10::convert(v2)); + auto u3 = c10::load(data[1] + offsets3[1]); + auto v3 = c10::load(data[2] + offsets3[2]); + ret_t result3 = f(c10::convert(u3), c10::convert(v3)); + *(ret_cpp_t*)out0 = c10::convert(result0); + *(ret_cpp_t*)out1 = c10::convert(result1); + *(ret_cpp_t*)out2 = c10::convert(result2); + *(ret_cpp_t*)out3 = c10::convert(result3); + } else { + auto offsets = offset_calc.get(idx); + void* out = data[0] + offsets[0]; + auto u = c10::load(data[1] + offsets[1]); + auto v = c10::load(data[2] + offsets[2]); + ret_t result = f(c10::convert(u), c10::convert(v)); + *(ret_cpp_t*)out = c10::convert(result); + } + }); + } + } +}; + +} // namespace +#endif + +template +void gpu_kernel_impl(TensorIteratorBase& iter, const func_t& f) { + if (!needs_dynamic_casting::check(iter)) { + return gpu_kernel_impl_nocast(iter, f); + } + using traits = function_traits; + using arg0_t = typename traits::result_type; + constexpr int ntensors = traits::arity + 1; + + TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing()); + TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity); + TORCH_INTERNAL_ASSERT(iter.noutputs() == 1); + + std::array data; + for (int i = 0; i < ntensors; i++) { + data[i] = (char*)iter.data_ptr(i); + } + + int64_t numel = iter.numel(); + + bool contiguous = iter.is_contiguous(); + + if (contiguous) { +#ifdef USE_ROCM + // Attempt to call specialized vectorized elementwise kernel + // that enables interleaving. + if (check_binary_rt_types_for_specialization(iter) && + memory::can_vectorize_up_to(data) > 1) { + // constexpr to reduce the amount of kernels generated for + // vectorized templated elementwise and limit which functors are actually + // applied to the load and store at compile time. + using func_tuple = typename traits::ArgsTuple; + if constexpr ( + std::is_same_v && traits::arity == 2 && + check_binary_functor_types_for_specialization< + func_tuple, + float, + float, + traits::arity, + /*arg_num=*/0>::check()) { + // If we got here, we know we are in one of the specialized cases. We + // need to translate the runtime type to a statically known type. This + // is effectively hoisting to the host the switch over runtime type in + // the kernel in fetch_and_cast. Loader, storer, offset calculators are + // only needed for the reminder loop. + auto input_offset_calculator = TrivialOffsetCalculator(); + auto output_offset_calculator = TrivialOffsetCalculator<1>(); + auto loader = memory::LoadWithCast(iter); + auto storer = memory::StoreWithCast<1>(iter); + memory::detail::static_unroll< + type_specialized_kernel_launcher, + rt_binary_specializations.size()>:: + with_args( + iter.dtype(0), + iter.input_dtype(0), + iter.input_dtype(1), + numel, + f, + data, + input_offset_calculator, + output_offset_calculator, + loader, + storer); + return; + } + } + std::array dtypes; + auto inner_strides = iter.get_inner_strides(); + std::array strides; + for (int i = 0; i < ntensors; i++) { + dtypes[i] = iter.dtype(i); + strides[i] = inner_strides[i]; + } + constexpr int grp_sz = 128; + launch_legacy_kernel_manual_unroll(numel, [=] GPU_LAMBDA(int idx, bool unrl) { + if (unrl) { + void* out0 = data[0] + strides[0] * idx; + void* out1 = data[0] + strides[0] * (idx + grp_sz); + void* out2 = data[0] + strides[0] * (idx + grp_sz * 2); + void* out3 = data[0] + strides[0] * (idx + grp_sz * 3); + arg0_t result0 = invoke(f, &data[1], &strides[1], &dtypes[1], idx); + arg0_t result1 = invoke(f, &data[1], &strides[1], &dtypes[1], (idx + grp_sz)); + arg0_t result2 = invoke(f, &data[1], &strides[1], &dtypes[1], (idx + grp_sz * 2)); + arg0_t result3 = invoke(f, &data[1], &strides[1], &dtypes[1], (idx + grp_sz * 3)); + c10::cast_and_store(dtypes[0], out0, result0); + c10::cast_and_store(dtypes[0], out1, result1); + c10::cast_and_store(dtypes[0], out2, result2); + c10::cast_and_store(dtypes[0], out3, result3); + } else { + void* out = data[0] + strides[0] * idx; + arg0_t result = invoke(f, &data[1], &strides[1], &dtypes[1], idx); + c10::cast_and_store(dtypes[0], out, result); + } + }); +#else + auto loader = memory::LoadWithCast(iter); + auto storer = memory::StoreWithCast<1>(iter); + auto input_offset_calculator = TrivialOffsetCalculator(); + auto output_offset_calculator = TrivialOffsetCalculator<1>(); + launch_unrolled_kernel( + numel, + f, + data, + input_offset_calculator, + output_offset_calculator, + loader, + storer); +#endif + } else { + std::array dtypes; + for (int i = 0; i < ntensors; i++) { + dtypes[i] = iter.dtype(i); + } + auto offset_calc = ::make_offset_calculator(iter); +#ifdef USE_ROCM + if (check_binary_rt_types_for_specialization(iter)) { + // constexpr to reduce the amount of kernels generated for + // broadcast elementwise with mexed dtypes and limit which functors are actually + // applied to the load and store at compile time. + using func_tuple = typename traits::ArgsTuple; + if constexpr ( + std::is_same_v && traits::arity == 2 && + check_binary_functor_types_for_specialization< + func_tuple, + float, + float, + traits::arity, + /*arg_num=*/0>::check()) { + memory::detail::static_unroll< + type_specialized_broadcast_kernel_launcher, + rt_binary_specializations.size()>::with_args( + numel, + f, + data, + dtypes, + offset_calc + ); + return; + } + } + + constexpr int grp_sz = 128; + launch_legacy_kernel_manual_unroll(numel, [=] GPU_LAMBDA(int idx, bool unrl) { + if (unrl) { + auto offsets0 = offset_calc.get(idx); + auto offsets1 = offset_calc.get(idx + grp_sz); + auto offsets2 = offset_calc.get(idx + grp_sz * 2); + auto offsets3 = offset_calc.get(idx + grp_sz * 3); + void* out0 = data[0] + offsets0[0]; + void* out1 = data[0] + offsets1[0]; + void* out2 = data[0] + offsets2[0]; + void* out3 = data[0] + offsets3[0]; + arg0_t result0 = invoke(f, &data[1], &offsets0[1], &dtypes[1], 1); + arg0_t result1 = invoke(f, &data[1], &offsets1[1], &dtypes[1], 1); + arg0_t result2 = invoke(f, &data[1], &offsets2[1], &dtypes[1], 1); + arg0_t result3 = invoke(f, &data[1], &offsets3[1], &dtypes[1], 1); + c10::cast_and_store(dtypes[0], out0, result0); + c10::cast_and_store(dtypes[0], out1, result1); + c10::cast_and_store(dtypes[0], out2, result2); + c10::cast_and_store(dtypes[0], out3, result3); + } else { + auto offsets = offset_calc.get(idx); + void* out = data[0] + offsets[0]; + arg0_t result = invoke(f, &data[1], &offsets[1], &dtypes[1], 1); + c10::cast_and_store(dtypes[0], out, result); + } + }); +#else + launch_legacy_kernel<128, 4>(numel, [=] GPU_LAMBDA(int idx) { + auto offsets = offset_calc.get(idx); + void* out = data[0] + offsets[0]; + arg0_t result = invoke(f, &data[1], &offsets[1], &dtypes[1], 1); + c10::cast_and_store(dtypes[0], out, result); + }); +#endif + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDAScalar.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDAScalar.cu new file mode 100644 index 0000000000000000000000000000000000000000..9ef8cbfb10cee3706f5432b23abf593c0ca15ebd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CUDAScalar.cu @@ -0,0 +1,84 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include +#include + +namespace at::native { + +namespace { + +bool is_cuda_caching_allocator_tensor(const Tensor& self) { + auto* cuda_allocator = c10::cuda::CUDACachingAllocator::get(); + if (cuda_allocator == nullptr) { + return false; + } + // SymmMem/NVSHMEM/rocSHMEM tensors are typically backed by custom + // from_blob-style deleters, so this check filters them out and keeps + // the direct dereference path limited to allocator-managed CUDA memory. + return self.storage().data_ptr().get_deleter() == cuda_allocator->raw_deleter(); +} + +template +void _local_scalar_dense_cuda_impl(const Tensor& self, Scalar& r) { +#if defined(USE_ROCM) && (ROCM_VERSION >= 70200) + // If this is a large BAR device, we can just read directly from VRAM + if ( + at::cuda::getCurrentDeviceProperties()->isLargeBar && + is_cuda_caching_allocator_tensor(self)) { + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); +#if ROCM_VERSION < 71400 + hipStreamCaptureStatus captureStatus; + C10_CUDA_CHECK(hipStreamGetCaptureInfo(stream, &captureStatus, nullptr)); + if (C10_LIKELY(captureStatus == hipStreamCaptureStatusNone)) { + at::cuda::stream_synchronize(stream); + r = Scalar(*self.template const_data_ptr()); + } else { + C10_CUDA_CHECK(hipErrorStreamCaptureUnsupported); + } +#else // ROCM_VERSION + // HIP reports the errors during graph capture in ROCm 7.14+ + // no StreamCaptureStatus check required + at::cuda::stream_synchronize(stream); + r = Scalar(*self.template const_data_ptr()); +#endif // ROCM_VERSION + return; + } +#endif + + // Create pinned memory for the scalar value to avoid implicit + // locking/sync in cuda library due to pageable memory + auto value = at::detail::empty_cpu( + {1}, /* size */ + c10::CppTypeToScalarType(), /* dtype */ + std::nullopt, /* layout */ + std::nullopt, /* device */ + true, /* pin_memory */ + std::nullopt /* memory format */ + ); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + at::cuda::memcpy_and_sync(value.template mutable_data_ptr(), self.template const_data_ptr(), sizeof(scalar_t), cudaMemcpyDeviceToHost, stream); + r = Scalar(*value.template const_data_ptr()); +} + +} // anonymous namespace + +Scalar _local_scalar_dense_cuda(const Tensor& self) { + Scalar r; + TORCH_CHECK(self.numel() > 0, "_local_scalar_dense: Empty tensor not supported"); + AT_DISPATCH_V2( + self.scalar_type(), "_local_scalar_dense_cuda", AT_WRAP([&] { + _local_scalar_dense_cuda_impl(self, r); + }), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), kComplexHalf, kBComplex32, kHalf, kBool, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)); + return r; +} + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Col2Im.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Col2Im.cu new file mode 100644 index 0000000000000000000000000000000000000000..a8d331ab75519d31202bb1ede60d0963748e7355 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Col2Im.cu @@ -0,0 +1,171 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { +namespace { + +void col2im_out_cuda_template( + Tensor& output, + const Tensor& input_, + IntArrayRef output_size, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride) { + TensorArg input_arg{input_, "input", 1}; + TensorArg output_arg{output, "output", 2}; + checkAllSameGPU(__func__, {input_arg, output_arg}); + + TORCH_CHECK( + output_size.size() == 2, + "It is expected output_size equals to 2, but got size ", + output_size.size()); + + TORCH_CHECK( + kernel_size.size() == 2, + "It is expected kernel_size equals to 2, but got size ", + kernel_size.size()); + + TORCH_CHECK( + dilation.size() == 2, + "It is expected dilation equals to 2, but got size ", + dilation.size()); + + TORCH_CHECK( + padding.size() == 2, + "It is expected padding equals to 2, but got size ", + padding.size()); + + TORCH_CHECK( + stride.size() == 2, + "It is expected stride equals to 2, but got size ", + stride.size()); + + int64_t output_height = output_size[0]; + int64_t output_width = output_size[1]; + int64_t kernel_height = kernel_size[0]; + int64_t kernel_width = kernel_size[1]; + int64_t dilation_height = dilation[0]; + int64_t dilation_width = dilation[1]; + int64_t pad_height = padding[0]; + int64_t pad_width = padding[1]; + int64_t stride_height = stride[0]; + int64_t stride_width = stride[1]; + + col2im_shape_check( + input_, + Tensor(), + output_height, + output_width, + kernel_height, + kernel_width, + dilation_height, + dilation_width, + pad_height, + pad_width, + stride_height, + stride_width); + + Tensor input = input_.contiguous(); + + bool batched_input = true; + if (input.dim() == 2) { + // Force batch + batched_input = false; + input = input.unsqueeze(0); + } + + int64_t batch_size = input.size(0); + int64_t n_input_plane = input.size(1); + int64_t n_output_plane = n_input_plane / (kernel_width * kernel_height); + int64_t input_batch_stride = input.stride(0); + + output.resize_({batch_size, n_output_plane, output_height, output_width}); + int64_t output_batch_stride = output.stride(0); + + AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND3(kHalf, kBFloat16, kBool, + input.scalar_type(), "col2im_out_cuda", [&] { + int64_t height_col = (output_height + 2 * pad_height - + (dilation_height * (kernel_height - 1) + 1)) / + stride_height + + 1; + int64_t width_col = (output_width + 2 * pad_width - + (dilation_width * (kernel_width - 1) + 1)) / + stride_width + + 1; + + col2im_batched( + at::cuda::getCurrentCUDAStream(), + input.const_data_ptr(), + input_batch_stride, + batch_size, + n_output_plane, + output_height, + output_width, + height_col, + width_col, + kernel_height, + kernel_width, + pad_height, + pad_width, + stride_height, + stride_width, + dilation_height, + dilation_width, + output.mutable_data_ptr(), + output_batch_stride); + + }); + if (!batched_input) { + output = output.squeeze(0); + } +} + +} // namespace + +Tensor& col2im_out_cuda(const Tensor& input, + IntArrayRef output_size, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride, + Tensor& output) { + col2im_out_cuda_template( + output, input, output_size, kernel_size, dilation, padding, stride); + return output; +} + +Tensor col2im_cuda( + const Tensor& input, + IntArrayRef output_size, + IntArrayRef kernel_size, + IntArrayRef dilation, + IntArrayRef padding, + IntArrayRef stride) { + Tensor output = at::empty_like(input, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + + col2im_out_cuda_template( + output, input, output_size, kernel_size, dilation, padding, stride); + return output; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompareEQKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompareEQKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..5cd79a2e825b265c4576e223c23473888f026ab0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompareEQKernel.cu @@ -0,0 +1,50 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include + + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { namespace { + +enum class EqOpType {EQ, NE}; + +template +struct CompareEqFunctor{ + CompareEqFunctor(EqOpType op): op_(op) {} + const EqOpType op_; + __device__ __forceinline__ bool operator() (scalar_t a, scalar_t b) const { + if (op_ == EqOpType::EQ) { + return a == b; + } else { //NE + return a != b; + } + + } + }; +} + +C10_NOINLINE void compare_eq_ne_kernel(TensorIteratorBase &iter, EqOpType op) { + AT_DISPATCH_V2(iter.common_dtype(), "compare_eq_ne_cuda", AT_WRAP([&]() { + opmath_symmetric_gpu_kernel_with_scalars( + iter, CompareEqFunctor(op)); + }), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), kComplexHalf, kBComplex32, kHalf, kBFloat16, kBool, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES), kFloat4_e2m1fn_x2); +} + +void eq_kernel_cuda(TensorIteratorBase& iter) { + compare_eq_ne_kernel(iter, EqOpType::EQ); +} + +void ne_kernel_cuda(TensorIteratorBase& iter) { + compare_eq_ne_kernel(iter, EqOpType::NE); +} + +REGISTER_DISPATCH(eq_stub, &eq_kernel_cuda) +REGISTER_DISPATCH(ne_stub, &ne_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompareKernels.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompareKernels.cu new file mode 100644 index 0000000000000000000000000000000000000000..31fe1da96020ba5826a496edb0e9151b004d40fa --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompareKernels.cu @@ -0,0 +1,103 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include + + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { namespace { + +enum class OpType {GE, GT, LE, LT}; + +template +struct CompareFunctor{ + constexpr CompareFunctor(OpType op): op_(op) {}; + OpType op_; + __device__ __forceinline__ bool operator() (scalar_t a, scalar_t b) const { + if (op_ == OpType::GE) { + return a >= b; + } else if (op_ == OpType::GT) { + return a > b; + } else if (op_ == OpType::LE) { + return a <= b; + } else { //LT + return a < b; + } + } +}; + +// Reflects the comparison operator, so reflect(op)(a, b) == op(b, a) +OpType reflect(OpType x) { + switch (x) { + case OpType::GE: return OpType::LE; + case OpType::GT: return OpType::LT; + case OpType::LE: return OpType::GE; + case OpType::LT: return OpType::GT; + } + TORCH_INTERNAL_ASSERT(false, "Invalid OpType"); +} + +} // namespace (anonymous) + +template +void compare_scalar_kernel(TensorIteratorBase &iter, OpType op, scalar_t rhs) { + CompareFunctor f(op); + gpu_kernel(iter, [=] GPU_LAMBDA (scalar_t lhs) -> bool { + return f(lhs, rhs); + }); +} + +template +void compare_kernel_impl(TensorIteratorBase &iter, OpType op) { + // If either input is a cpu scalar, perform the equivalent comparison + // where the scalar is on the right hand side. This saves us from + // generating two otherwise identical kernels with mirrored + // arguments. + if (iter.is_cpu_scalar(1)) { + const scalar_t lhs = iter.scalar_value(1); + iter.remove_operand(1); + const DeviceGuard device_guard(iter.device(1)); + compare_scalar_kernel(iter, reflect(op), lhs); + } else if (iter.is_cpu_scalar(2)) { + const scalar_t rhs = iter.scalar_value(2); + iter.remove_operand(2); + compare_scalar_kernel(iter, op, rhs); + } else { + CompareFunctor f(op); + gpu_kernel(iter, f); + } +} + +C10_NOINLINE void compare_kernel_with_scalars(TensorIteratorBase &iter, OpType op) { + AT_DISPATCH_ALL_TYPES_AND3(kHalf, kBFloat16, kBool, iter.common_dtype(), "compare_cuda", [&]() { + compare_kernel_impl(iter, op); + }); +} + + +void ge_kernel_cuda(TensorIteratorBase& iter) { + compare_kernel_with_scalars(iter, OpType::GE); +} + +void gt_kernel_cuda(TensorIteratorBase& iter) { + compare_kernel_with_scalars(iter, OpType::GT); +} + +void le_kernel_cuda(TensorIteratorBase& iter) { + compare_kernel_with_scalars(iter, OpType::LE); +} + +void lt_kernel_cuda(TensorIteratorBase& iter) { + compare_kernel_with_scalars(iter, OpType::LT); +} + +REGISTER_DISPATCH(ge_stub, &ge_kernel_cuda) +REGISTER_DISPATCH(gt_stub, >_kernel_cuda) +REGISTER_DISPATCH(le_stub, &le_kernel_cuda) +REGISTER_DISPATCH(lt_stub, <_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ComplexKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ComplexKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..c8d6df00f5e4dda7a981aa93c7af4e745a886c5c --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ComplexKernel.cu @@ -0,0 +1,36 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { +namespace { + +void complex_kernel_cuda(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES_AND(kHalf, iter.input_dtype(0), "complex_cuda", [&]() { + gpu_kernel( + iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> c10::complex { + return c10::complex(a, b); + }); + }); +} + +void polar_kernel_cuda(TensorIterator& iter) { + AT_DISPATCH_FLOATING_TYPES(iter.input_dtype(0), "polar_cuda", [&]() { + gpu_kernel( + iter, [] GPU_LAMBDA(scalar_t a, scalar_t b) -> c10::complex { + return c10::complex(a * std::cos(b), a * std::sin(b)); + }); + }); +} + +} // anonymous namespace + +REGISTER_DISPATCH(complex_stub, &complex_kernel_cuda) +REGISTER_DISPATCH(polar_stub, &polar_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompositeRandomAccessor.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompositeRandomAccessor.h new file mode 100644 index 0000000000000000000000000000000000000000..aa42e4bc0869b2b4a01bfccb491e591a85b03340 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CompositeRandomAccessor.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include + +namespace at { namespace native { + +struct TupleInfoCPU { + template + using tuple = thrust::tuple; + + template + static constexpr auto tie(Types&... args) noexcept { + return thrust::tie(args...); + } +}; + +template +using CompositeRandomAccessorCPU = + CompositeRandomAccessor; + +template +void swap( + references_holder rh1, + references_holder rh2 +) { + thrust::swap(rh1.data(), rh2.data()); +} + +template +auto get(references_holder rh) -> decltype(thrust::get(rh.data())) { + return thrust::get(rh.data()); +} + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ConvolutionMM2d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ConvolutionMM2d.cu new file mode 100644 index 0000000000000000000000000000000000000000..5c13921112996be8ca5da296efd613b3c02190ac --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ConvolutionMM2d.cu @@ -0,0 +1,502 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace at::native { +namespace { + +void slow_conv2d_shape_check( + const Tensor& input, const Tensor& grad_output, + const Tensor& weight, const Tensor& bias, + int64_t kH, int64_t kW, + int64_t dH, int64_t dW, + int64_t padH, int64_t padW, + bool weight_nullable) { + TORCH_CHECK(kW > 0 && kH > 0, + "kernel size should be greater than zero, but got kH: ", kH, " kW: ", kW); + TORCH_CHECK(dW > 0 && dH > 0, + "stride should be greater than zero, but got dH: ", dH, " dW: ", dW); + + TORCH_CHECK(weight_nullable || weight.defined(), + "weight tensor is expected to be non-nullable"); + TORCH_CHECK(!weight.defined() || + ((weight.numel() > 0) && (weight.dim() == 2)), + "non-empty 2D weight tensor expected, but got: ", weight.sizes()); + TORCH_CHECK(!bias.defined() || (bias.dim() == 1 && bias.sizes()[0] == weight.sizes()[0]), + "Expected bias to have shape [", weight.sizes()[0], "] but got ", bias.sizes()); + + const auto in_sizes = input.sizes(); + constexpr int ndim = 4; + constexpr int dimf = 1; + constexpr int dimh = 2; + constexpr int dimw = 3; + TORCH_CHECK(in_sizes.size() == ndim, "Expected 4D input tensor, but got ", in_sizes); + + // Allow for empty batch size but not other dimensions + const bool valid_empty = c10::multiply_integers(in_sizes.slice(1)) != 0; + TORCH_CHECK(valid_empty, "non-empty input tensor expected but got: ", in_sizes); + + int64_t inputHeight = in_sizes[dimh]; + int64_t inputWidth = in_sizes[dimw]; + + int64_t exactInputHeight = inputHeight + 2 * padH; + int64_t exactInputWidth = inputWidth + 2 * padW; + + TORCH_CHECK(exactInputHeight >= kH && exactInputWidth >= kW, + "Calculated padded input size per channel: ", + IntArrayRef{exactInputHeight, exactInputWidth}, + ". Kernel size: ", IntArrayRef{kH, kW}, + ". Kernel size can't be greater than actual input size"); + + // NOTE: can't use conv_output_size if the weight isn't defined + auto outputHeight = div_rtn(exactInputHeight - kH, dH) + 1; + auto outputWidth = div_rtn(exactInputWidth - kW, dW) + 1; + + TORCH_CHECK(outputWidth >= 1 && outputHeight >= 1, + "Given input size per channel: ", + IntArrayRef{inputHeight, inputWidth}, + ". Calculated output size per channel: ", + IntArrayRef{outputHeight, outputWidth}, + ". Output size is too small"); + + if (weight.defined()) { + const auto w_sizes = weight.sizes(); + int64_t nInputPlane = w_sizes[1]; + if (w_sizes.size() == 2) { + nInputPlane /= (kH * kW); + } + TORCH_CHECK(in_sizes[dimf] == nInputPlane, + "Expected input dim ", dimf, " to have size ", nInputPlane, + " but got ", in_sizes[dimf]); + } + + if (grad_output.defined()) { + const auto gO_sizes = grad_output.sizes(); + TORCH_CHECK(gO_sizes.size() == ndim, + "Expected grad_output to have ", ndim, + " dimensions but got shape", gO_sizes); + + if (weight.defined()) { + const auto w_sizes = weight.sizes(); + TORCH_CHECK(gO_sizes[dimf] == w_sizes[0], + "Expected dim ", dimf, " to have size ", w_sizes[0], + " but got ", gO_sizes[dimf]); + } else if (bias.defined()) { + const auto b_sizes = bias.sizes(); + int64_t nOutputPlane = b_sizes.empty() ? 1 : b_sizes[0]; + TORCH_CHECK(gO_sizes[dimf] == nOutputPlane, + "Expected grad_output dim ", dimf, " to have size ", + nOutputPlane, " but got ", gO_sizes[dimf]); + } + TORCH_CHECK(gO_sizes[dimh] == outputHeight, + "Expected grad_output dim ", dimh, " to have size ", + outputHeight, " but got ", gO_sizes[dimh]); + TORCH_CHECK(gO_sizes[dimw] == outputWidth, + "Expected grad_output dim ", dimw, " to have size ", + outputWidth, " but got ", gO_sizes[dimw]); + } +} + +Tensor new_view_weight_MM2d(const Tensor& weight_) { + auto weight = weight_.expect_contiguous(); + const auto w_sizes = weight->sizes(); + TORCH_CHECK(w_sizes.size() == 4); + int64_t s1 = w_sizes[0]; + int64_t s2 = c10::multiply_integers(w_sizes.slice(1)); + return weight->view({s1, s2}); +} + +void slow_conv2d_forward( + const Tensor &input, + const Tensor &output, + const Tensor &weight_, + const Tensor &bias, + int64_t kH, int64_t kW, + int64_t dH, int64_t dW, + int64_t padH, int64_t padW) { + auto weight = new_view_weight_MM2d(weight_); + slow_conv2d_shape_check( + input, {}, weight, bias, kH, kW, dH, dW, padH, padW, /*weight_nullable*/false); + + constexpr int dimf = 1; + constexpr int dimh = 2; + constexpr int dimw = 3; + + auto in_sizes = input.sizes(); + int64_t batchSize = in_sizes[0]; + int64_t nInputPlane = in_sizes[dimf]; + int64_t inputHeight = in_sizes[dimh]; + int64_t inputWidth = in_sizes[dimw]; + int64_t nOutputPlane = weight.sizes()[0]; + int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; + int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; + + // Resize output + resize_output(output, {batchSize, nOutputPlane, outputHeight, outputWidth}); + + // Create temporary columns + at::Tensor columns; + + const bool requires_columns = ( + kW != 1 || kH != 1 || dW != 1 || dH != 1 || padH != 0 || padW != 0); + + if (requires_columns) { + columns = at::empty({nInputPlane * kW * kH, outputHeight * outputWidth}, input.options()); + } + + if (bias.defined()) { + TORCH_CHECK(bias.scalar_type() == input.scalar_type(), + "Expected bias to have type ", input.scalar_type(), + " but got ", bias.scalar_type()); + output.copy_(bias.view({-1, 1, 1})); + } else { + output.zero_(); + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "slow_conv2d_cuda", [&] { + // For each elt in batch, do: + for (int elt = 0; elt < batchSize; elt ++) { + // Matrix multiply per output: + auto input_n = input.select(0, elt); + auto output_n = output.select(0, elt); + + if (requires_columns) { + // Extract columns: + at::native::im2col( + c10::cuda::getCurrentCUDAStream(), + input_n.const_data_ptr(), + nInputPlane, inputHeight, inputWidth, + outputHeight, outputWidth, + kH, kW, padH, padW, dH, dW, + 1, 1, + columns.mutable_data_ptr() + ); + } + + // M,N,K are dims of matrix A and B + // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) + int64_t m = nOutputPlane; + int64_t n = outputHeight * outputWidth; + int64_t k = nInputPlane*kH*kW; + + // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) + auto gemm_in_ptr = requires_columns ? + columns.const_data_ptr() : + input_n.const_data_ptr(); + at::cuda::blas::gemm( + 'n', 'n', + n, m, k, + scalar_t(1), + gemm_in_ptr, n, + weight.const_data_ptr(), k, + scalar_t(1), + output_n.mutable_data_ptr(), n + ); + } + }); +} + +void slow_conv2d_backward( + const Tensor &input, + const Tensor &grad_output, + const Tensor &grad_input, + const Tensor &weight_, + const Tensor &grad_columns, + int kH, int kW, + int dH, int dW, + int padH, int padW) { + Tensor weight = new_view_weight_MM2d(weight_); + slow_conv2d_shape_check(input, grad_output, weight, {}, + kH, kW, dH, dW, padH, padW, /*weight_nullable=*/false); + + // Params + auto weight_sizes = weight.sizes(); + int nInputPlane = weight_sizes[1]/(kW*kH); + int nOutputPlane = weight_sizes[0]; + + TORCH_INTERNAL_ASSERT(grad_output.is_contiguous()); + + auto input_sizes = input.sizes(); + int64_t inputWidth = input_sizes[3]; + int64_t inputHeight = input_sizes[2]; + auto output_sizes = grad_output.sizes(); + int64_t outputWidth = output_sizes[3]; + int64_t outputHeight = output_sizes[2]; + + // Batch size + input planes + int64_t batchSize = input_sizes[0]; + + // Resize output + resize_output(grad_input, input_sizes); + TORCH_CHECK(grad_input.is_contiguous(), "grad_input must be contiguous"); + + // Resize temporary columns + resize_output(grad_columns, {nInputPlane*kW*kH, outputHeight*outputWidth}); + TORCH_CHECK(grad_columns.is_contiguous(), "grad_columns must be contiguous"); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "slow_conv2d_backward_cuda", [&] { + // For each elt in batch, do: + for (int elt = 0; elt < batchSize; elt ++) { + // Matrix multiply per sample: + auto grad_input_n = grad_input.select(0, elt); + auto grad_output_n = grad_output.select(0, elt); + + // M,N,K are dims of matrix A and B + // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) + int64_t m = nInputPlane*kW*kH; + int64_t n = grad_columns.sizes()[1]; + int64_t k = nOutputPlane; + + // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) + at::cuda::blas::gemm( + 'n', 't', + n, m, k, + scalar_t(1), + grad_output_n.const_data_ptr(), n, + weight.const_data_ptr(), m, + scalar_t(0), + grad_columns.mutable_data_ptr(), n + ); + + // Unpack columns back into input: + using acc_t = at::acc_type; + at::native::col2im( + c10::cuda::getCurrentCUDAStream(), + grad_columns.const_data_ptr(), + nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, kH, kW, padH, padW, dH, dW, + 1, 1, grad_input_n.mutable_data_ptr() + ); + } + }); +} + +void slow_conv2d_grad_weight( + const Tensor &input, + const Tensor &grad_output, + const Tensor &grad_weight_, + const Tensor &columns, + int64_t kH, int64_t kW, + int64_t dH, int64_t dW, + int64_t padH, int64_t padW) { + TORCH_CHECK(grad_weight_.is_contiguous(), "grad_weight needs to be contiguous"); + auto grad_weight = new_view_weight_MM2d(grad_weight_); + slow_conv2d_shape_check(input, grad_output, grad_weight, {}, + kH, kW, dH, dW, padH, padW, /*weight_nullable=*/true); + + // Params + TORCH_INTERNAL_ASSERT(input.is_contiguous()); + TORCH_INTERNAL_ASSERT(grad_output.is_contiguous()); + + auto input_sizes = input.sizes(); + int64_t nInputPlane = input_sizes[1]; + int64_t nOutputPlane = grad_output.sizes()[1]; + + int64_t inputWidth = input_sizes[3]; + int64_t inputHeight = input_sizes[2]; + int64_t outputWidth = (inputWidth + 2*padW - kW) / dW + 1; + int64_t outputHeight = (inputHeight + 2*padH - kH) / dH + 1; + + // Batch size + input planes + int64_t batchSize = input_sizes[0]; + + // Resize temporary columns + resize_output(columns, {nInputPlane * kH * kW, outputHeight * outputWidth}); + + const bool requires_columns = ( + kW != 1 || kH != 1 || dW != 1 || dH != 1 || padH != 0 || padW != 0); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "slow_conv2d_grad_weight_cuda", [&] { + // For each elt in batch, do: + for (int elt = 0; elt < batchSize; elt ++) { + // Matrix multiply per output: + auto grad_output_n = grad_output.select(0, elt); + + // Matrix multiply per output: + auto input_n = input.select(0, elt); + + if (requires_columns) { + // Extract columns: + at::native::im2col( + c10::cuda::getCurrentCUDAStream(), + input_n.const_data_ptr(), + nInputPlane, inputHeight, inputWidth, + outputHeight, outputWidth, + kH, kW, padH, padW, dH, dW, + 1, 1, + columns.mutable_data_ptr() + ); + } + + // M,N,K are dims of matrix A and B + // (see http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-gemm) + int64_t m = nOutputPlane; + int64_t n = nInputPlane*kW*kH; + int64_t k = columns.sizes()[1]; + + // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) + auto gemm_in_ptr = requires_columns ? + columns.const_data_ptr() : + input_n.const_data_ptr(); + at::cuda::blas::gemm( + 't', 'n', + n, m, k, + scalar_t(1), + gemm_in_ptr, k, + grad_output_n.const_data_ptr(), k, + scalar_t(1), + grad_weight.mutable_data_ptr(), n + ); + } + }); +} + +} // namespace (anonymous) + + +Tensor& slow_conv2d_forward_out_cuda( + const Tensor &self_, + const Tensor &weight_, + IntArrayRef kernel_size, + const std::optional &bias_, + IntArrayRef stride, + IntArrayRef padding, + Tensor &output) { + TORCH_CHECK(kernel_size.size() == 2); + TORCH_CHECK(stride.size() == 2); + TORCH_CHECK(padding.size() == 2); + + auto self = self_.expect_contiguous(); + auto weight = weight_.expect_contiguous(); + auto bias = [&] { + if (bias_.has_value() && bias_->defined()) { + return bias_->expect_contiguous(); + } + return MaybeOwned::owned(std::in_place); + }(); + + slow_conv2d_forward( + *self, + output, + *weight, + *bias, + kernel_size[0], kernel_size[1], + stride[0], stride[1], + padding[0], padding[1] + ); + return output; +} + +Tensor slow_conv2d_forward_cuda( + const Tensor &self, + const Tensor &weight, + IntArrayRef kernel_size, + const std::optional &bias, + IntArrayRef stride, + IntArrayRef padding) { + auto output = at::empty({0}, self.options()); + return slow_conv2d_forward_out_cuda( + self, weight, kernel_size, bias, stride, padding, output); +} + +std::tuple slow_conv2d_backward_out_cuda( + const Tensor& grad_output_, + const Tensor& self_, + const Tensor& weight_, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + Tensor& grad_input, + Tensor& grad_weight, + Tensor& grad_bias) { + auto grad_output = grad_output_.expect_contiguous(); + + Tensor columns = at::empty({0}, self_.options()); + if (grad_input.defined()) { + resize_output(grad_input, self_.sizes()); + auto weight = weight_.expect_contiguous(); + + slow_conv2d_backward( + self_, *grad_output, + grad_input, *weight, + columns, + kernel_size[0], kernel_size[1], + stride[0], stride[1], + padding[0], padding[1]); + } + if (grad_bias.defined()) { + at::sum_out(grad_bias, *grad_output, IntArrayRef{0, 2, 3}); + } + if (grad_weight.defined()) { + resize_output(grad_weight, weight_.sizes()); + grad_weight.zero_(); + auto self = self_.expect_contiguous(); + slow_conv2d_grad_weight( + *self, + *grad_output, + grad_weight, + columns, + kernel_size[0], kernel_size[1], + stride[0], stride[1], + padding[0], padding[1] + ); + } + return std::tuple{ + grad_input, grad_weight, grad_bias}; +} + +std::tuple slow_conv2d_backward_cuda( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + std::array output_mask) { + Tensor grad_input; + Tensor grad_weight; + Tensor grad_bias; + + if (output_mask[0]) { + grad_input = at::empty({0}, grad_output.options()); + } + + if (output_mask[1]) { + grad_weight = at::empty({0}, grad_output.options()); + } + + if (output_mask[2]) { + grad_bias = at::empty({0}, grad_output.options()); + } + + return native::slow_conv2d_backward_out_cuda( + grad_output, + self, + weight, + kernel_size, + stride, + padding, + grad_input, + grad_weight, + grad_bias); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Copy.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Copy.cu new file mode 100644 index 0000000000000000000000000000000000000000..7a13733976c32ff0bb90c95e4e0efdc8661f94e1 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Copy.cu @@ -0,0 +1,501 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#endif + +#include +#include +#include + +#if defined(CUDA_VERSION) && CUDA_VERSION >= 13000 +#include +#endif + +namespace at::native { + +namespace { + +// Initial pool size for CUDA events per device. +constexpr size_t kInitialEventPoolSize = 8; + +at::cuda::CUDAEventPool::Event getEventFromPool(const at::DeviceIndex device_idx) { + // Pre-populate the pool with events to avoid stalls in creating events + static auto* event_pool = new at::cuda::CUDAEventPool(kInitialEventPoolSize); + return event_pool->get(device_idx); +} + +} // namespace + +void neg_kernel_cuda(TensorIteratorBase &iter); +void conj_kernel_cuda(TensorIteratorBase &iter); + +void float16_copy_kernel_cuda(TensorIteratorBase &iter) { + gpu_kernel_nocast(iter, [] GPU_LAMBDA(float value) { + return static_cast(value); + }); +} + +void bfloat16_copy_kernel_cuda(TensorIteratorBase &iter) { + gpu_kernel_nocast(iter, [] GPU_LAMBDA(float value) { + return static_cast(value); + }); +} + +#ifdef USE_ROCM +void bfloat16tofloat32_copy_kernel_cuda(TensorIteratorBase &iter) { + gpu_kernel_nocast(iter, [] GPU_LAMBDA(at::BFloat16 value) { + return static_cast(value); + }); +} +void float16tofloat32_copy_kernel_cuda(TensorIteratorBase &iter) { + gpu_kernel_nocast(iter, [] GPU_LAMBDA(at::Half value) { + return static_cast(value); + }); +} +#endif + +template +struct ConvertToFloat8E4M3fnOp { + __device__ __forceinline__ Float8_e4m3fn operator()(SrcT value) const { +#if defined(CUDA_VERSION) && CUDA_VERSION >= 13000 && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 890 + __nv_fp8_storage_t x; + if constexpr (std::is_same_v) { + x = __nv_cvt_float_to_fp8(value, __NV_SATFINITE, __NV_E4M3); + } else if constexpr (std::is_same_v) { + x = __nv_cvt_halfraw_to_fp8(static_cast<__half>(value), __NV_SATFINITE, __NV_E4M3); + } else if constexpr (std::is_same_v) { + x = __nv_cvt_bfloat16raw_to_fp8(static_cast<__nv_bfloat16>(value), __NV_SATFINITE, __NV_E4M3); + } else { + x = __nv_cvt_float_to_fp8(static_cast(value), __NV_SATFINITE, __NV_E4M3); + } + return Float8_e4m3fn(x, Float8_e4m3fn::from_bits()); +#else + return Float8_e4m3fn(value); +#endif + } +}; + +// e5m2 intrinsics are correct but slower; only used for float on Blackwell +// to work around the ptxas subnormal codegen bug. +struct ConvertFloatToFloat8E5M2Op { + __device__ __forceinline__ Float8_e5m2 operator()(float value) const { +#if defined(CUDA_VERSION) && CUDA_VERSION >= 13020 && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 1000 + auto x = __nv_cvt_float_to_fp8(value, __NV_NOSAT, __NV_E5M2); + return Float8_e5m2(x, Float8_e5m2::from_bits()); +#else + return Float8_e5m2(value); +#endif + } +}; + +void float8_copy_kernel_cuda(TensorIteratorBase &iter) { + ScalarType dtype = iter.dtype(0); + ScalarType other_dtype = iter.dtype(1); + if (dtype == kFloat8_e4m3fn) { + switch (other_dtype) { + case kFloat: + gpu_kernel_nocast(iter, ConvertToFloat8E4M3fnOp{}); + break; + case kHalf: + gpu_kernel_nocast(iter, ConvertToFloat8E4M3fnOp{}); + break; + case kBFloat16: + gpu_kernel_nocast(iter, ConvertToFloat8E4M3fnOp{}); + break; + default: + gpu_kernel(iter, [] GPU_LAMBDA(Float8_e4m3fn x) { return x; }); + break; + } + } else if (dtype == kFloat8_e5m2) { + switch (other_dtype) { + case kFloat: + gpu_kernel_nocast(iter, ConvertFloatToFloat8E5M2Op{}); + break; + case kHalf: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(Half value) { + return Float8_e5m2(value); + }); + break; + case kBFloat16: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(BFloat16 value) { + return Float8_e5m2(value); + }); + break; + default: + gpu_kernel(iter, [] GPU_LAMBDA(Float8_e5m2 x) { return x; }); + break; + } + } else if (dtype == kFloat8_e4m3fnuz) { + switch (other_dtype) { + case kFloat: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(float value) { + return Float8_e4m3fnuz(value); + }); + break; + case kHalf: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(Half value) { + return Float8_e4m3fnuz(value); + }); + break; + case kBFloat16: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(BFloat16 value) { + return Float8_e4m3fnuz(value); + }); + break; + default: + gpu_kernel(iter, [] GPU_LAMBDA(Float8_e4m3fnuz x) { return x; }); + break; + } + } else if (dtype == kFloat8_e5m2fnuz) { + switch (other_dtype) { + case kFloat: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(float value) { + return Float8_e5m2fnuz(value); + }); + break; + case kHalf: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(Half value) { + return Float8_e5m2fnuz(value); + }); + break; + case kBFloat16: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(BFloat16 value) { + return Float8_e5m2fnuz(value); + }); + break; + default: + gpu_kernel(iter, [] GPU_LAMBDA(Float8_e5m2fnuz x) { return x; }); + break; + } + } else if (dtype == kFloat8_e8m0fnu) { + // TODO(#146647): clean this up, too much copy-pasta + switch (other_dtype) { + case kFloat: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(float value) { + return Float8_e8m0fnu(value); + }); + break; + case kHalf: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(Half value) { + return Float8_e8m0fnu(value); + }); + break; + case kBFloat16: + gpu_kernel_nocast(iter, [] GPU_LAMBDA(BFloat16 value) { + return Float8_e8m0fnu(value); + }); + break; + default: + gpu_kernel(iter, [] GPU_LAMBDA(Float8_e8m0fnu x) { return x; }); + break; + } + } else { + TORCH_CHECK(false, "This supposed to be called only for Float8 types"); + } +} + +// TODO: We probably can use the opaque type trick to avoid creating duplicate +// kernels for equivalent bit lengths +void direct_copy_kernel_cuda(TensorIteratorBase &iter) { + ScalarType dtype = iter.dtype(0); + if (isQIntType(dtype)) { + AT_DISPATCH_QINT_TYPES(dtype, "copy_", [&] { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t x) { return x; }); + }); + } else if (isFloat8Type(dtype)) { + float8_copy_kernel_cuda(iter); + } else if (iter.dtype(1) == kFloat && (dtype == kBFloat16 || dtype == kHalf)) { + if (dtype == kBFloat16) { + bfloat16_copy_kernel_cuda(iter); + } else { + float16_copy_kernel_cuda(iter); + } + } +#ifdef USE_ROCM + else if ((iter.dtype(1) == kBFloat16 || iter.dtype(1) == kHalf) && dtype == kFloat) { + if (iter.dtype(1) == kBFloat16) { + bfloat16tofloat32_copy_kernel_cuda(iter); + } else { + float16tofloat32_copy_kernel_cuda(iter); + } + } +#endif + else if (isBitsType(dtype)) { + TORCH_CHECK(dtype == iter.dtype(1), "copy_() does not support casting " + "bits types to different bits types. Source dtype is ", iter.dtype(1), "target dtype is ", dtype); + AT_DISPATCH_BIT_TYPES(dtype, "copy_", [&] { + gpu_kernel_nocast(iter, [] GPU_LAMBDA(scalar_t x) { return x; }); + }); + } else if (dtype == ScalarType::Float4_e2m1fn_x2) { + TORCH_CHECK(dtype == iter.dtype(1), "copy_() does not support casting " + "Float4_e2m1fn_x2 to different types. Source dtype is ", iter.dtype(1), "target dtype is ", dtype); + gpu_kernel_nocast(iter, [] GPU_LAMBDA(Float4_e2m1fn_x2 x) { return x; }); + } else { + AT_DISPATCH_V2( + dtype, "copy_", AT_WRAP([&] { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t x) { return x; }); + }), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), kHalf, kBool, kBFloat16, kComplexHalf, kBComplex32, AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)); + } +} + +void neg_conj_kernel_cuda(TensorIteratorBase &iter) { + AT_DISPATCH_COMPLEX_TYPES(iter.common_dtype(), "neg_conj_cuda", [&] { + gpu_kernel(iter, [] GPU_LAMBDA(scalar_t x) { return -std::conj(x); }); + }); +} + +using namespace at::cuda; + +// device-to-device copy, does type conversion +void copy_device_to_device(TensorIterator& iter, + bool non_blocking, + bool p2p_enabled) { + int64_t numel = iter.numel(); + + // We can memcpy the memory if both tensors have the same type AND both + // tensors are contiguous after dimension coalescing and reordering. + bool same_type = iter.dtype(0) == iter.dtype(1); + bool same_conj = iter.tensor(0).is_conj() == iter.tensor(1).is_conj(); + bool same_neg = iter.tensor(0).is_neg() == iter.tensor(1).is_neg(); + bool memcpy_eligible = same_type && same_conj && same_neg && iter.is_contiguous(); + + Device dst_device = iter.device(0); + Device src_device = iter.device(1); + + CUDAGuard device_guard(src_device); + + // We always perform the copy on the source device, using the current stream + // on the source device, and we fully synchronize on both src and dst's + // current streams for completion of the copy. We have to explicitly do this + // for non-contig copies. This mimics the behavior of cross-device + // cudaMemcpyAsync on the default stream. + CUDAStream copy_stream = getCurrentCUDAStream(src_device.index()); + if (src_device != dst_device) { + // This is a cross-device copy on the src current stream and dst current + // stream. We perform a two-way barrier between both devices' streams + // before the copy. This ensures that any write-after-write and + // write-after-read dependencies on the destination side are handled, so + // that no one is operating on the dst memory when we perform the copy. + // src waits on dst barrier (src already waits on src) + + // Use event pool for better performance instead of creating new events + auto dst_ready = getEventFromPool(dst_device.index()); + device_guard.set_device(dst_device); + dst_ready->record(getCurrentCUDAStream(dst_device.index())); + + device_guard.set_device(src_device); + dst_ready->block(copy_stream); + } + + if (memcpy_eligible) { + void *dst = iter.data_ptr(0); + void *src = iter.data_ptr(1); + size_t size = numel * iter.element_size(0); + if (src != dst || src_device != dst_device) { + // Due to bizarre cuda driver intricacies, copies of + // cudaMallocAsynced memory between devices that aren't + // peer-to-peer-capable need "cudaMemcpyPeerAsync". + // So we let the allocator implement the correct call + // (either cudaMemcpyAsync or cudaMemcpyPeerAsync) + AT_CUDA_CHECK(CUDACachingAllocator::memcpyAsync( + dst, dst_device.index(), + src, src_device.index(), + size, copy_stream, p2p_enabled)); + } + } else { + if (same_neg) { + if (!same_conj) { + conj_kernel_cuda(iter); + } else { + direct_copy_kernel_cuda(iter); + } + } else { + if (!same_conj) { + neg_conj_kernel_cuda(iter); + } else { + neg_kernel_cuda(iter); + } + } + } + + if (src_device != dst_device) { + // dst waits on src barrier (dst already waits on dst). We cannot + // operate on dst's copy until the copy is complete. + + // Still on src_device, record stream event + auto src_ready = getEventFromPool(src_device.index()); + src_ready->record(copy_stream); + + device_guard.set_device(dst_device); + src_ready->block(getCurrentCUDAStream(dst_device.index())); + } + + AT_CUDA_CHECK(cudaGetLastError()); +} + +static bool copy_requires_temporaries(TensorIterator& iter, bool p2p_enabled) { + Device dst_device = iter.device(0); + Device src_device = iter.device(1); + + if (dst_device == src_device) { + // We never require temporaries for copies on the same GPU. + TORCH_INTERNAL_ASSERT(dst_device.is_cuda() && src_device.is_cuda()); + return false; + } + + bool same_dtype = iter.dtype(0) == iter.dtype(1); + if (same_dtype && iter.is_contiguous()) { + // Contiguous same-dtype copies can always use cudaMemcpyAsync + return false; + } else if (dst_device.is_cuda() && src_device.is_cuda()) { + // Copies between GPUs can use the copy kernel if P2P is supported + return !p2p_enabled; + } else { + // The remaining cases require temporaries. For example, this includes + // non-contiguous copies between CPU and GPU. + return true; + } +} + +static bool maybe_enable_p2p_access(Device dst_device, Device src_device) { + if (dst_device.is_cpu() || src_device.is_cpu()) { + return false; + } + return at::cuda::get_p2p_access(src_device.index(), dst_device.index()); +} + +static void copy_kernel_cuda(TensorIterator& iter, bool non_blocking) { + TORCH_CHECK(iter.ntensors() == 2); + + Device dst_device = iter.device(0); + Device src_device = iter.device(1); + + // Enable p2p access between devices. (No-op if it involves the CPU) + bool p2p_enabled = maybe_enable_p2p_access(dst_device, src_device); + + if (copy_requires_temporaries(iter, p2p_enabled)) { + // NB: this involves recursive calls to copy. Be careful that those copies + // don't require temporaries or you will cause an infinite recursion! + auto& dst = iter.tensor(0); + Tensor dst_contig; + Tensor src_contig; + + // If non_blocking is true - type conversions are performed on the GPU + // For blocking transfers conversions are performed on CPU to avoid allocating + // extra GPU memory + // for GPU-GPU transfers conversions are performed on the source device + auto conversion_device = non_blocking ? kCUDA : kCPU; + if (iter.device_type(1) == conversion_device) { + dst_contig = dst.is_contiguous() ? dst : at::empty_like(dst, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + src_contig = iter.tensor(1).to(iter.dtype(0)).expand_as(dst).contiguous(); + } else { + bool same_type = iter.dtype(0) == iter.dtype(1); + dst_contig = (dst.is_contiguous() && same_type) ? dst : at::empty_like(dst, iter.dtype(1), LEGACY_CONTIGUOUS_MEMORY_FORMAT); + src_contig = iter.tensor(1).expand_as(dst).contiguous(); + } + + // propagate the correct conjugate bit + dst_contig._set_conj(dst.is_conj()); + src_contig._set_conj(iter.tensor(1).is_conj()); + + dst_contig._set_neg(dst.is_neg()); + src_contig._set_neg(iter.tensor(1).is_neg()); + + // perform a same-dtype copy on contiguous tensors + TORCH_INTERNAL_ASSERT(dst_contig.sizes().equals(src_contig.sizes())); + TORCH_INTERNAL_ASSERT(dst_contig.scalar_type() == src_contig.scalar_type()); + dst_contig.copy_(src_contig, non_blocking); + + // if necessary, copy back into dst + if (!dst_contig.is_same(dst)) { + TORCH_INTERNAL_ASSERT(dst_contig.device() == dst.device()); + dst.copy_(dst_contig, non_blocking); + } + return; + } + + // Copy on GPU (or between GPUs) + if (dst_device.is_cuda() && src_device.is_cuda()) { + copy_device_to_device(iter, non_blocking, p2p_enabled); + return; + } + + // Copy between CPU and GPU + cuda::OptionalCUDAGuard device_guard; + cudaMemcpyKind kind; + const Tensor* host_tensor = nullptr; + if (dst_device.is_cuda() && src_device.is_cpu()) { + device_guard.set_device(dst_device); + kind = cudaMemcpyHostToDevice; + host_tensor = &iter.tensor(1); + } else if (dst_device.is_cpu() && src_device.is_cuda()) { + device_guard.set_device(src_device); + kind = cudaMemcpyDeviceToHost; + host_tensor = &iter.tensor(0); + } else { + TORCH_INTERNAL_ASSERT(false, "unsupported devices in GPU copy_()"); + } + + // Check for unpinned CPU memory during CUDA graph capture + if (at::cuda::currentStreamCaptureStatus() != at::cuda::CaptureStatus::None) { + TORCH_CHECK( + host_tensor->is_pinned(), + "Cannot copy between CPU and CUDA tensors during CUDA graph capture ", + "unless the CPU tensor is pinned. Please use tensor.pin_memory() or ", + "allocate the tensor with pin_memory=True."); + } + + void* dst = iter.data_ptr(0); + void* src = iter.data_ptr(1); + int64_t nbytes = iter.numel() * iter.element_size(0); + CUDAStream stream = getCurrentCUDAStream(); + + if (non_blocking) { + AT_CUDA_CHECK(cudaMemcpyAsync(dst, src, nbytes, kind, stream)); + // we use both the storage context and the tensor data pointer as the key + // for the caching host allocator. This allows us to better attribute the + // events to the original tensor allocation correctly. The cases we seek to + // handle are: + + // 1: a user can pass a pinned memory tensor with an alternative + // context, for example if allocating memory directly from the pinned memory + // allocator and constructing a tensor with torch::from_blob. + + // 2: a user can pass a tensor with a different base pointer to the original + // allocation (via slicing). + const auto& dst_tensor = iter.tensor(0); + const auto& src_tensor = iter.tensor(1); + const auto& host_tensor = (dst_device == kCPU ? dst_tensor : src_tensor); + auto* ptr = (dst_device == kCPU ? dst : src); + auto* ctx = host_tensor.storage().data_ptr().get_context(); + // TODO: warn on the return value. + at::getHostAllocator(at::kCUDA)->record_event(ptr, ctx, stream.unwrap()); + } else { + at::cuda::memcpy_and_sync(dst, src, nbytes, kind, stream); + } + + if (iter.tensor(0).is_conj() != iter.tensor(1).is_conj()) { + iter.tensor(0).conj_physical_(); + } + if (iter.tensor(0).is_neg() != iter.tensor(1).is_neg()) { + iter.tensor(0).neg_(); + } +} + +REGISTER_DISPATCH(copy_stub, ©_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Copy.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Copy.h new file mode 100644 index 0000000000000000000000000000000000000000..285b888db77863d664caf710095d9dca70eb50a6 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Copy.h @@ -0,0 +1,11 @@ +#pragma once + +namespace at { +struct TensorIteratorBase; + +namespace native { + +void direct_copy_kernel_cuda(TensorIteratorBase& iter); + +} +} // namespace at diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CopysignKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CopysignKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..6341f747f644739ad9b13804b7b4eb9190c9ebcb --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CopysignKernel.cu @@ -0,0 +1,60 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include + +#if defined(__CUDACC__) +#include +#include +#include +#elif defined(__HIPCC__) +#include +#include +#include +#endif + +// NOTE: CUDA on Windows requires that the enclosing function +// of a __device__ lambda not have internal linkage. + +namespace at::native { + +namespace { + +C10_HOST_DEVICE inline c10::Half copysign_half(c10::Half a, c10::Half b) { + return c10::Half( + static_cast((a.x & 0x7fff) | (b.x & 0x8000)), + c10::Half::from_bits()); +} + +C10_HOST_DEVICE inline c10::BFloat16 copysign_bf16(c10::BFloat16 a, c10::BFloat16 b) { + return c10::BFloat16( + static_cast((a.x & 0x7fff) | (b.x & 0x8000)), + c10::BFloat16::from_bits()); +} + +} // namespace + +void copysign_kernel_cuda(TensorIteratorBase& iter) { + auto dtype = iter.common_dtype(); + if (dtype == kHalf) { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(c10::Half a, c10::Half b) -> c10::Half { + return copysign_half(a, b); + }); + } else if (dtype == kBFloat16) { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(c10::BFloat16 a, c10::BFloat16 b) -> c10::BFloat16 { + return copysign_bf16(a, b); + }); + } else { + AT_DISPATCH_FLOATING_TYPES(dtype, "copysign_cuda", [&]() { + gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { + return c10::cuda::compat::copysign(a, b); + }); + }); + } +} + +REGISTER_DISPATCH(copysign_stub, ©sign_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CrossKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CrossKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..6d8ee1da9e51bf35b781166613ca199022e02458 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CrossKernel.cu @@ -0,0 +1,92 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include + +namespace at::native { + +template +__global__ void cross_kernel( + int numel, T* out, const T* x1, const T* x2, OffsetCalc offset_calculator, + StrideType ostride, StrideType x1stride, StrideType x2stride) { + CUDA_KERNEL_LOOP(i, numel) { + const auto offsets = offset_calculator.get(i); + auto* out_row = out + offsets[0]; + const auto* x1_row = x1 + offsets[1]; + const auto* x2_row = x2 + offsets[2]; + + const T val0 = (x1_row[1 * x1stride] * x2_row[2 * x2stride] - + x1_row[2 * x1stride] * x2_row[1 * x2stride]); + + const T val1 = (x1_row[2 * x1stride] * x2_row[0 * x2stride] - + x1_row[0 * x1stride] * x2_row[2 * x2stride]); + + const T val2 = (x1_row[0 * x1stride] * x2_row[1 * x2stride] - + x1_row[1 * x1stride] * x2_row[0 * x2stride]); + + + out_row[0 * ostride] = val0; + out_row[1 * ostride] = val1; + out_row[2 * ostride] = val2; + } +} + +void launch_cross_kernel(const TensorIteratorBase& iter, int64_t ostride, + int64_t x1stride, int64_t x2stride) { + const auto N = iter.numel(); + auto offset_calculator = make_element_offset_calculator<3>(iter); + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(N > 0 && N <= std::numeric_limits::max()); + int64_t grid = (N + num_threads() - 1) / num_threads(); + auto stream = at::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2(kHalf, kBFloat16, iter.common_dtype(), "cross_cuda", [&] { + auto out = static_cast(iter.data_ptr(0)); + auto x1 = static_cast(iter.data_ptr(1)); + auto x2 = static_cast(iter.data_ptr(2)); + constexpr int64_t int_max = std::numeric_limits::max(); + if (ostride * 2 > int_max || x1stride * 2 > int_max || x2stride * 2 > int_max) { + cross_kernel<<>>( + N, out, x1, x2, offset_calculator, ostride, x1stride, x2stride); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + cross_kernel<<>>( + N, out, x1, x2, offset_calculator, + static_cast(ostride), + static_cast(x1stride), + static_cast(x2stride)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); +} + +void cross_impl(const Tensor& result, const Tensor& x1, const Tensor& x2, int64_t dim) { + const int64_t ostride = result.stride(dim); + const int64_t x1stride = x1.stride(dim); + const int64_t x2stride = x2.stride(dim); + + auto iter = TensorIteratorConfig() + .add_output(result) + .add_const_input(x1) + .add_const_input(x2) + .resize_outputs(false) + .declare_static_shape(result.sizes(), /*squash_dims=*/dim) + .build(); + + if (iter.numel() == 0) { + return; + } + + if (iter.can_use_32bit_indexing()) { + launch_cross_kernel(iter, ostride, x1stride, x2stride); + } else { + for (auto&& sub_iter: iter.with_32bit_indexing()) { + launch_cross_kernel(sub_iter, ostride, x1stride, x2stride); + } + } +} + +REGISTER_DISPATCH(cross_stub, &cross_impl) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CuFFTPlanCache.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CuFFTPlanCache.h new file mode 100644 index 0000000000000000000000000000000000000000..e181a740c47cfe9ff074ff566964a59832671085 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CuFFTPlanCache.h @@ -0,0 +1,494 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace at::native::detail { + +// Enum representing the FFT type +enum class CuFFTTransformType : int8_t { + C2C, // Complex-to-complex + R2C, // Real-to-complex + C2R, // Complex-to-real +}; + +// This struct is used to let us easily compute hashes of the +// parameters. +// It will be the **key** to the plan cache. +struct CuFFTParams +{ + int64_t signal_ndim_; // between 1 and max_rank, i.e., 1 <= signal_ndim <= 3 + // These include additional batch dimension as well. + int64_t sizes_[max_rank + 1]; + int64_t input_strides_[max_rank + 1]; + int64_t output_strides_[max_rank + 1]; + CuFFTTransformType fft_type_; + ScalarType value_type_; + + CuFFTParams() = default; + + CuFFTParams(IntArrayRef in_strides, IntArrayRef out_strides, + IntArrayRef signal_sizes, CuFFTTransformType fft_type, ScalarType value_type) { + // Padding bits must be zeroed for hashing + memset(this, 0, sizeof(*this)); + signal_ndim_ = signal_sizes.size() - 1; + fft_type_ = fft_type; + value_type_ = value_type; + + TORCH_INTERNAL_ASSERT(in_strides.size() == signal_sizes.size()); + TORCH_INTERNAL_ASSERT(out_strides.size() == signal_sizes.size()); + TORCH_INTERNAL_ASSERT(1 <= signal_ndim_ && signal_ndim_ <= max_rank); + + std::copy(signal_sizes.cbegin(), signal_sizes.cend(), sizes_); + std::copy(in_strides.cbegin(), in_strides.cend(), input_strides_); + std::copy(out_strides.cbegin(), out_strides.cend(), output_strides_); + } +}; + +static_assert(std::is_trivial_v ); + +// Returns true if the transform type has complex input +inline bool cufft_complex_input(CuFFTTransformType type) { + switch (type) { + case CuFFTTransformType::C2C: + case CuFFTTransformType::C2R: + return true; + + case CuFFTTransformType::R2C: + return false; + } + TORCH_INTERNAL_ASSERT(false); +} + +// Returns true if the transform type has complex output +inline bool cufft_complex_output(CuFFTTransformType type) { + switch (type) { + case CuFFTTransformType::C2C: + case CuFFTTransformType::R2C: + return true; + + case CuFFTTransformType::C2R: + return false; + } + TORCH_INTERNAL_ASSERT(false); +} + +// Create transform type enum from bools representing if input and output are complex +inline CuFFTTransformType GetCuFFTTransformType(bool complex_input, bool complex_output) { + if (complex_input && complex_output) { + return CuFFTTransformType::C2C; + } else if (complex_input && !complex_output) { + return CuFFTTransformType::C2R; + } else if (!complex_input && complex_output) { + return CuFFTTransformType::R2C; + } + TORCH_INTERNAL_ASSERT(false, "Real to real FFTs are not supported"); +} + + +class CuFFTHandle { + ::cufftHandle handle_; +public: + + CuFFTHandle() { + CUFFT_CHECK(cufftCreate(&handle_)); + } + + ::cufftHandle & get() { return handle_; } + const ::cufftHandle & get() const { return handle_; } + + ~CuFFTHandle() { +// Not using fftDestroy() for rocFFT to work around double freeing of handles +#if !defined(USE_ROCM) + cufftDestroy(handle_); +#endif + } +}; + +__forceinline__ +static bool is_pow_of_two(int64_t x) { + return (x & (x - 1)) == 0; +} + +using cufft_size_type = long long int; + +using CuFFTDimVector = c10::SmallVector; + +// Struct representing a tensor in CuFFT's data layout for planning transforms +// See NOTE [ cuFFT Embedded Strides ]. +struct CuFFTDataLayout { + CuFFTDimVector embed; + cufft_size_type stride, dist; + bool must_clone, simple; +}; + +// Returns a cufft embedding for a contiguous signal of the given size. +// e.g. if the input is cloned, this will be the resulting data layout +// See NOTE [ cuFFT Embedded Strides ]. +inline CuFFTDataLayout cufft_simple_embed(IntArrayRef sizes, bool onesided) { + CuFFTDataLayout layout; + layout.simple = true; + layout.must_clone = false; + layout.embed.assign(sizes.cbegin() + 1, sizes.cend()); + if (onesided) { + layout.embed.back() = sizes.back() / 2 + 1; + } + layout.stride = 1; + layout.dist = 1; + for (const auto& len : layout.embed) { + layout.dist *= len; + } + return layout; +} + +// Convert strides to a CuFFT embedded representation. +// If strides cannot be embedded, returns a simple layout and sets must_clone flag +// See NOTE [ cuFFT Embedded Strides ]. +inline CuFFTDataLayout as_cufft_embed(IntArrayRef strides, IntArrayRef sizes, bool onesided) { + const auto signal_ndim = strides.size() - 1; + CuFFTDataLayout layout; + auto last_stride = strides[signal_ndim]; + layout.must_clone = (last_stride <= 0); + + const auto last_dim_size = onesided ? + sizes[signal_ndim] / 2 + 1 : sizes[signal_ndim]; + const auto signal_numel = c10::multiply_integers(sizes.slice(1, sizes.size() - 2)) * last_dim_size; + + // Zero stides are not allowed, even if the batch size is one. + // If that happens just set a dummy case + if (sizes[0] == 1) { + layout.dist = signal_numel; + } else if (strides[0] == 0) { + layout.must_clone = true; + } else { + layout.dist = strides[0]; + } + + // Calculate the embedding shape, or set must_clone if the strides cannot be embedded + layout.embed.resize(signal_ndim); + for (auto i = signal_ndim - 1; !layout.must_clone && i > 0; i--) { + auto stride = strides[i]; + if (sizes[i] == 1) { + layout.embed[i] = 1; + } else if (stride > 0 && stride % last_stride == 0) { + layout.embed[i] = stride / last_stride; + last_stride = stride; + } else { + layout.must_clone = true; + } + } + + if (layout.must_clone) { + // If the input needs to be cloned, assume it will be contiguous + layout = cufft_simple_embed(sizes, onesided); + layout.must_clone = true; + } else { + layout.embed[0] = sizes[1]; + layout.stride = strides[signal_ndim]; + // Determine if layout represents a simple embedding (contiguous data) + layout.simple = [&] { + for (const auto i : c10::irange(1, signal_ndim - 1)) { + if (layout.embed[i] != sizes[i + 1]) { + return false; + } + } + + return (layout.stride == 1 && layout.dist == signal_numel && + layout.embed.back() == last_dim_size); + }(); + } + return layout; +} + +// This class contains all the information needed to execute a cuFFT plan: +// 1. the plan +// 2. whether to clone input before executing the plan +// 3. the workspace size needed +// +// This class will be the **value** in the plan cache. +// It **owns** the raw plan via a unique_ptr. +class CuFFTConfig { +public: + + // Only move semantics is enough for this class. Although we already use + // unique_ptr for the plan, still remove copy constructor and assignment op so + // we don't accidentally copy and take perf hit. + CuFFTConfig(const CuFFTConfig&) = delete; + CuFFTConfig& operator=(CuFFTConfig const&) = delete; + + explicit CuFFTConfig(const CuFFTParams& params): + CuFFTConfig( + IntArrayRef(params.input_strides_, params.signal_ndim_ + 1), + IntArrayRef(params.output_strides_, params.signal_ndim_ + 1), + IntArrayRef(params.sizes_, params.signal_ndim_ + 1), + params.fft_type_, + params.value_type_) {} + + // For complex types, strides are in units of 2 * element_size(dtype) + // sizes are for the full signal, including batch size and always two-sided + CuFFTConfig(IntArrayRef in_strides, IntArrayRef out_strides, + IntArrayRef sizes, CuFFTTransformType fft_type, ScalarType dtype): + fft_type_(fft_type), value_type_(dtype) { + + // signal sizes (excluding batch dim) + CuFFTDimVector signal_sizes(sizes.begin() + 1, sizes.end()); + + // input batch size + const int64_t batch = sizes[0]; + const int64_t signal_ndim = sizes.size() - 1; + + // Since cuFFT has limited non-unit stride support and various constraints, we + // use a flag to keep track throughout this function to see if we need to + // input = input.clone(); + +#if defined(USE_ROCM) + // clone input to avoid issues with hipfft clobering the input and failing tests + clone_input = true; +#else + clone_input = false; +#endif + + // For half, base strides on the real part of real-to-complex and + // complex-to-real transforms are not supported. Since our output is always + // contiguous, only need to check real-to-complex case. + if (dtype == ScalarType::Half) { + // cuFFT on half requires compute capability of at least SM_53 + auto dev_prop = at::cuda::getCurrentDeviceProperties(); + TORCH_CHECK(dev_prop->major >= 5 && !(dev_prop->major == 5 && dev_prop->minor < 3), + "cuFFT doesn't support signals of half type with compute " + "capability less than SM_53, but the device containing input half " + "tensor only has SM_", dev_prop->major, dev_prop->minor); + for (const auto i : c10::irange(signal_ndim)) { + TORCH_CHECK(is_pow_of_two(sizes[i + 1]), + "cuFFT only supports dimensions whose sizes are powers of two when" + " computing in half precision, but got a signal size of", + sizes.slice(1)); + } + clone_input |= in_strides.back() != 1; + } + + CuFFTDataLayout in_layout; + if (clone_input) { + in_layout = cufft_simple_embed(sizes, fft_type == CuFFTTransformType::C2R); + } else { + in_layout = as_cufft_embed(in_strides, sizes, fft_type == CuFFTTransformType::C2R); + } + auto out_layout = as_cufft_embed(out_strides, sizes, fft_type == CuFFTTransformType::R2C); + TORCH_INTERNAL_ASSERT(!out_layout.must_clone, "Out strides cannot be represented as CuFFT embedding"); + clone_input |= in_layout.must_clone; + + // Check if we can take advantage of simple data layout. + // + // See NOTE [ cuFFT Embedded Strides ] in native/cuda/SpectralOps.cu. + + const bool simple_layout = in_layout.simple && out_layout.simple; + cudaDataType itype, otype, exec_type; + const auto complex_input = cufft_complex_input(fft_type); + const auto complex_output = cufft_complex_output(fft_type); + if (dtype == ScalarType::Float) { + itype = complex_input ? CUDA_C_32F : CUDA_R_32F; + otype = complex_output ? CUDA_C_32F : CUDA_R_32F; + exec_type = CUDA_C_32F; + } else if (dtype == ScalarType::Double) { + itype = complex_input ? CUDA_C_64F : CUDA_R_64F; + otype = complex_output ? CUDA_C_64F : CUDA_R_64F; + exec_type = CUDA_C_64F; + } else if (dtype == ScalarType::Half) { + itype = complex_input ? CUDA_C_16F : CUDA_R_16F; + otype = complex_output ? CUDA_C_16F : CUDA_R_16F; + exec_type = CUDA_C_16F; + } else { + TORCH_CHECK(false, "cuFFT doesn't support tensor of type: ", dtype); + } + + // disable auto allocation of workspace to use THC allocator + CUFFT_CHECK(cufftSetAutoAllocation(plan(), /* autoAllocate */ 0)); + + size_t ws_size_t; + + // make plan + if (simple_layout) { + // If with unit-stride, we tell cuFFT by setting inembed == onembed == NULL. + // In such case, cuFFT ignores istride, ostride, idist, and odist + // by assuming istride = ostride = 1. + // + // See NOTE [ cuFFT Embedded Strides ] in native/cuda/SpectralOps.cu. + CUFFT_CHECK(cufftXtMakePlanMany(plan(), signal_ndim, signal_sizes.data(), + /* inembed */ nullptr, /* base_istride */ 1, /* idist */ 1, itype, + /* onembed */ nullptr, /* base_ostride */ 1, /* odist */ 1, otype, + batch, &ws_size_t, exec_type)); + } else { + CUFFT_CHECK(cufftXtMakePlanMany(plan(), signal_ndim, signal_sizes.data(), + in_layout.embed.data(), in_layout.stride, in_layout.dist, itype, + out_layout.embed.data(), out_layout.stride, out_layout.dist, otype, + batch, &ws_size_t, exec_type)); + } + ws_size = static_cast(ws_size_t); + } + + const cufftHandle &plan() const { return plan_ptr.get(); } + + CuFFTTransformType transform_type() const { return fft_type_; } + ScalarType data_type() const { return value_type_; } + bool should_clone_input() const { return clone_input; } + int64_t workspace_size() const { return ws_size; } + +private: + CuFFTHandle plan_ptr; + bool clone_input; + int64_t ws_size; + CuFFTTransformType fft_type_; + ScalarType value_type_; +}; + +#if defined(USE_ROCM) + // Note that the max plan number for CUDA version < 10 has to be 1023 + // due to a bug that fails on the 1024th plan + constexpr int64_t CUFFT_MAX_PLAN_NUM = 1023; + constexpr int64_t CUFFT_DEFAULT_CACHE_SIZE = CUFFT_MAX_PLAN_NUM; +#else + constexpr int64_t CUFFT_MAX_PLAN_NUM = std::numeric_limits::max(); + // The default max cache size chosen for CUDA version > 10 is arbitrary. + // This number puts a limit on how big of a plan cache should we maintain by + // default. Users can always configure it via cufft_set_plan_cache_max_size. + constexpr int64_t CUFFT_DEFAULT_CACHE_SIZE = 4096; +#endif +static_assert(0 <= CUFFT_MAX_PLAN_NUM && CUFFT_MAX_PLAN_NUM <= std::numeric_limits::max(), + "CUFFT_MAX_PLAN_NUM not in size_t range"); +static_assert(CUFFT_DEFAULT_CACHE_SIZE >= 0 && CUFFT_DEFAULT_CACHE_SIZE <= CUFFT_MAX_PLAN_NUM, + "CUFFT_DEFAULT_CACHE_SIZE not in [0, CUFFT_MAX_PLAN_NUM] range"); + +// This cache assumes that the mapping from key to value never changes. +// This is **NOT** thread-safe. Please use a mutex when using it **AND** the +// value returned from try_emplace_value. +// The contract of using this cache is that try_emplace_value should only be +// used when the max_size is positive. +class CuFFTParamsLRUCache { +public: + using kv_t = typename std::pair; + using map_t = typename std::unordered_map, + typename std::list::iterator, + ParamsHash, + ParamsEqual>; + using map_kkv_iter_t = typename map_t::iterator; + + + CuFFTParamsLRUCache() : CuFFTParamsLRUCache(CUFFT_DEFAULT_CACHE_SIZE) {} + + CuFFTParamsLRUCache(int64_t max_size) { + _set_max_size(max_size); + } + + CuFFTParamsLRUCache(CuFFTParamsLRUCache&& other) noexcept : + _usage_list(std::move(other._usage_list)), + _cache_map(std::move(other._cache_map)), + _max_size(other._max_size) {} + + CuFFTParamsLRUCache& operator=(CuFFTParamsLRUCache&& other) noexcept { + _usage_list = std::move(other._usage_list); + _cache_map = std::move(other._cache_map); + _max_size = other._max_size; + return *this; + } + + // If key is in this cache, return the cached config. Otherwise, emplace the + // config in this cache and return it. + // Return const reference because CuFFTConfig shouldn't be tampered with once + // created. + const CuFFTConfig &lookup(CuFFTParams params) { + AT_ASSERT(_max_size > 0); + + map_kkv_iter_t map_it = _cache_map.find(params); + // Hit, put to list front + if (map_it != _cache_map.end()) { + _usage_list.splice(_usage_list.begin(), _usage_list, map_it->second); + return map_it->second->second; + } + + // Miss + // remove if needed + if (_usage_list.size() >= _max_size) { + auto last = _usage_list.end(); + last--; + _cache_map.erase(last->first); + _usage_list.pop_back(); + } + + // construct new plan at list front, then insert into _cache_map + _usage_list.emplace_front(std::piecewise_construct, + std::forward_as_tuple(params), + std::forward_as_tuple(params)); + auto kv_it = _usage_list.begin(); + _cache_map.emplace(std::piecewise_construct, + std::forward_as_tuple(kv_it->first), + std::forward_as_tuple(kv_it)); + return kv_it->second; + } + + void clear() { + _cache_map.clear(); + _usage_list.clear(); + } + + void resize(int64_t new_size) { + _set_max_size(new_size); + auto cur_size = _usage_list.size(); + if (cur_size > _max_size) { + auto delete_it = _usage_list.end(); + for (size_t i = 0; i < cur_size - _max_size; i++) { + delete_it--; + _cache_map.erase(delete_it->first); + } + _usage_list.erase(delete_it, _usage_list.end()); + } + } + + size_t size() const { return _cache_map.size(); } + + size_t max_size() const noexcept { return _max_size; } + + std::mutex mutex; + +private: + // Only sets size and does value check. Does not resize the data structures. + void _set_max_size(int64_t new_size) { + // We check that 0 <= new_size <= CUFFT_MAX_PLAN_NUM here. Since + // CUFFT_MAX_PLAN_NUM is of type size_t, we need to do non-negativity check + // first. + TORCH_CHECK(new_size >= 0, + "cuFFT plan cache size must be non-negative, but got ", new_size); + TORCH_CHECK(new_size <= CUFFT_MAX_PLAN_NUM, + "cuFFT plan cache size can not be larger than ", CUFFT_MAX_PLAN_NUM, ", but got ", new_size); + _max_size = static_cast(new_size); + } + + std::list _usage_list; + map_t _cache_map; + size_t _max_size; +}; + +// Since ATen is separated into CPU build and CUDA build, we need a way to call +// these functions only when CUDA is loaded. We use CUDA hooks for this purpose +// (at cuda/detail/CUDAHooks.cpp), and call the hooked functions from the actual +// native function counterparts (at native/SpectralOps.cpp), i.e., +// _cufft_get_plan_cache_max_size, _cufft_set_plan_cache_max_size +// _cufft_get_plan_cache_size, and _cufft_clear_plan_cache. +int64_t cufft_get_plan_cache_max_size_impl(DeviceIndex device_index); +void cufft_set_plan_cache_max_size_impl(DeviceIndex device_index, int64_t max_size); +int64_t cufft_get_plan_cache_size_impl(DeviceIndex device_index); +void cufft_clear_plan_cache_impl(DeviceIndex device_index); + +} // namespace at::native::detail diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CuFFTUtils.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CuFFTUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..b520b99538e88f2855a34718c143e01288edc70f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CuFFTUtils.h @@ -0,0 +1,75 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace at { namespace native { + +// This means that max dim is 3 + 2 = 5 with batch dimension and possible +// complex dimension +constexpr int max_rank = 3; + +static inline std::string _cudaGetErrorEnum(cufftResult error) +{ + switch (error) + { + case CUFFT_SUCCESS: + return "CUFFT_SUCCESS"; + case CUFFT_INVALID_PLAN: + return "CUFFT_INVALID_PLAN"; + case CUFFT_ALLOC_FAILED: + return "CUFFT_ALLOC_FAILED"; + case CUFFT_INVALID_TYPE: + return "CUFFT_INVALID_TYPE"; + case CUFFT_INVALID_VALUE: + return "CUFFT_INVALID_VALUE"; + case CUFFT_INTERNAL_ERROR: + return "CUFFT_INTERNAL_ERROR"; + case CUFFT_EXEC_FAILED: + return "CUFFT_EXEC_FAILED"; + case CUFFT_SETUP_FAILED: + return "CUFFT_SETUP_FAILED"; + case CUFFT_INVALID_SIZE: + return "CUFFT_INVALID_SIZE"; + case CUFFT_UNALIGNED_DATA: + return "CUFFT_UNALIGNED_DATA"; + case CUFFT_INVALID_DEVICE: + return "CUFFT_INVALID_DEVICE"; + case CUFFT_NO_WORKSPACE: + return "CUFFT_NO_WORKSPACE"; + case CUFFT_NOT_IMPLEMENTED: + return "CUFFT_NOT_IMPLEMENTED"; +#if CUDA_VERSION <= 12090 + case CUFFT_INCOMPLETE_PARAMETER_LIST: + return "CUFFT_INCOMPLETE_PARAMETER_LIST"; + case CUFFT_PARSE_ERROR: + return "CUFFT_PARSE_ERROR"; +#endif +#if !defined(USE_ROCM) && CUDA_VERSION <= 12090 + case CUFFT_LICENSE_ERROR: + return "CUFFT_LICENSE_ERROR"; +#endif + case CUFFT_NOT_SUPPORTED: + return "CUFFT_NOT_SUPPORTED"; + default: + std::ostringstream ss; + ss << "unknown error " << error; + return ss.str(); + } +} + +static inline void CUFFT_CHECK(cufftResult error) +{ + if (error != CUFFT_SUCCESS) { + std::ostringstream ss; + ss << "cuFFT error: " << _cudaGetErrorEnum(error); + TORCH_CHECK(false, ss.str()); + } +} + +}} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumminmaxKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumminmaxKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..1e5c1cbe47fff34f5a3e435e6213ad9fb6c60a62 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumminmaxKernel.cu @@ -0,0 +1,29 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include + +#include +#include + +#include +#include + +namespace at::native { + +void launch_cummax_cuda_kernel(const TensorBase& self, const TensorBase& values, const TensorBase& indices, int64_t dim) { + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::Half, at::ScalarType::BFloat16, + self.scalar_type(), "cummax_cuda", [&]() { + scalar_t init = self.is_floating_point() ? (-1*std::numeric_limits::infinity()) : std::numeric_limits::lowest(); + scan_dim_with_indices(self, values, indices, dim, init, std::greater_equal()); + }); +} + +void launch_cummin_cuda_kernel(const TensorBase& self, const TensorBase& values, const TensorBase& indices, int64_t dim) { + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Bool, at::ScalarType::Half, at::ScalarType::BFloat16, + self.scalar_type(), "cummin_cuda", [&]() { + scalar_t init = self.is_floating_point() ? std::numeric_limits::infinity() : std::numeric_limits::max(); + scan_dim_with_indices(self, values, indices, dim, init, std::less_equal()); + }); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumprodKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumprodKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..f8d3d0082e3c7a5e73a453bf2ba858b2a492d21b --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumprodKernel.cu @@ -0,0 +1,23 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include + +#include +#include + +namespace at::native { + +void launch_cumprod_cuda_kernel(const TensorBase& result, const TensorBase& self, int64_t dim) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( + ScalarType::Half, ScalarType::BFloat16, self.scalar_type(), "cumprod_cuda", [&]() { + scalar_t init = 1; + scan_dim( + self, + result, + dim, + init, + std::multiplies()); + }); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumsumKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumsumKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..aa218353950758b7ef95911b61dc0d15dc30a0ef --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/CumsumKernel.cu @@ -0,0 +1,25 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include + +#include +#include + +namespace at::native { + +void launch_cumsum_cuda_kernel(const TensorBase& result, const TensorBase& self, int64_t dim) { + AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND2( + ScalarType::Half, ScalarType::BFloat16, + self.scalar_type(), "cumsum_cuda", + [&]() { + scalar_t init = 0; + scan_dim( + self, + result, + dim, + init, + std::plus()); + }); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DepthwiseConv2d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DepthwiseConv2d.cu new file mode 100644 index 0000000000000000000000000000000000000000..619b7926cf9c4df0934f82184b491a2b376408a9 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DepthwiseConv2d.cu @@ -0,0 +1,765 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::native { +namespace { +using at::cuda::detail::CUDA_NUM_THREADS; +using at::cuda::detail::GET_BLOCKS; + +template class PtrTraits = DefaultPtrTraits> +PackedTensorAccessor32 dummy_packed_accessor32() { + std::array zeros{}; + return {nullptr, zeros.data(), zeros.data()}; +} + +template +__global__ void +#if !defined(USE_ROCM) +C10_LAUNCH_BOUNDS_1(at::cuda::detail::CUDA_NUM_THREADS) +#endif +conv_depthwise2d_forward_kernel_generic( + const PackedTensorAccessor32 input, + PackedTensorAccessor32 output, + const PackedTensorAccessor32 weight, + const PackedTensorAccessor32 bias, + bool biasEnabled, + index_t totalElements, + const int outputChannels, + const int depthwiseMultiplier, + const int inputWidth, const int inputHeight, + const int outputWidth, const int outputHeight, + const int kernelWidth, const int kernelHeight, + const int strideWidth, const int strideHeight, + const int padWidth, const int padHeight, + const int dilationWidth, const int dilationHeight) { + using acc_t = at::acc_type; + + CUDA_KERNEL_LOOP_TYPE(linearIndex, totalElements, index_t) { + //calculate n,c,h,w indices, replacing modulos by divide and multiply add, + //result is same as would be in the code below + //const int n = linearIndex / batchStride; //batchStride = outputChannels * outputHeight * outputWidth + //const int c = (linearIndex / channelStride) % outputChannels; //channelStride = outputHeight * outputWidth + //const int h = (linearIndex / outputWidth) % outputHeight; + //const int w = linearIndex % outputWidth; + + int indtmp1 = linearIndex/outputWidth; + const int w = linearIndex - indtmp1 * outputWidth; + int indtmp2 = indtmp1/outputHeight; + const int h = indtmp1 - indtmp2 * outputHeight; + indtmp1 = indtmp2; + indtmp2 = indtmp1/outputChannels; + const int c = indtmp1 - indtmp2 * outputChannels; + const int n = indtmp2; + + int inputChannel = c; + int inputChannels = outputChannels; + if (depthwiseMultiplier !=1) { + inputChannel /= depthwiseMultiplier; + inputChannels /= depthwiseMultiplier; + } + + int weightOffset = c * kernelHeight * kernelWidth; + + // By precisely computing the filtering boundaries, we avoid repeating several + // expensive edge condition checks for every fetched item. If the input element is + // resident in L1, then the extra branches and comparisons would have been + // comparable in terms of cycles with the actual data fetch. Therefore computing + // boundaries ahead of the loop showed significant performance boost. + + int kHmin = 0, kHmax = kernelHeight, kWmin = 0, kWmax = kernelWidth; + + // Top + int h_in_min = -padHeight + h * strideHeight; + if (h_in_min < 0) { + kHmin = -h_in_min / dilationHeight; + if ((-h_in_min) % dilationHeight > 0) { + kHmin++; + } + } + + // Bottom + int h_in_max = h_in_min + (kernelHeight - 1) * dilationHeight - inputHeight + 1; + if (h_in_max >= 0) { + kHmax = kernelHeight - h_in_max / dilationHeight; + if (h_in_max % dilationHeight > 0) { + kHmax--; + } + } + + // Left + int w_in_min = -padWidth + w * strideWidth; + if (w_in_min < 0) { + kWmin = -w_in_min / dilationWidth; + if ((-w_in_min) % dilationWidth > 0) { + kWmin++; + } + } + + // Right + int w_in_max = w_in_min + (kernelWidth - 1) * dilationWidth - inputWidth + 1; + if (w_in_max >= 0) { + kWmax = kernelWidth - w_in_max / dilationWidth; + if (w_in_max % dilationWidth > 0) { + kWmax--; + } + } + + acc_t value = biasEnabled ? static_cast(bias.data()[c]) : acc_t(0); + const index_t offset0 = (n * inputChannels + inputChannel) * inputHeight * inputWidth; + + for (int kH = kHmin; kH < kHmax; ++kH) { + const int h_in = -padHeight + h * strideHeight + kH * dilationHeight; + for (int kW = kWmin; kW < kWmax; ++kW) { + const int w_in = -padWidth + w * strideWidth + kW * dilationWidth; + const index_t offset = offset0 + h_in * inputWidth + w_in; + value += (static_cast(weight.data()[weightOffset + kH * kernelWidth + kW]) * + static_cast(input.data()[offset])); + } + } + output.data()[linearIndex] = static_cast(value); + } +} + +template +__global__ void +#if !defined(USE_ROCM) +C10_LAUNCH_BOUNDS_1(at::cuda::detail::CUDA_NUM_THREADS) +#endif +conv_depthwise2d_forward_kernel( + const PackedTensorAccessor32 input, + PackedTensorAccessor32 output, + const PackedTensorAccessor32 weight, + const PackedTensorAccessor32 bias, + bool biasEnabled, + index_t totalElements, + const int outputChannels, + const int depthwiseMultiplier, + const int inputWidth, const int inputHeight, + const int outputWidth, const int outputHeight, + const int kernelWidth, const int kernelHeight, + const int strideWidth, const int strideHeight, + const int padWidth, const int padHeight, + const int dilationWidth, const int dilationHeight) { + using acc_t = at::acc_type; + const int KW_LIMIT = (kSize != 0) ? kSize : kernelWidth; + const int KH_LIMIT = (kSize != 0) ? kSize : kernelHeight; + + CUDA_KERNEL_LOOP_TYPE(linearIndex, totalElements, index_t) { + //calculate n,c,h,w indices, replacing modulos by divide and multiply add, + //result is same as would be in the code below + //const int n = linearIndex / batchStride; //batchStride = outputChannels * outputHeight * outputWidth + //const int c = (linearIndex / channelStride) % outputChannels; //channelStride = outputHeight * outputWidth + //const int h = (linearIndex / outputWidth) % outputHeight; + //const int w = linearIndex % outputWidth; + + int indtmp1 = linearIndex/outputWidth; + const int w = linearIndex - indtmp1 * outputWidth; + int indtmp2 = indtmp1/outputHeight; + const int h = indtmp1 - indtmp2 * outputHeight; + indtmp1 = indtmp2; + indtmp2 = indtmp1/outputChannels; + const int c = indtmp1 - indtmp2 * outputChannels; + const int n = indtmp2; + + int inputChannel = c; + int inputChannels = outputChannels; + if (depthwiseMultiplier !=1) { + inputChannel /= depthwiseMultiplier; + inputChannels /= depthwiseMultiplier; + } + + int weightOffset = c * kernelHeight * kernelWidth; + + acc_t value = biasEnabled ? static_cast(bias.data()[c]) : acc_t(0); + const index_t offset0 = (n * inputChannels + inputChannel) * inputHeight * inputWidth; +#if !defined(USE_ROCM) +#pragma unroll +#endif + for (int kH = 0; kH < KH_LIMIT; ++kH) { +#if !defined(USE_ROCM) +#pragma unroll +#endif + for (int kW = 0; kW < KW_LIMIT; ++kW) { + const int h_in = -padHeight + h * strideHeight + kH * dilationHeight; + const int w_in = -padWidth + w * strideWidth + kW * dilationWidth; + + if ((h_in >= 0) && (h_in < inputHeight) && (w_in >= 0) && (w_in < inputWidth)) { + const index_t offset = offset0 + h_in * inputWidth + w_in; + value += (static_cast(weight.data()[weightOffset]) * + static_cast(input.data()[offset])); + } + ++weightOffset; + } + } + output.data()[linearIndex] = static_cast(value); + } +} + +template +#if !defined(USE_ROCM) +C10_LAUNCH_BOUNDS_1(at::cuda::detail::CUDA_NUM_THREADS) +#endif +__global__ void conv_depthwise2d_backward_kernel( + const PackedTensorAccessor32 grad_output, + PackedTensorAccessor32 grad_input, + const PackedTensorAccessor32 weight, + index_t totalElements, + const int inputChannels, + const int depthwiseMultiplier, + const int outputChannels, + const int inputWidth, const int inputHeight, + const int outputWidth, const int outputHeight, + const int kernelWidth, const int kernelHeight, + const int strideWidth, const int strideHeight, + const int padWidth, const int padHeight, + const int dilationWidth, const int dilationHeight) { + using acc_t = at::acc_type; + const int KW_LIMIT = (kSize != 0) ? kSize : kernelWidth; + const int KH_LIMIT = (kSize != 0) ? kSize : kernelHeight; + const int strideW = (stride != 0) ? stride : strideWidth; + const int strideH = (stride != 0) ? stride : strideHeight; + + CUDA_KERNEL_LOOP_TYPE(linearIndex, totalElements, index_t) { + int indtmp1 = linearIndex/inputWidth; + const int w = linearIndex - indtmp1 * inputWidth; + int indtmp2 = indtmp1/inputHeight; + const int h = indtmp1 - indtmp2 * inputHeight; + indtmp1 = indtmp2; + indtmp2 = indtmp1/inputChannels; + const int c = indtmp1 - indtmp2 * inputChannels; + const int n = indtmp2; + + acc_t value(0); + + for (int multiplier = 0; multiplier < depthwiseMultiplier; ++multiplier) { + int och = (c * depthwiseMultiplier) + multiplier; + int weightOffset = och * kernelHeight * kernelWidth; + for (int kh = 0; kh < KH_LIMIT; ++kh) { +#if !defined(USE_ROCM) +#pragma unroll +#endif + for (int kw = 0; kw < KW_LIMIT; ++kw) { + int h_out = h + padHeight - kh * dilationHeight; + int w_out = w + padWidth - kw * dilationWidth; + if ((h_out % strideH == 0) && (w_out % strideW == 0)) { + h_out = h_out / strideH; + w_out = w_out / strideW; + + if ((h_out >= 0) && (h_out < outputHeight) + && (w_out >= 0) && (w_out < outputWidth)) { + + const int offset = ((n * outputChannels + och) * outputHeight + h_out) + * outputWidth + w_out; + value += (static_cast(weight.data()[weightOffset]) * + static_cast(grad_output.data()[offset])); + } + } + ++weightOffset; + } + } + } + grad_input.data()[linearIndex] = static_cast(value); + } +} + +template +__global__ void conv_depthwise2d_grad_weight_kernel( + const PackedTensorAccessor32 grad_output, + const PackedTensorAccessor32 input, + PackedTensorAccessor32 grad_weight, + const int batchSize, + const int inputChannels, + const int kernelChannels, + const int depthwiseMultiplier, + const int inputWidth, const int inputHeight, + const int outputWidth, const int outputHeight, + const int kernelWidth, const int kernelHeight, + const int strideWidth, const int strideHeight, + const int padWidth, const int padHeight, + const int dilationWidth, const int dilationHeight) { + using acc_t = at::acc_type; + const int channelStride = kernelWidth * kernelHeight; + + // Each Block is responsible for accumulating over a permutation of + // (channels x kH x kW), use blockIdx to determine which one + int bidx = blockIdx.x; + int kW = bidx % kernelWidth; + int kH = (bidx / kernelWidth) % kernelHeight; + int ch = (bidx / channelStride); + + // Need to calculate which input channel is associated with this filter + // channel + int inputCh = ch / depthwiseMultiplier; + + acc_t grad(0); + + const int laneId = threadIdx.x % C10_WARP_SIZE; + const int batch = threadIdx.x / C10_WARP_SIZE; + const int nwarps = blockDim.x / C10_WARP_SIZE; + const int imageElements = outputWidth * outputHeight; + // Use warp per item. In the original kernel, a threadblock was used to sum over NHW. + // Here, we use a warp to sum values over HW dimension, and if batchSize is larger than the + // number of warps, a warp would loop over remaining batch items (e.g. if there are 8 warps, + // warp 0 would go over 0-8-16 etc image, warp 1 over 1-9-17 etc). Later in blockReduce, + // all the warps will be reduced anyway, thus the full reduction will be over NHW, like it + // should be. That allows to get rid of one modulo operation inside the loop (because n/batchIdx + // now does not have to be computed through modulo, you are just looping over it), and + // bring a nice speed-up. + for (int batchIdx = batch; batchIdx < batchSize; batchIdx += nwarps){ + // Warp-stride loop over elements in a batch item + for (index_t idx = laneId; idx < imageElements; idx += C10_WARP_SIZE) { + // Need to calculate the following: batch position, and offset into the grad_output + // in height, and width. We can intuit the corresponding position in the input from + // the other parameters we have + int go_w_offset = idx % outputWidth; + int go_h_offset = (idx / outputWidth); + + int i_w_offset = (go_w_offset * strideWidth) + (kW * dilationWidth) - padWidth; + int i_h_offset = (go_h_offset * strideHeight) + (kH * dilationHeight) - padHeight; + + if (i_w_offset >= 0 && i_h_offset >= 0 && i_w_offset < inputWidth && i_h_offset < inputHeight) { + int inputOffset = ((batchIdx * inputChannels + inputCh) * inputHeight + i_h_offset) * inputWidth + i_w_offset; + int outputOffset = ((batchIdx * kernelChannels + ch) * outputHeight ) * outputWidth + idx; + grad += (static_cast(input.data()[inputOffset]) * + static_cast(grad_output.data()[outputOffset])); + } + } + } + + // At this point each thread in the block has a local gradient, which we need to + // accumulate prior to writing the global value + extern __shared__ char smem[]; + acc_t* buf = reinterpret_cast(smem); + acc_t tval = cuda_utils::BlockReduceSum(grad, buf); + + // After reduction, first thread in the block has the gradient, so its responsible + // for writing it to grad_weight + if (threadIdx.x == 0) { + int weightOffset = kW + (kernelWidth * kH) + (kernelWidth * kernelHeight * ch); + grad_weight.data()[weightOffset] = static_cast(tval); + } +} + +void conv_depthwise2d_forward_out( + const Tensor &input, + const Tensor &output, + const Tensor &weight, + const Tensor &bias, + const int kW, const int kH, + const int dW, const int dH, + const int padW, const int padH, + const int dilationW, const int dilationH) { + // Only handle 4D Input Tensors for now + TORCH_CHECK(input.numel() > 0 && input.dim() == 4); + TORCH_CHECK(weight.numel() > 0 && weight.dim() == 4); + TORCH_CHECK(output.is_contiguous()); + + auto in_sizes = input.sizes(); + auto w_sizes = weight.sizes(); + + // We assume that the input and weight Tensors are shaped properly by + // the caller, so we verify that here to some extent + + // Weight Tensor is shape (output_channels, 1, kH, kW) + TORCH_CHECK(w_sizes[1] == 1); + + // Input Tensor is shape (N, input_channels, H, W) + // We verify that the # of output_channels is a multiple of input_channels + TORCH_CHECK(w_sizes[0] % in_sizes[1] == 0); + + // Bias has same # of channels as output + const bool has_bias = bias.defined(); + TORCH_CHECK(!has_bias || (bias.dim() <= 1 && bias.numel() == w_sizes[0])); + + // Following the behavior of other THCUNN functions, we shape the output + // Tensor ourselves + int64_t height = in_sizes[2]; + int64_t width = in_sizes[3]; + int64_t outputChannels = w_sizes[0]; + auto out_sizes = conv_output_size(in_sizes, weight.sizes(), {padH, padW}, {dH, dW}, + {dilationH, dilationW}); + const auto outputWidth = out_sizes[3]; + const auto outputHeight = out_sizes[2]; + + resize_output(output, out_sizes); + + int64_t inputChannels = in_sizes[1]; + int64_t depthwiseMultiplier = outputChannels / inputChannels; + + // One thread per output value + TORCH_CHECK(canUse32BitIndexMath(input) && canUse32BitIndexMath(output)); + int32_t n = output.numel(); + int blocks = GET_BLOCKS(n); + dim3 grid(blocks); + dim3 block(CUDA_NUM_THREADS); + const auto stream = c10::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "conv_depthwise2d_forward_cuda", [&] { + // Create PackedTensorAccessor + // Kernel currently relies upon all the Tensors to be contiguous, but we made + // them contiguous above + const auto input_a = input.packed_accessor32(); + const auto weight_a = weight.packed_accessor32(); + const auto output_a = output.packed_accessor32(); + const auto bias_a = has_bias ? + bias.packed_accessor32() : + dummy_packed_accessor32(); + if (kW == 5 && kH == 5) { + conv_depthwise2d_forward_kernel<5> <<>>( + input_a, output_a, weight_a, bias_a, has_bias, n, outputChannels, depthwiseMultiplier, + width, height, outputWidth, outputHeight, + kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else if (kW == 3 && kH == 3) { + conv_depthwise2d_forward_kernel<3> <<>>( + input_a, output_a, weight_a, bias_a, has_bias, n, outputChannels, depthwiseMultiplier, + width, height, outputWidth, outputHeight, + kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else if (kW == 1 && kH == 1) { + conv_depthwise2d_forward_kernel<1> <<>>( + input_a, output_a, weight_a, bias_a, has_bias, n, outputChannels, depthwiseMultiplier, + width, height, outputWidth, outputHeight, + kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + conv_depthwise2d_forward_kernel_generic<<>>( + input_a, output_a, weight_a, bias_a, has_bias, n, outputChannels, depthwiseMultiplier, + width, height, outputWidth, outputHeight, + kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); +} + +void conv_depthwise2d_backward_out( + const Tensor &input, + const Tensor &grad_output, + const Tensor &grad_input, + const Tensor &weight, + const int kW, const int kH, + const int dW, const int dH, + const int padW, const int padH, + const int dilationW, const int dilationH) { + // Only handle 4D Input Tensors for now + TORCH_CHECK(input.numel() > 0 && input.dim() == 4); + TORCH_CHECK(weight.numel() > 0 && weight.dim() == 4); + TORCH_CHECK(grad_output.numel() > 0 && grad_output.dim() == 4); + + // Minimal shape checking, as above + // Same # of elements in batch + TORCH_CHECK(input.sizes()[0] == grad_output.sizes()[0]); + // Same # of filters as outputChannels + TORCH_CHECK(weight.sizes()[0] == grad_output.sizes()[1]); + + // Resize Grainput_a + auto in_sizes = input.sizes(); + resize_output(grad_input, in_sizes); + + int inputChannels = in_sizes[1]; + int height = in_sizes[2]; + int width = in_sizes[3]; + + auto gO_sizes = grad_output.sizes(); + int outputChannels = gO_sizes[1]; + int outputHeight = gO_sizes[2]; + int outputWidth = gO_sizes[3]; + + int depthwiseMultiplier = outputChannels / inputChannels; + + // Kernel currently relies upon all the Tensors to be contiguous + TORCH_CHECK(grad_output.is_contiguous()); + TORCH_CHECK(weight.is_contiguous()); + TORCH_CHECK(grad_input.is_contiguous()); + + // One thread per grainput_a value + TORCH_CHECK(canUse32BitIndexMath(grad_input) && + canUse32BitIndexMath(grad_output)); + int32_t n = grad_input.numel(); + int blocks = GET_BLOCKS(n); + dim3 grid(blocks); + dim3 block(CUDA_NUM_THREADS); + const auto stream = c10::cuda::getCurrentCUDAStream(); + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, grad_output.scalar_type(), + "conv_depthwise2d_backward_cuda", [&] { + auto grad_output_a = grad_output.packed_accessor32(); + auto grad_input_a = grad_input.packed_accessor32(); + auto weight_a = weight.packed_accessor32(); + + if (kW == 5 && kH == 5) { + if (dW == 1 && dH == 1){ + conv_depthwise2d_backward_kernel<5, 1><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else if (dW == 2 && dH == 2) { + conv_depthwise2d_backward_kernel<5, 2><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + conv_depthwise2d_backward_kernel<5, 0><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + } else if (kW == 3 && kH == 3) { + if (dW == 1 && dH == 1){ + conv_depthwise2d_backward_kernel<3, 1><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else if (dW == 2 && dH == 2) { + conv_depthwise2d_backward_kernel<3, 2><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + conv_depthwise2d_backward_kernel<3, 0><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + } else if (kW == 1 && kH == 1) { + if (dW == 1 && dH == 1){ + conv_depthwise2d_backward_kernel<1, 1><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else if (dW == 2 && dH == 2) { + conv_depthwise2d_backward_kernel<1, 2><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + conv_depthwise2d_backward_kernel<1, 0><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + } else if (dW == 1 && dH == 1) { + conv_depthwise2d_backward_kernel<0, 1><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else if (dW == 2 && dH == 2) { + conv_depthwise2d_backward_kernel<0, 2><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + conv_depthwise2d_backward_kernel<0, 0><<>>( + grad_output_a, grad_input_a, weight_a, n, inputChannels, depthwiseMultiplier, outputChannels, width, + height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); +} + +// Crude benchmarks suggest 256 is better than 512 and 1024 +// TODO: Autotune/use better heuristics, improve speed more. +int getGradParamsNumThreads(int batchSize) { + //warp per item in a batch, up to a maximum + constexpr int MAX_BLOCK_SIZE = 256; + return std::min(batchSize * at::cuda::warp_size(), MAX_BLOCK_SIZE); +} + +void conv_depthwise2d_grad_weight_out( + const Tensor &input, + const Tensor &grad_output, + const Tensor &grad_weight, + const int kW, const int kH, + const int dW, const int dH, + const int padW, const int padH, + const int dilationW, const int dilationH) { + // Only handle 4D Input Tensors for now + TORCH_CHECK(input.numel() > 0 && input.dim() == 4); + TORCH_CHECK(grad_output.numel() > 0 && grad_output.dim() == 4); + + // Minimal shape checking as above + // Same # of elements in batch + TORCH_CHECK(input.sizes()[0] == grad_output.sizes()[0]); + + auto in_sizes = input.sizes(); + int batchSize = in_sizes[0]; + int inputChannels = in_sizes[1]; + int height = in_sizes[2]; + int width = in_sizes[3]; + + auto gO_sizes = grad_output.sizes(); + int outputChannels = gO_sizes[1]; + int outputHeight = gO_sizes[2]; + int outputWidth = gO_sizes[3]; + + int depthwiseMultiplier = outputChannels / inputChannels; + + resize_output(grad_weight, {outputChannels, 1, kH, kW}); + + // Kernel currently relies upon all the Tensors to be contiguous + TORCH_CHECK(grad_output.is_contiguous()); + TORCH_CHECK(input.is_contiguous()); + TORCH_CHECK(grad_weight.is_contiguous()); + + // We parallelize so that each block computes a single value in grad_weight + TORCH_CHECK(canUse32BitIndexMath(input) && + canUse32BitIndexMath(grad_output)); + int blocks = outputChannels * kH * kW; + + // Make sure we have enough threads to perform the reduction, and use this number + // to create the shared memory size for the reduction + dim3 grid(blocks); + dim3 block(getGradParamsNumThreads(batchSize)); + const auto stream = c10::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, grad_output.scalar_type(), + "conv_depthwise2d_grad_weight_cuda", [&] { + const auto grad_output_a = grad_output.packed_accessor32(); + const auto input_a = input.packed_accessor32(); + const auto grad_weight_a = grad_weight.packed_accessor32(); + using acc_t = at::acc_type; + int warp_size = at::cuda::warp_size(); + TORCH_INTERNAL_ASSERT(block.x % warp_size == 0); + int smem = (block.x / warp_size) * sizeof(acc_t); + conv_depthwise2d_grad_weight_kernel<<>>( + grad_output_a, input_a, grad_weight_a, batchSize, inputChannels, outputChannels, depthwiseMultiplier, + width, height, outputWidth, outputHeight, kW, kH, dW, dH, padW, padH, dilationW, dilationH); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); +} + +} // namespace (anonymous) + +Tensor& conv_depthwise2d_cuda_out( + const Tensor &input_, + const Tensor &weight_, + IntArrayRef kernel_size, + const std::optional &bias_opt, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + Tensor &out) { + TORCH_CHECK(kernel_size.size() == 2); + TORCH_CHECK(stride.size() == 2); + TORCH_CHECK(padding.size() == 2); + TORCH_CHECK(dilation.size() == 2); + + auto input = input_.expect_contiguous(); + auto weight = weight_.expect_contiguous(); + auto bias = [&] { + if (bias_opt.has_value() && bias_opt->defined()) { + return bias_opt->expect_contiguous(); + } + return c10::MaybeOwned::owned(std::in_place); + }(); + + conv_depthwise2d_forward_out( + *input, + out, + *weight, + *bias, + kernel_size[1], kernel_size[0], + stride[1], stride[0], + padding[1], padding[0], + dilation[1], dilation[0]); + return out; +} + +Tensor conv_depthwise2d_cuda( + const Tensor &input, + const Tensor &weight, + IntArrayRef kernel_size, + const std::optional &bias, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation) { + auto out = at::empty({0}, input.options()); + return conv_depthwise2d_cuda_out(input, weight, kernel_size, bias, + stride, padding, dilation, out); +} + +std::tuple conv_depthwise2d_backward_cuda_out( + const Tensor & grad_output_, + const Tensor & self_, + const Tensor & weight_, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + Tensor & grad_input, + Tensor & grad_weight) { + auto grad_output = grad_output_.expect_contiguous(); + + if (grad_weight.defined()) { + auto self = self_.expect_contiguous(); + conv_depthwise2d_grad_weight_out( + *self, *grad_output, grad_weight, + kernel_size[1], kernel_size[0], + stride[1], stride[0], + padding[1], padding[0], + dilation[1], dilation[0]); + } + + if (grad_input.defined()) { + auto weight = weight_.expect_contiguous(); + conv_depthwise2d_backward_out( + self_, *grad_output, grad_input, *weight, + kernel_size[1], kernel_size[0], + stride[1], stride[0], + padding[1], padding[0], + dilation[1], dilation[0]); + } + return std::forward_as_tuple(grad_input, grad_weight); +} + +std::tuple conv_depthwise2d_backward_cuda( + const Tensor& grad_output, + const Tensor& self, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + std::array output_mask) { + Tensor grad_input; + Tensor grad_weight; + + if (output_mask[0]) { + grad_input = at::empty({0}, grad_output.options()); + } + + if (output_mask[1]) { + grad_weight = at::empty({0}, grad_output.options()); + } + return conv_depthwise2d_backward_cuda_out( + grad_output, + self, + weight, + kernel_size, + stride, + padding, + dilation, + grad_input, + grad_weight); +} + +REGISTER_CUDA_DISPATCH(conv_depthwise2d_backward_stub, &conv_depthwise2d_backward_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DepthwiseConv3d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DepthwiseConv3d.cu new file mode 100644 index 0000000000000000000000000000000000000000..ffffad4c8fb0fb14bc50977f6f763899996c2502 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DepthwiseConv3d.cu @@ -0,0 +1,706 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +#include +#include +#include + +namespace at::native { +namespace { + +template +__global__ void conv_depthwise3d_cuda_kernel( + const PackedTensorAccessor32 input, + PackedTensorAccessor32 output, + const PackedTensorAccessor32 kernel, + const scalar_t* bias, + int strideT, int strideH, int strideW, + int paddingT, int paddingH, int paddingW, + int dilationT_, int dilationH_, int dilationW_) +{ + const int kT = kKnownKernelT > 0 ? kKnownKernelT : kernel.size(2); + const int kH = kKnownKernelH > 0 ? kKnownKernelH : kernel.size(3); + const int kW = kKnownKernelW > 0 ? kKnownKernelW : kernel.size(4); + const int oC = output.size(1); + const int oT = output.size(2); + const int oH = output.size(3); + const int oW = output.size(4); + const int iC = input.size(1); + const int iT = input.size(2); + const int iH = input.size(3); + const int iW = input.size(4); + const int channel_multiplier = oC / iC; + const int dilationT = kKnownDilationT > 0 ? kKnownDilationT : dilationT_; + const int dilationH = kKnownDilationH > 0 ? kKnownDilationH : dilationH_; + const int dilationW = kKnownDilationW > 0 ? kKnownDilationW : dilationW_; + const int num_output = output.size(0) * output.stride(0); + + CUDA_KERNEL_LOOP(index, num_output) { + const int out_col = index % oW; + const int out_row = (index / oW) % oH; + const int out_frame = (index / oW / oH) % oT; + const int out_channel = (index / oW / oH / oT) % oC; + const int batch = index / oW / oH / oT / oC; + + const int in_channel = out_channel / channel_multiplier; + + const int in_col_start = out_col * strideW - paddingW; + const int in_row_start = out_row * strideH - paddingH; + const int in_frame_start = out_frame * strideT - paddingT; + + accscalar_t sum = 0; + const scalar_t *kernel_ptr = kernel[out_channel].data(); + const scalar_t *input_ptr = + &input[batch][in_channel][in_frame_start][in_row_start][in_col_start]; + for (int k_frame = 0; k_frame < kT; ++k_frame) { + const int in_frame = in_frame_start + k_frame * dilationT; + for (int k_row = 0; k_row < kH; ++k_row) { + const int in_row = in_row_start + k_row * dilationH; + for (int k_col = 0; k_col < kW; ++k_col) { + const accscalar_t op1 = *(kernel_ptr++); + const int in_col = in_col_start + k_col * dilationW; + if (in_frame >= 0 && in_row >= 0 && in_col >= 0 && + in_frame < iT && in_row < iH && in_col < iW) { + sum += op1 * *(input_ptr); + } + input_ptr += dilationW; + } + input_ptr += iW * dilationH - kW * dilationW; + } + input_ptr += iW * (iH * dilationT - kH * dilationH); + } + if (bias != nullptr) { + sum += bias[out_channel]; + } + + output[batch][out_channel][out_frame][out_row][out_col] = sum; + } +} + +template +__global__ void +conv_depthwise3d_cuda_backward_input_kernel( + const PackedTensorAccessor32 grad_output, + PackedTensorAccessor32 grad_input, + const PackedTensorAccessor32 kernel, + int strideT_, int strideH_, int strideW_, + int paddingT, int paddingH, int paddingW, + int dilationT_, int dilationH_, int dilationW_) { + const int kT = kKnownKernelT > 0 ? kKnownKernelT : kernel.size(2); + const int kH = kKnownKernelH > 0 ? kKnownKernelH : kernel.size(3); + const int kW = kKnownKernelW > 0 ? kKnownKernelW : kernel.size(4); + const int oC = grad_output.size(1); + const int oT = grad_output.size(2); + const int oH = grad_output.size(3); + const int oW = grad_output.size(4); + const int iC = grad_input.size(1); + const int iT = grad_input.size(2); + const int iH = grad_input.size(3); + const int iW = grad_input.size(4); + const int channel_multiplier = oC / iC; + const int dilationT = kKnownDilationT > 0 ? kKnownDilationT : dilationT_; + const int dilationH = kKnownDilationH > 0 ? kKnownDilationH : dilationH_; + const int dilationW = kKnownDilationW > 0 ? kKnownDilationW : dilationW_; + const int strideT = kKnownStrideT > 0 ? kKnownStrideT : strideT_; + const int strideH = kKnownStrideH > 0 ? kKnownStrideH : strideH_; + const int strideW = kKnownStrideW > 0 ? kKnownStrideW : strideW_; + const int num_input = grad_input.size(0) * grad_input.stride(0); + + CUDA_KERNEL_LOOP(index, num_input) { + const int in_col = index % iW; + const int in_row = (index / iW) % iH; + const int in_frame = (index / iW / iH) % iT; + const int in_channel = (index / iW / iH / iT) % iC; + const int batch = index / iW / iH / iT / iC; + + const int out_col_end = in_col + paddingW; + const int out_row_end = in_row + paddingH; + const int out_frame_end = in_frame + paddingT; + + const scalar_t* kernel_ptr = kernel[in_channel * channel_multiplier].data(); + accscalar_t sum = 0; + + for (int k_chn = in_channel * channel_multiplier; + k_chn < (in_channel + 1) * channel_multiplier; + ++k_chn) { + const scalar_t* gout_ptr = grad_output[batch][k_chn].data(); + + for (int k_frame = 0; k_frame < kT; ++k_frame) { + const int out_frame_raw = out_frame_end - k_frame * dilationT; + const int out_frame = out_frame_raw / strideT; + for (int k_row = 0; k_row < kH; ++k_row) { + const int out_row_raw = out_row_end - k_row * dilationH; + const int out_row = out_row_raw / strideH; + for (int k_col = 0; k_col < kW; ++k_col) { + const accscalar_t op1 = *(kernel_ptr++); + const int out_col_raw = out_col_end - k_col * dilationW; + const int out_col = out_col_raw / strideW; + + const int out_offs = (out_frame * oH + out_row) * oW + out_col; + + accscalar_t op2 = (accscalar_t)0; + if (out_col >= 0 && out_row >= 0 && out_frame >= 0 && + out_col < oW && out_row < oH && out_frame < oT) { + op2 = *(gout_ptr + out_offs); + } + if (out_frame * strideT == out_frame_raw && + out_row * strideH == out_row_raw && + out_col * strideW == out_col_raw) { + sum += op1 * op2; + } + } + } + } + } + + grad_input[batch][in_channel][in_frame][in_row][in_col] = sum; + } +} + +template +__global__ void +conv_depthwise3d_cuda_backward_weight_kernel( + const PackedTensorAccessor32 grad_output, + const PackedTensorAccessor32 input, + PackedTensorAccessor32 grad_kernel, + int strideT, int strideH_, int strideW_, + int paddingT, int paddingH, int paddingW, + int dilationT, int dilationH, int dilationW) { + const int kC = grad_kernel.size(0); + const int kT = grad_kernel.size(2); + const int kH = grad_kernel.size(3); + const int kW = grad_kernel.size(4); + + const int strideH = kKnownStrideH > 0 ? kKnownStrideH : strideH_; + const int strideW = kKnownStrideW > 0 ? kKnownStrideW : strideW_; + + const int k_col = blockIdx.x % kW; + const int k_row = (blockIdx.x / kW) % kH; + const int k_frame = (blockIdx.x / kW / kH) % kT; + const int k_channel = blockIdx.x / kW / kH / kT; + scalar_t *result = &grad_kernel[k_channel][0][k_frame][k_row][k_col]; + + const int oT = grad_output.size(2); + const int oH = grad_output.size(3); + const int oW = grad_output.size(4); + const int iT = input.size(2); + const int iH = input.size(3); + const int iW = input.size(4); + const int channel_multiplier = grad_output.size(1) / input.size(1); + const int in_channel = k_channel / channel_multiplier; + + extern __shared__ int sdata_raw[]; + scalar_t* sdata = reinterpret_cast(sdata_raw); + + if (k_channel >= kC) { + return; + } + + const int laneid = threadIdx.x % C10_WARP_SIZE; + const int warpid = threadIdx.x / C10_WARP_SIZE; + const int nwarps = blockDim.x / C10_WARP_SIZE; + + accscalar_t grad = 0; + int batch = warpid / oT; + int gout_frame = warpid - batch * oT; + for (int outer_pos = warpid; outer_pos < input.size(0) * oT; + outer_pos += nwarps, gout_frame += nwarps) { + while (gout_frame >= oT) { gout_frame -= oT; batch ++; } + + const int in_frame = (gout_frame * strideT) + (k_frame * dilationT) - paddingT; + + if (in_frame < 0 || in_frame >= iT) { + continue; + } + + const scalar_t* gout_ptr = grad_output[batch][k_channel][gout_frame].data() + laneid; + const scalar_t* input_ptr = input[batch][in_channel][in_frame].data(); + + int gout_row = laneid / oW; + int gout_col = laneid - gout_row * oW; + + for (; gout_row < oH; ) { + const accscalar_t op1 = *(gout_ptr); + gout_ptr += C10_WARP_SIZE; + + const int in_col = (gout_col * strideW) + (k_col * dilationW) - paddingW; + const int in_row = (gout_row * strideH) + (k_row * dilationH) - paddingH; + const int in_pos = in_row * iW + in_col; + + accscalar_t op2 = (accscalar_t)0; + if (in_col >= 0 && in_col < iW && in_row >= 0 && in_row < iH) { + op2 = *(input_ptr + in_pos); + } + + gout_col += C10_WARP_SIZE; + while (gout_col >= oW) { + gout_col -= oW; gout_row ++; + } + + grad += op1 * op2; + } + } + + sdata[threadIdx.x] = grad; + __syncthreads(); + + CUDA_KERNEL_ASSERT(__popc(blockDim.x) == 1); +#pragma unroll + for (int i = blockDim.x / 2; i >= 1; i >>= 1) { + if (threadIdx.x < i) { + sdata[threadIdx.x] += sdata[threadIdx.x + i]; + } + __syncthreads(); + } + + if (threadIdx.x == 0) { + *result = sdata[0]; + } +} + +template +void conv_depthwise_shape_check( + const Tensor& input, + const Tensor& weight, + const Tensor& bias, + const Tensor& grad_output, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation) { + TORCH_CHECK(kernel_size.size() == dim, + "kernel size length should be ", dim, ", but got ", kernel_size.size()); + TORCH_CHECK(stride.size() == dim, + "stride length should be ", dim, ", but got ", stride.size()); + TORCH_CHECK(padding.size() == dim, + "padding length should be ", dim, ", but got ", padding.size()); + TORCH_CHECK(dilation.size() == dim, + "dilation length should be ", dim, ", but got ", dilation.size()); + + TORCH_CHECK(weight.defined(), + "Weight must be defined."); + TORCH_CHECK(input.dim() == dim + 1 || input.dim() == dim + 2, + "Input dimension should be ", + dim + 1, "D or ", dim + 2, "D, got ", + input.dim(), "D"); + TORCH_CHECK(weight.dim() == dim + 2, + "Weight dimension should be ", dim + 2, "D, got ", weight.dim(), "D"); + TORCH_CHECK(weight.size(1) == 1, + "Depthwise weight should have in_channels=1, got ", weight.size(1)); + TORCH_CHECK(weight.size(0) % input.size(-dim - 1) == 0, + "Depthwise out channels should be a multiple of in channels, got ", + weight.size(0), " and ", input.size(-dim - 1)); + for (int i = 0; i < dim; ++i) { + TORCH_CHECK(weight.size(i + 2) == kernel_size[i], + "kernel size and weight size mismatch, got ", + kernel_size, " and ", weight.sizes()); + TORCH_CHECK(stride[i] >= 1, + "stride should be at least 1, got ", stride); + TORCH_CHECK(padding[i] >= 0, + "padding should be non-negative, got ", padding); + TORCH_CHECK(dilation[i] >= 1, + "dilation should be at least 1, got ", dilation); + } + + if (bias.defined()) { + TORCH_CHECK(bias.dim() == 1, + "Bias should be 1D tensor, got ", bias.dim(), "D"); + TORCH_CHECK(bias.size(0) == weight.size(0), + "Bias length should be equal to out_channels, got ", + bias.size(0), " and ", weight.size(0)); + } + + if (grad_output.defined()) { + auto expected_output_size = conv_output_size(input.sizes(), weight.sizes(), + padding, stride, dilation); + TORCH_CHECK(static_cast(grad_output.dim()) == expected_output_size.size(), + "Expect grad_output to be ", + expected_output_size.size(), "D, got ", + grad_output.dim(), "D."); + for (int i = 0; i < grad_output.dim(); ++i) { + TORCH_CHECK(grad_output.size(i) == expected_output_size[i], + "Expect grad_output to be of same shape as output, got ", + grad_output.size(i), " and ", expected_output_size[i], + " at dimension ", i); + } + } +} + +} + +#define NODEF_OR_EQUAL(x, y) ((y) < 0 || (x) == (y)) +#define NODEF_OR_EQUAL_3(x, y1, y2, y3) \ + (NODEF_OR_EQUAL(x[0], y1) && \ + NODEF_OR_EQUAL(x[1], y2) && \ + NODEF_OR_EQUAL(x[2], y3)) + +#define DWCONV3D_FORWARD_DISPATCH_SPECIALIZATION(kt, kh, kw, dilt, dilh, dilw) \ + if (NODEF_OR_EQUAL_3(kernel_size, (kt), (kh), (kw)) && \ + NODEF_OR_EQUAL_3(dilation, (dilt), (dilh), (dilw))) { \ + using accscalar_t = acc_type; \ + conv_depthwise3d_cuda_kernel \ + \ + <<>>( \ + input_.packed_accessor32(), \ + output_.packed_accessor32(), \ + weight_.packed_accessor32(), \ + bias_ptr, \ + stride[0], stride[1], stride[2], \ + padding[0], padding[1], padding[2], \ + dilation[0], dilation[1], dilation[2]); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + } else + +#define DWCONV3D_FORWARD_DISPATCH_OTHERS \ + { \ + using accscalar_t = acc_type; \ + conv_depthwise3d_cuda_kernel \ + \ + <<>>( \ + input_.packed_accessor32(), \ + output_.packed_accessor32(), \ + weight_.packed_accessor32(), \ + bias_ptr, \ + stride[0], stride[1], stride[2], \ + padding[0], padding[1], padding[2], \ + dilation[0], dilation[1], dilation[2]); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + } + +Tensor conv_depthwise3d_cuda( + const Tensor& input, + const Tensor& weight, + IntArrayRef kernel_size, const std::optional& bias_opt, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned bias_maybe_owned = at::borrow_from_optional_tensor(bias_opt); + const Tensor& bias = *bias_maybe_owned; + + TORCH_CHECK(input.device() == weight.device(), "expects input and weight tensors to be on the same device."); + if (bias.defined()) { + TORCH_CHECK(input.device() == bias.device(), "expects input and bias tensors to be on the same device."); + } + + conv_depthwise_shape_check<3>(input, weight, bias, Tensor() /* undefined */, + kernel_size, stride, padding, dilation); + + Tensor input_ = input.contiguous(); + + if (input.dim() == 4 /* no batch */) { + input_ = input.unsqueeze(0); + } + + auto output_size = conv_output_size(input_.sizes(), weight.sizes(), + padding, stride, dilation); + for (size_t i = 0; i < output_size.size(); ++i) { + TORCH_CHECK(output_size[i] > 0, + "Output size should be positive, got ", output_size[i], " at dim ", i); + } + Tensor output = at::empty(output_size, input.options()); + Tensor output_ = output; + Tensor weight_ = weight.contiguous(); + Tensor bias_ = bias.defined() ? bias.contiguous() : bias; + + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + input.scalar_type(), + "conv_depthwise3d", + [&]{ + int64_t num_outputs = output_.numel(); + int64_t block = 256; + int64_t grid = std::min((num_outputs - 1) / block + 1, (int64_t)65536); + int64_t smem = 0; + + const scalar_t* bias_ptr = + bias_.defined() ? bias_.const_data_ptr() : nullptr; + + // Range check to avoid overflow in CUDA kernels. + TORCH_CHECK(input_.numel() <= std::numeric_limits::max(), + "Input tensor is too large."); + TORCH_CHECK(output_.numel() <= std::numeric_limits::max(), + "Output tensor is too large."); + TORCH_CHECK(weight_.numel() <= std::numeric_limits::max(), + "Weight tensor is too large."); + for (int i = 0; i < 3; ++i) { + TORCH_CHECK(padding[i] * 2 + input.size(i + 2) <= std::numeric_limits::max(), + "Padded input tensor is too large."); + } + + DWCONV3D_FORWARD_DISPATCH_SPECIALIZATION(3, 3, 3, 1, 1, 1) + DWCONV3D_FORWARD_DISPATCH_SPECIALIZATION(-1, -1, -1, 1, 1, 1) + DWCONV3D_FORWARD_DISPATCH_OTHERS + } + ); + + return output; +} + +#undef DWCONV3D_FORWARD_DISPATCH_SPECIALIZATION +#undef DWCONV3D_FORWARD_DISPATCH_OTHERS + +#define DWCONV3D_BACKWARD_INPUT_DISPATCH_SPECIALIZATION( \ + kt, kh, kw, dilt, dilh, dilw, dt, dh, dw) \ + if (NODEF_OR_EQUAL_3(kernel_size, (kt), (kh), (kw)) && \ + NODEF_OR_EQUAL_3(dilation, (dilt), (dilh), (dilw)) && \ + NODEF_OR_EQUAL_3(stride, (dt), (dh), (dw))) { \ + using accscalar_t = acc_type; \ + conv_depthwise3d_cuda_backward_input_kernel \ + \ + <<>>( \ + grad_output_.packed_accessor32(), \ + grad_input_.packed_accessor32(), \ + weight_.packed_accessor32(), \ + stride[0], stride[1], stride[2], \ + padding[0], padding[1], padding[2], \ + dilation[0], dilation[1], dilation[2]); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + } else + +#define DWCONV3D_BACKWARD_INPUT_DISPATCH_OTHERS \ + { \ + using accscalar_t = acc_type; \ + conv_depthwise3d_cuda_backward_input_kernel \ + \ + <<>>( \ + grad_output_.packed_accessor32(), \ + grad_input_.packed_accessor32(), \ + weight_.packed_accessor32(), \ + stride[0], stride[1], stride[2], \ + padding[0], padding[1], padding[2], \ + dilation[0], dilation[1], dilation[2]); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + } + +#define DWCONV3D_BACKWARD_WEIGHT_DISPATCH_SPECIALIZATION(dh, dw) \ + if (NODEF_OR_EQUAL_3(stride, -1, (dh), (dw))) { \ + using accscalar_t = acc_type; \ + conv_depthwise3d_cuda_backward_weight_kernel \ + \ + <<>>( \ + grad_output_.packed_accessor32(), \ + input_.packed_accessor32(), \ + grad_weight.packed_accessor32(), \ + stride[0], stride[1], stride[2], \ + padding[0], padding[1], padding[2], \ + dilation[0], dilation[1], dilation[2]); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + } else + +#define DWCONV3D_BACKWARD_WEIGHT_DISPATCH_OTHERS \ + { \ + using accscalar_t = acc_type; \ + conv_depthwise3d_cuda_backward_weight_kernel \ + \ + <<>>( \ + grad_output_.packed_accessor32(), \ + input_.packed_accessor32(), \ + grad_weight.packed_accessor32(), \ + stride[0], stride[1], stride[2], \ + padding[0], padding[1], padding[2], \ + dilation[0], dilation[1], dilation[2]); \ + C10_CUDA_KERNEL_LAUNCH_CHECK(); \ + } + +std::tuple _depthwise_3d_backward_cuda_out( + Tensor& grad_input, + Tensor& grad_weight, + Tensor& grad_bias, + const Tensor& grad_output, + const Tensor& input, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + const std::array output_mask) +{ + + TORCH_CHECK(grad_output.device() == input.device() && + input.device() == weight.device(), + "expects input, weight and grad_output to be on the same device."); + conv_depthwise_shape_check<3>( + input, weight, Tensor() /* undefined */, grad_output, + kernel_size, stride, padding, dilation); + + const Tensor grad_output_ = grad_output.contiguous(); + + Tensor grad_input_ = + (output_mask[0] ? grad_input + : Tensor()); + + if (output_mask[0]) { + const Tensor weight_ = weight.contiguous(); + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + grad_output.scalar_type(), + "conv_depthwise3d", + [&] { + int64_t num_inputs = grad_input_.numel(); + int64_t block = 256; + int64_t grid = std::min((num_inputs - 1) / block + 1, (int64_t)65536); + + // Range check to avoid overflow in CUDA kernels. + TORCH_CHECK(grad_input_.numel() <= std::numeric_limits::max(), + "Input tensor is too large."); + TORCH_CHECK(grad_output_.numel() <= std::numeric_limits::max(), + "Output tensor is too large."); + TORCH_CHECK(weight_.numel() <= std::numeric_limits::max(), + "Weight tensor is too large."); + for (int i = 0; i < 3; ++i) { + TORCH_CHECK(padding[i] * 2 + input.size(i + 2) <= std::numeric_limits::max(), + "Padded input tensor is too large."); + } + + DWCONV3D_BACKWARD_INPUT_DISPATCH_SPECIALIZATION( + 3, 3, 3, 1, 1, 1, 1, 1, 1) + DWCONV3D_BACKWARD_INPUT_DISPATCH_SPECIALIZATION( + 3, 3, 3, 1, 1, 1, -1, -1, -1) + DWCONV3D_BACKWARD_INPUT_DISPATCH_SPECIALIZATION( + 3, 3, 3, -1, -1, -1, 1, 1, 1) + DWCONV3D_BACKWARD_INPUT_DISPATCH_SPECIALIZATION( + 3, 3, 3, -1, -1, -1, -1, -1, -1) + DWCONV3D_BACKWARD_INPUT_DISPATCH_OTHERS + } + ); + } + + if (output_mask[1]) { + const Tensor input_ = input.contiguous(); + AT_DISPATCH_FLOATING_TYPES_AND2( + kHalf, + kBFloat16, + grad_output.scalar_type(), + "conv_depthwise3d", + [&] { + int64_t grid = grad_weight.numel(); + int64_t block = 256; + int64_t smem = sizeof(scalar_t) * block; + + const int64_t int_max = std::numeric_limits::max(); + TORCH_CHECK(grad_input_.numel() <= int_max, + "Input tensor is too large."); + TORCH_CHECK(grad_output_.numel() <= int_max, + "Output tensor is too large."); + TORCH_CHECK(weight.numel() <= int_max, + "Weight tensor is too large."); + for (int i = 0; i < 3; ++i) { + TORCH_CHECK(padding[i] * 2 + input.size(i + 2) <= int_max, + "Padded input tensor is too large."); + } + int64_t warp_size = at::cuda::warp_size(); + TORCH_CHECK(grad_output_.size(0) * grad_output_.size(2) < int_max - block / warp_size && + grad_output_.size(3) <= int_max - warp_size && + grad_output_.size(4) <= int_max - warp_size, + "Output size is too large."); + + DWCONV3D_BACKWARD_WEIGHT_DISPATCH_SPECIALIZATION(1, 1) + DWCONV3D_BACKWARD_WEIGHT_DISPATCH_SPECIALIZATION(2, 2) + DWCONV3D_BACKWARD_WEIGHT_DISPATCH_OTHERS + } + ); + } + + if (output_mask[2]) { + grad_bias = grad_output.sum({0, 2, 3, 4}); + } + + return std::tie(grad_input, grad_weight, grad_bias); + +} + + +std::tuple conv_depthwise3d_backward_cuda_out(const Tensor& grad_output, + const Tensor& input, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + Tensor& grad_input, + Tensor& grad_weight, + Tensor& grad_bias) { + if (grad_weight.defined()) { + grad_weight.resize_(weight.sizes()); + grad_weight.zero_(); + } + + return _depthwise_3d_backward_cuda_out( + grad_input, + grad_weight, + grad_bias, + grad_output, + input, + weight, + kernel_size, + stride, + padding, + dilation, + {true,true,true}); +} + +std::tuple conv_depthwise3d_backward_cuda( + const Tensor& grad_output, + const Tensor& input, + const Tensor& weight, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + const std::array output_mask) { + + auto options = grad_output.options(); + Tensor grad_input = + (output_mask[0] ? at::empty(input.sizes(), options) : Tensor()); + Tensor grad_weight = + (output_mask[1] ? at::empty(weight.sizes(), options) : Tensor()); + Tensor grad_bias; /* undefined temporarily */ + + return _depthwise_3d_backward_cuda_out( + grad_input, + grad_weight, + grad_bias, + grad_output, + input, + weight, + kernel_size, + stride, + padding, + dilation, + output_mask + ); + +} + +REGISTER_CUDA_DISPATCH(conv_depthwise3d_backward_stub, &conv_depthwise3d_backward_cuda) + +#undef DWCONV3D_BACKWARD_INPUT_DISPATCH_SPECIALIZATION +#undef DWCONV3D_BACKWARD_INPUT_DISPATCH_OTHERS + +#undef NODEF_OR_EQUAL_3 +#undef NODEF_OR_EQUAL + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DeviceAddCmulCdiv.cuh b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DeviceAddCmulCdiv.cuh new file mode 100644 index 0000000000000000000000000000000000000000..190fca8caad959fc8b409736fc9604193b473672 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DeviceAddCmulCdiv.cuh @@ -0,0 +1,32 @@ +#pragma once + +namespace at::native { + +// Computes input + alpha * op(tensor1, tensor2). +// Special-cases alpha=1 and uses explicit std::fma for multiplies +// to ensure consistent FMA behavior across all code paths. +template +C10_HOST_DEVICE __forceinline__ opmath_t pointwise_op_impl( + opmath_t input, + opmath_t tensor1, + opmath_t tensor2, + opmath_t alpha, + Op op) { + if (alpha == opmath_t(1)) { + // Use explicit fma for std::multiplies on real floating-point types + // to guarantee FMA instruction (std::fma doesn't support complex) + if constexpr (std::is_same_v> && + std::is_floating_point_v) { + return std::fma(tensor1, tensor2, input); + } else { + return input + op(tensor1, tensor2); + } + } + if constexpr(std::is_floating_point_v) { + return std::fma(alpha, op(tensor1, tensor2), input); + } else { + return input + alpha * op(tensor1, tensor2); + } +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DeviceSqrt.cuh b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DeviceSqrt.cuh new file mode 100644 index 0000000000000000000000000000000000000000..6dad8efbca88aa7144a6ef08646940402aea3521 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DeviceSqrt.cuh @@ -0,0 +1,25 @@ +#pragma once + +namespace at::native { +#if defined(USE_ROCM) +// take these out when ROCm implements std:: math functions +#include +template +static __forceinline__ __device__ scalar_t device_sqrt(scalar_t val); + +template <> +__forceinline__ __device__ float device_sqrt(float val) { + return ::sqrtf(val); +} + +template <> +__forceinline__ __device__ double device_sqrt(double val) { + return ::sqrt(val); +} +#else +template +__forceinline__ __device__ double device_sqrt(scalar_t val) { + return std::sqrt(val); +} +#endif +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DilatedMaxPool2d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DilatedMaxPool2d.cu new file mode 100644 index 0000000000000000000000000000000000000000..4ca89be1d1b489552d551ab35b3735e1108c58c7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DilatedMaxPool2d.cu @@ -0,0 +1,788 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at::native { +namespace { + +__device__ inline int min(int a, int b) { + return a <= b ? a : b; +} + +#ifdef USE_ROCM +#define CUDA_MAX_THREADS 256 +#define BLOCK_STRIDE_FWD 2 // increasing block_stride to lower # of blocks launched +#define BLOCK_STRIDE_BWD 4 // increasing block_stride to lower # of blocks launched +#else +#define CUDA_MAX_THREADS 1024 // this is safe, in reality 256 is our limit +#define BLOCK_STRIDE_FWD 2 // increasing block_stride to lower # of blocks launched +#define BLOCK_STRIDE_BWD 2 // increasing block_stride to lower # of blocks launched +#endif + +template +static __device__ inline index_t p_start(index_t size, int pad, int kernel, int dilation, int stride) { + const auto kernel_extent = static_cast((kernel - 1) * dilation + 1); + return (size + pad < kernel_extent) ? index_t(0) : (size + pad - kernel_extent) / stride + 1; +} + +template +static __device__ inline index_t p_end(index_t size, int pad, index_t pooled_size, int stride) { + return std::min((size + pad) / stride + 1, pooled_size); +} + +static inline bool can_use_int32_nhwc( + int64_t nbatch, int64_t channels, + int64_t height, int64_t width, + int64_t pooled_height, int64_t pooled_width, + int64_t in_stride_n, int64_t in_stride_c, + int64_t in_stride_h, int64_t in_stride_w) +{ + constexpr int64_t int_max = std::numeric_limits::max(); + + int64_t max_intra_batch = + (height ? (height - 1) * in_stride_h : 0) + + (width ? (width - 1) * in_stride_w : 0) + + (channels? (channels - 1) * in_stride_c : 0); + + int64_t max_input_offset = (nbatch ? (nbatch - 1) * in_stride_n : 0) + max_intra_batch; + + if (max_input_offset > int_max) return false; + + int64_t out_batch_stride = pooled_height * pooled_width * channels; + if ((nbatch ? (nbatch - 1) * out_batch_stride : 0) > int_max) return false; + + if (height * width > int_max) return false; + + return true; +} + +static inline bool can_use_int32_nchw( + int64_t nbatch, int64_t channels, + int64_t height, int64_t width, + int64_t pooled_height, int64_t pooled_width) { + int64_t hw = height * width; + return can_use_int32_nhwc( + nbatch, channels, height, width, + pooled_height, pooled_width, + channels * hw, // in_stride_n + hw, // in_stride_c + width, // in_stride_h + 1 // in_stride_w + ); +} + +// kernels borrowed from Caffe +template +__global__ void max_pool_forward_nchw( + const index_t nthreads, + const scalar_t* bottom_data, + const int64_t channels, + const int64_t height, + const int64_t width, + const int pooled_height, + const int pooled_width, + const int kernel_h, const int kernel_w, + const int stride_h, const int stride_w, + const int pad_h, const int pad_w, + const int dilation_h, const int dilation_w, + scalar_t* top_data, + int64_t* top_mask) { + CUDA_KERNEL_LOOP_TYPE(index, nthreads, index_t) { + index_t pw = index % pooled_width; + index_t ph = (index / pooled_width) % pooled_height; + index_t c = (index / pooled_width / pooled_height) % channels; + index_t n = index / pooled_width / pooled_height / channels; + index_t hstart = ph * stride_h - pad_h; + index_t wstart = pw * stride_w - pad_w; + index_t hend = min(hstart + (kernel_h - 1) * dilation_h + 1, height); + index_t wend = min(wstart + (kernel_w - 1) * dilation_w + 1, width); + while(hstart < 0) + hstart += dilation_h; + while(wstart < 0) + wstart += dilation_w; + scalar_t maxval = at::numeric_limits::lower_bound(); // -Infinity + index_t maxidx = hstart * width + wstart; + const scalar_t* btm_data = bottom_data + (n * channels + c) * height * width; + for (int h = hstart; h < hend; h += dilation_h) { + for (int w = wstart; w < wend; w += dilation_w) { + scalar_t val = btm_data[h * width + w]; + if ((val > maxval) || at::_isnan(val)) { + maxidx = h * width + w; + maxval = val; + } + } + } + top_data[index] = maxval; + top_mask[index] = maxidx; + } +} + +template +C10_LAUNCH_BOUNDS_1(CUDA_MAX_THREADS) +__global__ void max_pool_forward_nhwc( + const scalar_t* bottom_data, + const int nbatch, + const index_t channels, const index_t height, const index_t width, + const index_t pooled_height, const index_t pooled_width, + const int kernel_h, const int kernel_w, const int stride_h, + const int stride_w, const int pad_h, const int pad_w, + const int dilation_h, const int dilation_w, + const index_t in_stride_n, const index_t in_stride_c, + const index_t in_stride_h, const index_t in_stride_w, + const int kernel_stride_C, const int kernel_size_C, + scalar_t* top_data, int64_t* top_mask) { + + extern __shared__ unsigned char smem_raw[]; + index_t *out_mask_cached = reinterpret_cast(smem_raw); + scalar_t *out_cached = reinterpret_cast( + out_mask_cached + kernel_size_C*blockDim.x*blockDim.y*blockDim.z); + + // flattening cta for pre-computation & smem initialization; + int thread_id = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * threadIdx.z); + int block_size = blockDim.x * blockDim.y * blockDim.z; + + // use shared memory to store temporary output value. This is simply to + // reduce register usage. + for (int i = thread_id; i < kernel_size_C*blockDim.x*blockDim.y*blockDim.z; i+= block_size) { + out_cached[i] = at::numeric_limits::lower_bound(); + out_mask_cached[i] = 0; + } + + __syncthreads(); + + int batch_id = blockIdx.x % nbatch; + int channel_id = blockIdx.x / nbatch; + int channel_offset = threadIdx.x + channel_id * blockDim.x; + + top_data = top_data + static_cast(batch_id) * (pooled_height * pooled_width * channels); + top_mask = top_mask + static_cast(batch_id) * (pooled_height * pooled_width * channels); + bottom_data = bottom_data + static_cast(batch_id) * in_stride_n; + + out_cached += (threadIdx.z * blockDim.y + threadIdx.y) * kernel_size_C*blockDim.x; + out_mask_cached += (threadIdx.z * blockDim.y + threadIdx.y) * kernel_size_C*blockDim.x; + + int oH = (static_cast(pooled_height) + gridDim.z - 1) / gridDim.z; + int oW = (static_cast(pooled_width) + gridDim.y - 1) / gridDim.y; + int ostartH = threadIdx.z + blockIdx.z*oH; + int oendH = ::min(ostartH+oH, static_cast(pooled_height)); + int ostartW = threadIdx.y + blockIdx.y*oW; + int oendW = ::min(ostartW+oW, static_cast(pooled_width)); + + for (int oh = ostartH; oh < oendH; oh+=blockDim.z) { + index_t hstart = static_cast(oh) * stride_h - pad_h; + index_t hend = std::min(hstart + static_cast((kernel_h - 1) * dilation_h + 1), height); + for (int ow = ostartW; ow < oendW; ow+=blockDim.y) { + index_t wstart = static_cast(ow) * stride_w - pad_w; + index_t wend = std::min(wstart + static_cast((kernel_w - 1) * dilation_w + 1), width); + while(hstart < 0) + hstart += dilation_h; + while(wstart < 0) + wstart += dilation_w; + +#if defined (USE_ROCM) +// Max h,w and c for using prefetch path +#define MAXh 3 +#define MAXw 3 +#define MAXc 1 + // Prefetch if conditions met... + if (kernel_h<=MAXh && + kernel_w<=MAXw && + channels<=MAXc*(blockDim.x*kernel_stride_C)) { + scalar_t val [MAXh][MAXw][MAXc] = {}; + for (int ih = 0; ih < MAXh; ih++) { + int ih_ = ih*dilation_h+hstart; + for (int iw = 0; iw < MAXw; iw++) { + int iw_ = iw*dilation_w+wstart; + const scalar_t *ptr_input = bottom_data + ih_ * in_stride_h + iw_ * in_stride_w; + for(int c = 0; c < MAXc; c++) { + int c_ = c*blockDim.x*kernel_stride_C+channel_offset; + if (ih_>=hend || iw_>=wend || c_>=channels) continue; + val[ih][iw][c] = ptr_input[c_*in_stride_c]; + } + } + } + for (int ih = 0; ih < MAXh; ih++) { + int ih_ = ih*dilation_h+hstart; + for (int iw = 0; iw < MAXw; iw++) { + int iw_ = iw*dilation_w+wstart; + int cached_index = threadIdx.x; + for(int c = 0; c < MAXc; c++) { + int c_ = c*blockDim.x*kernel_stride_C+channel_offset; + if (ih_>=hend || iw_>=wend || c_>=channels) continue; + if ((val[ih][iw][c] > out_cached[cached_index]) || at::_isnan(val[ih][iw][c])) { + out_cached[cached_index] = val[ih][iw][c]; + out_mask_cached[cached_index] = ih_ * width + iw_; + } + cached_index += blockDim.x; + } + } + } + } + // Else do it Non-Prefetch... + else +#endif + for (index_t ih = hstart; ih < hend; ih += dilation_h) { + for (index_t iw = wstart; iw < wend; iw += dilation_w) { + int cached_index = threadIdx.x; + const scalar_t *ptr_input = bottom_data + ih * in_stride_h + iw * in_stride_w; + for (index_t c = channel_offset; c < channels; c += static_cast(blockDim.x) * kernel_stride_C) { + scalar_t val = ptr_input[c * in_stride_c]; + if ((val > out_cached[cached_index]) || at::_isnan(val)) { + out_cached[cached_index] = val; + out_mask_cached[cached_index] = ih * width + iw; + } + cached_index += blockDim.x; + } + } + } + + scalar_t *ptr_output_data = top_data + (static_cast(oh) * pooled_width + ow) * channels; + int64_t *ptr_output_mask = top_mask + (static_cast(oh) * pooled_width + ow) * channels; + + int cached_index = threadIdx.x; + for (index_t c = channel_offset; c < channels; c += static_cast(blockDim.x) * kernel_stride_C) { + ptr_output_data[c] = out_cached[cached_index]; + ptr_output_mask[c] = static_cast(out_mask_cached[cached_index]); + out_cached[cached_index] = at::numeric_limits::lower_bound(); + out_mask_cached[cached_index] = index_t(0); + cached_index += blockDim.x; + } + } + } +} + + +static constexpr int BLOCK_THREADS = 256; + +template +#if defined (USE_ROCM) +C10_LAUNCH_BOUNDS_2(BLOCK_THREADS, 4) +#else +C10_LAUNCH_BOUNDS_2(BLOCK_THREADS, 8) +#endif +__global__ void max_pool_backward_nchw( + const scalar_t* top_diff, + const int64_t* top_mask, + const index_t num, + const index_t channels, + const index_t height, + const index_t width, + const index_t pooled_height, + const index_t pooled_width, + const int kernel_h, const int kernel_w, + const int stride_h, const int stride_w, + const int pad_h, const int pad_w, + const int dilation_h, const int dilation_w, + scalar_t* bottom_diff) { + CUDA_KERNEL_LOOP_TYPE(index, height*width, index_t) { + index_t h = index / width; + index_t w = index - h * width; + index_t phstart = p_start(h, pad_h, kernel_h, dilation_h, stride_h); + index_t phend = p_end(h, pad_h, pooled_height, stride_h); + index_t pwstart = p_start(w, pad_w, kernel_w, dilation_w, stride_w); + index_t pwend = p_end(w, pad_w, pooled_width, stride_w); + for (index_t n = blockIdx.y; n < num; n += gridDim.y) { + for (index_t c = blockIdx.z; c < channels; c += gridDim.z) { + accscalar_t gradient = accscalar_t(0); + index_t offset = (n * channels + c) * pooled_height * pooled_width; + for (index_t ph = phstart; ph < phend; ++ph) { + for (index_t pw = pwstart; pw < pwend; ++pw) { + if (top_mask[ph * pooled_width + pw + offset] == h * width + w) { + gradient += static_cast(top_diff[ph * pooled_width + pw + offset]); + } + } + } + bottom_diff[(n*channels+c)*height*width+index] = static_cast(gradient); + } + } + } +} + +template +C10_LAUNCH_BOUNDS_1(CUDA_MAX_THREADS) +__global__ void max_pool_backward_nhwc(const scalar_t* top_diff, + const int64_t* top_mask, const int nbatch, const int64_t channels, + const int64_t height, const int64_t width, const int pooled_height, + const int pooled_width, const int kernel_h, const int kernel_w, + const int stride_h, const int stride_w, const int pad_h, const int pad_w, + const int dilation_h, const int dilation_w, + const int out_stride_c, const int out_stride_h, const int out_stride_w, + const int kernel_stride_C, const int kernel_size_C, + scalar_t* bottom_diff) { + extern __shared__ int smem[]; + accscalar_t *out_cached = reinterpret_cast(smem); + + int thread_id = threadIdx.x + blockDim.x * (threadIdx.y + blockDim.y * threadIdx.z); + int block_size = blockDim.x * blockDim.y * blockDim.z; + + int batch_id = blockIdx.x % nbatch; + int channel_id = blockIdx.x / nbatch; + int channel_offset = threadIdx.x + channel_id * blockDim.x; + + for (int i = thread_id; i < kernel_size_C*blockDim.x*blockDim.y*blockDim.z; i+= block_size) { + out_cached[i] = accscalar_t(0.0); + } + + __syncthreads(); + + out_cached = &out_cached[(threadIdx.z * blockDim.y + threadIdx.y) * kernel_size_C*blockDim.x]; + + bottom_diff = bottom_diff + batch_id * height * width * channels; + top_mask = top_mask + batch_id * pooled_height * pooled_width * channels; + top_diff = top_diff + batch_id * pooled_height * pooled_width * channels; + + int iH = (height + gridDim.z-1) / gridDim.z; + int iW = (width + gridDim.y-1) / gridDim.y; + int istartH = threadIdx.z + blockIdx.z*iH; + int iendH = ::min(static_cast(istartH)+iH, height); + int istartW = threadIdx.y + blockIdx.y*iW; + int iendW = ::min(static_cast(istartW)+iW, width); + + for (int ih = istartH; ih < iendH; ih+=blockDim.z) { + int phstart = p_start(ih, pad_h, kernel_h, dilation_h, stride_h); + int phend = p_end(ih, pad_h, pooled_height, stride_h); + for (int iw = istartW; iw < iendW; iw+=blockDim.y) { + int pwstart = p_start(iw, pad_w, kernel_w, dilation_w, stride_w); + int pwend = p_end(iw, pad_w, pooled_width, stride_w); + int index_shift = ih * width + iw; + if ((phstart + 1 != phend) || (pwstart + 1 != pwend)) { + +#if defined (USE_ROCM) +#define _MAXh 2 +#define _MAXw 2 + if (phend-phstart<=_MAXh && pwend-pwstart<=_MAXw) { + int msk[_MAXh][_MAXw]; + scalar_t tpd[_MAXh][_MAXw]; + int cached_index = threadIdx.x; +#pragma unroll + for (int c = channel_offset; c < channels; c += blockDim.x*kernel_stride_C) { +#pragma unroll + for(int oh = 0; oh < _MAXh; ++oh) { +#pragma unroll + for(int ow = 0; ow < _MAXw; ++ow) { + int oh_ = oh+phstart; + int ow_ = ow+pwstart; + const int64_t* ptr_top_mask = top_mask + oh_ * out_stride_h + ow_ * out_stride_w; + if (oh_ >= phend || ow_ >= pwend) { + msk[oh][ow] = ~index_shift; + } else { + msk[oh][ow] = ptr_top_mask[c*out_stride_c]; + tpd[oh][ow] = top_diff[oh_ * out_stride_h + ow_ * out_stride_w + c*out_stride_c]; + } + } + } + + accscalar_t acm = 0; +#pragma unroll + for(int oh = 0; oh < _MAXh; ++oh) { +#pragma unroll + for(int ow = 0; ow < _MAXw; ++ow) { + if (msk[oh][ow] == index_shift) { + acm += static_cast(tpd[oh][ow]); + } + } + } + out_cached[cached_index] += acm; + cached_index += blockDim.x; + } + } + else +#undef _MAXh +#undef _MAXw +#endif + + for(int oh = phstart; oh < phend; ++oh) { + for(int ow = pwstart; ow < pwend; ++ow) { + int cached_index = threadIdx.x; + const int64_t* ptr_top_mask = top_mask + oh * out_stride_h + ow * out_stride_w; + for (int c = channel_offset; c < channels; c += blockDim.x*kernel_stride_C) { + if (ptr_top_mask[c*out_stride_c] == index_shift) { + out_cached[cached_index] += + static_cast(top_diff[oh * out_stride_h + ow * out_stride_w + c*out_stride_c]); + } + cached_index += blockDim.x; + } + } + } + scalar_t *ptr_bottom_diff = bottom_diff + index_shift * channels; + int cached_index = threadIdx.x; + for (int c = channel_offset; c < channels; c += blockDim.x*kernel_stride_C) { + ptr_bottom_diff[c] = static_cast(out_cached[cached_index]); + out_cached[cached_index] = accscalar_t(0.0); + cached_index += blockDim.x; + } + } else { + const int64_t* ptr_top_mask = top_mask + phstart * out_stride_h + pwstart * out_stride_w; + scalar_t *ptr_bottom_diff = bottom_diff + index_shift * channels; + int cached_index = threadIdx.x; + for (int c = channel_offset; c < channels; c += blockDim.x*kernel_stride_C) { + if (ptr_top_mask[c*out_stride_c] == index_shift) { + ptr_bottom_diff[c] = + static_cast(top_diff[phstart * out_stride_h + pwstart * out_stride_w + c*out_stride_c]); + } + cached_index += blockDim.x; + } + } + } + } +} + +} // namespace + +TORCH_IMPL_FUNC(max_pool2d_with_indices_out_cuda) +(const Tensor& input_, +IntArrayRef kernel_size, +IntArrayRef stride, +IntArrayRef padding, +IntArrayRef dilation, +bool ceil_mode, +const Tensor& output, +const Tensor& indices) { + + TensorArg output_arg{ output, "output", 1 }; + TensorArg indices_arg{ indices, "indices", 2 }; + TensorArg input_arg{ input_, "input_", 3 }; + + checkAllSameGPU(__func__, {output_arg, indices_arg, input_arg}); + if (output.numel() == 0) { + return; + } + + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + const int dilationH = c10::checked_convert(dilation[0], "int"); + const int dilationW = dilation.size() == 1 ? dilationH : c10::checked_convert(dilation[1], "int"); + + const auto memory_format = input_.suggest_memory_format(); + + const int64_t nbatch = input_.ndimension() == 4 ? input_.size(-4) : 1; + const int64_t nInputPlane = input_.size(-3); + const int64_t inputHeight = input_.size(-2); + const int64_t inputWidth = input_.size(-1); + + const int64_t outputHeight = output.size(-2); + const int64_t outputWidth = output.size(-1); + + Tensor input = input_.contiguous(memory_format); + + const int64_t in_stride_n = input_.ndimension() == 4 ? input.stride(-4) : 0; + const int64_t in_stride_c = input.stride(-3); + const int64_t in_stride_h = input.stride(-2); + const int64_t in_stride_w = input.stride(-1); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "max_pool2d_with_indices_out_cuda_frame", + [&] { + using accscalar_t = acc_type; + + scalar_t *output_data = output.mutable_data_ptr(); + const scalar_t *input_data = input.const_data_ptr(); + int64_t *indices_data = indices.mutable_data_ptr(); + + switch (memory_format) { + case MemoryFormat::ChannelsLast: { + const int max_threads = std::min( + at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, CUDA_MAX_THREADS); + int* maxThreadsDim = at::cuda::getCurrentDeviceProperties()->maxThreadsDim; + int block_x = std::min( + {maxThreadsDim[0], lastPow2(nInputPlane), at::cuda::warp_size()}); + int block_y = std::min( + {maxThreadsDim[1], lastPow2(outputWidth), max_threads / block_x}); + int block_z = std::min( + {maxThreadsDim[2], lastPow2(outputHeight), max_threads / block_x / block_y}); + block_x = std::min( + {maxThreadsDim[0], lastPow2(nInputPlane), max_threads / block_y / block_z}); + const dim3 block(block_x, block_y, block_z); + + bool use_int32 = can_use_int32_nhwc( + nbatch, nInputPlane, inputHeight, inputWidth, + outputHeight, outputWidth, + in_stride_n, in_stride_c, in_stride_h, in_stride_w); + + int kernel_stride_C = ceil_div( + c10::checked_convert(nInputPlane, "int"), block_x * 4); + int kernel_size_C = ceil_div( + c10::checked_convert(nInputPlane, "int"), block_x * kernel_stride_C); + + int grid_x = nbatch*kernel_stride_C; + int grid_y = std::min( + at::cuda::getCurrentDeviceProperties()->maxGridSize[1], + ceil_div(c10::checked_convert(outputWidth, "int"), block_y*BLOCK_STRIDE_FWD)); + int grid_z = std::min( + at::cuda::getCurrentDeviceProperties()->maxGridSize[2], + ceil_div(c10::checked_convert(outputHeight, "int"), block_z*BLOCK_STRIDE_FWD)); + const dim3 grid(grid_x, grid_y, grid_z); + + size_t shmem_size; + size_t mask_elems = static_cast(kernel_size_C) * block_x * block_y * block_z; + + if (use_int32) { + shmem_size = mask_elems * (sizeof(int32_t) + sizeof(scalar_t)); + TORCH_CHECK(shmem_size <= at::cuda::getCurrentDeviceProperties()->sharedMemPerBlock, + "shared memory too small"); + max_pool_forward_nhwc + <<>>( + input_data, static_cast(nbatch), + static_cast(nInputPlane), + static_cast(inputHeight), + static_cast(inputWidth), + static_cast(outputHeight), + static_cast(outputWidth), + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + static_cast(in_stride_n), + static_cast(in_stride_c), + static_cast(in_stride_h), + static_cast(in_stride_w), + kernel_stride_C, kernel_size_C, + output_data, indices_data); + } else { + shmem_size = mask_elems * (sizeof(int64_t) + sizeof(scalar_t)); + TORCH_CHECK(shmem_size <= at::cuda::getCurrentDeviceProperties()->sharedMemPerBlock, + "shared memory too small"); + max_pool_forward_nhwc + <<>>( + input_data, static_cast(nbatch), + nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + in_stride_n, in_stride_c, in_stride_h, in_stride_w, + kernel_stride_C, kernel_size_C, + output_data, indices_data); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + case MemoryFormat::Contiguous: { + const int threads = std::min( + at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, + BLOCK_THREADS); + const int64_t nthreads = output.numel(); + bool use_int32 = can_use_int32_nchw( + nbatch, nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth); + const int maxGridX = at::cuda::getCurrentDeviceProperties()->maxGridSize[0]; + const int blocks = static_cast(std::min( + ceil_div(nthreads, static_cast(threads)), + static_cast(maxGridX))); + auto stream = at::cuda::getCurrentCUDAStream(); + if (use_int32) { + max_pool_forward_nchw + <<>>( + static_cast(nthreads), + input_data, + static_cast(nInputPlane), + static_cast(inputHeight), + static_cast(inputWidth), + static_cast(outputHeight), + static_cast(outputWidth), + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + output_data, indices_data); + } else { + max_pool_forward_nchw + <<>>( + nthreads, + input_data, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + output_data, indices_data); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + default: TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + } + ); +} + +TORCH_IMPL_FUNC(max_pool2d_with_indices_backward_out_cuda) +(const Tensor& gradOutput_, +const Tensor& input_, +IntArrayRef kernel_size, +IntArrayRef stride, +IntArrayRef padding, +IntArrayRef dilation, +bool ceil_mode, +const Tensor& indices_, +const Tensor& gradInput) { + + TensorArg gradInput_arg{ gradInput, "gradInput", 1 }; + TensorArg gradOutput_arg{ gradOutput_, "gradOutput_", 2 }; + TensorArg input_arg{ input_, "input_", 3 }; + TensorArg indices_arg{ indices_, "indices", 4 }; + + checkAllSameGPU(__func__, + {gradInput_arg, gradOutput_arg, input_arg, indices_arg}); + if (gradOutput_.numel() == 0) { + return; + } + + const int kH = c10::checked_convert(kernel_size[0], "int"); + const int kW = kernel_size.size() == 1 ? kH : c10::checked_convert(kernel_size[1], "int"); + + const int dH = stride.empty() ? kH : c10::checked_convert(stride[0], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dH : c10::checked_convert(stride[1], "int"); + + const int padH = c10::checked_convert(padding[0], "int"); + const int padW = padding.size() == 1 ? padH : c10::checked_convert(padding[1], "int"); + + const int dilationH = c10::checked_convert(dilation[0], "int"); + const int dilationW = dilation.size() == 1 ? dilationH : c10::checked_convert(dilation[1], "int"); + + const auto memory_format = input_.suggest_memory_format(); + + const Tensor input = input_.contiguous(memory_format); + + const int64_t nbatch = input.ndimension() == 4 ? input.size(-4) : 1; + const int64_t nInputPlane = input.size(-3); + const int64_t inputHeight = input.size(-2); + const int64_t inputWidth = input.size(-1); + + const Tensor gradOutput = gradOutput_.contiguous(memory_format); + + const int64_t outputHeight = gradOutput.size(-2); + const int64_t outputWidth = gradOutput.size(-1); + + const int64_t out_stride_c = gradOutput.stride(-3); + const int64_t out_stride_h = gradOutput.stride(-2); + const int64_t out_stride_w = gradOutput.stride(-1); + + const Tensor indices = indices_.contiguous(memory_format); + + gradInput.zero_(); + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "max_pool2d_with_indices_out_cuda_frame", + [&] { + using accscalar_t = acc_type; + + const scalar_t *gradOutput_data = gradOutput.const_data_ptr(); + scalar_t *gradInput_data = gradInput.mutable_data_ptr(); + const int64_t *indices_data = indices.const_data_ptr(); + + switch (memory_format) { + case MemoryFormat::ChannelsLast: { + const int max_threads = std::min(at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, CUDA_MAX_THREADS); + int* maxThreadsDim = at::cuda::getCurrentDeviceProperties()->maxThreadsDim; + int block_x = std::min( + {maxThreadsDim[0], lastPow2(nInputPlane), at::cuda::warp_size()}); + int block_y = std::min( + {maxThreadsDim[1], lastPow2(inputWidth), max_threads / block_x}); + int block_z = std::min( + {maxThreadsDim[2], lastPow2(inputHeight), max_threads / block_x / block_y}); + block_x = std::min( + {maxThreadsDim[0], lastPow2(nInputPlane), max_threads / block_y / block_z}); + const dim3 block(block_x, block_y, block_z); + + int kernel_stride_C = ceil_div( + c10::checked_convert(nInputPlane, "int"), block_x * 4); + int kernel_size_C = ceil_div( + c10::checked_convert(nInputPlane, "int"), block_x * kernel_stride_C); + + int grid_x = nbatch*kernel_stride_C; + int grid_y = std::min( + at::cuda::getCurrentDeviceProperties()->maxGridSize[1], + ceil_div(c10::checked_convert(inputWidth, "int"), block_y*BLOCK_STRIDE_BWD)); + int grid_z = std::min( + at::cuda::getCurrentDeviceProperties()->maxGridSize[2], + ceil_div(c10::checked_convert(inputHeight, "int"), block_z*BLOCK_STRIDE_BWD)); + const dim3 grid(grid_x, grid_y, grid_z); + + size_t shmem_size = (kernel_size_C * block_x*block_y*block_z) * sizeof(accscalar_t); + AT_ASSERT(shmem_size <= at::cuda::getCurrentDeviceProperties()->sharedMemPerBlock); + + // The backward kernel is launched on input instead output. + // If it is launched on output layer, atomic_add would not provide much benefit on FP16. + // Please check comments at https://github.com/pytorch/pytorch/pull/34519. + max_pool_backward_nhwc + <<>>( + gradOutput_data, + indices_data, + nbatch, + nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth, + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + out_stride_c, out_stride_h, out_stride_w, + kernel_stride_C, kernel_size_C, + gradInput_data); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + case MemoryFormat::Contiguous: { + const int threads = std::min( + at::cuda::getCurrentDeviceProperties()->maxThreadsPerBlock, + BLOCK_THREADS); + const int imgcount = inputWidth * inputHeight; + const int maxGridX = at::cuda::getCurrentDeviceProperties()->maxGridSize[0]; + const int maxGridY = at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; + const int maxGridZ = at::cuda::getCurrentDeviceProperties()->maxGridSize[2]; + const int blocks_x = std::min(ceil_div(imgcount, threads), maxGridX); + dim3 grid(blocks_x, static_cast(std::min(nbatch, maxGridY)), static_cast(std::min(nInputPlane, maxGridZ))); + bool use_int32 = can_use_int32_nchw( + nbatch, nInputPlane, inputHeight, inputWidth, outputHeight, outputWidth); + auto stream = at::cuda::getCurrentCUDAStream(); + if (use_int32) { + max_pool_backward_nchw + <<>>( + gradOutput_data, + indices_data, + static_cast(nbatch), + static_cast(nInputPlane), + static_cast(inputHeight), + static_cast(inputWidth), + static_cast(outputHeight), + static_cast(outputWidth), + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + gradInput_data); + } else { + max_pool_backward_nchw + <<>>( + gradOutput_data, + indices_data, + nbatch, + nInputPlane, + inputHeight, + inputWidth, + outputHeight, + outputWidth, + kH, kW, dH, dW, padH, padW, dilationH, dilationW, + gradInput_data); + } + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + } + default: TORCH_CHECK(false, "Unsupported memory format. Supports only ChannelsLast, Contiguous"); + } + } + ); +} + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DilatedMaxPool3d.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DilatedMaxPool3d.cu new file mode 100644 index 0000000000000000000000000000000000000000..b2bde3b9f93299291da43eafa14cb02be5babc9a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DilatedMaxPool3d.cu @@ -0,0 +1,646 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#endif + +namespace at::native { +namespace { + +__device__ inline int min(int a, int b) { + return a <= b ? a : b; +} + +template +__global__ static void max_pool3d_with_indices_single_out_frame( + const scalar_t* inputData, + scalar_t* outputData, + int64_t* indicesData, + int features, + int itime, int iheight, int iwidth, + int obatch, int otime, int oheight, int owidth, + int kT, int kH, int kW, + int dT, int dH, int dW, + int pT, int pH, int pW, + int dilationT, int dilationH, int dilationW, + int offsetZ, + bool channels_last) +{ + int64_t oColumn = blockIdx.x * blockDim.x + threadIdx.x; + int64_t oRow = blockIdx.y * blockDim.y + threadIdx.y; + int64_t oFrame = 0; + // used only for channels-first indexing + int64_t slice = 0; + // used only for channels-last indexing + int batch = 0; + int channel = 0; + if (!channels_last) { + // indexing order: batch, channel, time + oFrame = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) % otime; // output frame/time + slice = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) / otime; // output slice/feature + } else { + // indexing order: batch, time, channel + channel = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) % features; // output feature (channel) + slice = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) / features; // output slice (batch + time) + batch = slice / otime; + oFrame = slice % otime; + } + + // For int64_t data type, see https://github.com/pytorch/pytorch/issues/52822 + if (oRow < oheight && oColumn < owidth && oFrame < otime && channel < features && batch < obatch) + { + int tStart = oFrame * dT - pT; + int hStart = oRow * dH - pH; + int wStart = oColumn * dW - pW; + int tEnd = min(tStart + (kT - 1) * dilationT + 1, itime); + int hEnd = min(hStart + (kH - 1) * dilationH + 1, iheight); + int wEnd = min(wStart + (kW - 1) * dilationW + 1, iwidth); + + while(tStart < 0) + tStart += dilationT; + while(hStart < 0) + hStart += dilationH; + while(wStart < 0) + wStart += dilationW; + + // maxIndex remains in "channels-first"/contiguous + int64_t maxIndex = tStart * iheight * iwidth + hStart * iwidth + wStart; + + if (!channels_last) { + inputData += slice * itime * iheight * iwidth; + } else { + inputData += ((int64_t) batch * itime * iheight * iwidth * features) + channel; + } + + scalar_t max = at::numeric_limits::lower_bound(); // -Infinity + + for (int t = tStart; t < tEnd; t += dilationT) + { + for (int h = hStart; h < hEnd; h += dilationH) + { + for (int w = wStart; w < wEnd; w += dilationW) + { + scalar_t val; + int index = t * iheight * iwidth + h * iwidth + w; + if (!channels_last) { + val = inputData[index]; + } else { + int64_t index_channels_last = index*features; + val = inputData[index_channels_last]; + } + + if ((max < val) || at::_isnan(val)) + { + max = val; + maxIndex = index; + } + } + } + } + + int64_t out_index; + if (!channels_last) { + out_index = slice*otime*oheight*owidth + oFrame*oheight*owidth + oRow*owidth + oColumn; + } else { + out_index = ((int64_t) batch*otime*oheight*owidth + oFrame*oheight*owidth + oRow*owidth + oColumn)*features + channel; + } + outputData[out_index] = max; + indicesData[out_index] = maxIndex; + } +} + +template +void max_pool3d_with_indices_out_frame( + const scalar_t* input_data, + const Tensor& output, + const Tensor& indices, + int features, + int64_t totalZ, + int itime, int iheight, int iwidth, + int obatch, int otime, int oheight, int owidth, + int kT, int kH, int kW, + int dT, int dH, int dW, + int pT, int pH, int pW, + int dilationT, int dilationH, int dilationW, + bool channels_last) +{ + int offsetZ = 0; + int threadX = 32; + int threadY = 8; + int threadZ = 1; + int stepZ = 65535; + if (channels_last) { + threadX = 2; + threadY = 4; + threadZ = 64; + } + dim3 block(threadX, threadY, threadZ); + + while (totalZ > 0) { + dim3 grid(ceil_div(owidth, static_cast(block.x)), + ceil_div(oheight, static_cast(block.y)), + totalZ > stepZ*threadZ ? stepZ : ceil_div(totalZ, static_cast(threadZ))); + + max_pool3d_with_indices_single_out_frame + <<>>( + input_data, + output.mutable_data_ptr(), + indices.mutable_data_ptr(), + features, + itime, iheight, iwidth, + obatch, otime, oheight, owidth, + kT, kH, kW, + dT, dH, dW, + pT, pH, pW, + dilationT, dilationH, dilationW, + offsetZ, channels_last); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + totalZ -= threadZ*stepZ; + offsetZ += threadZ*stepZ; + } +} + +#undef UPDATE_OUTPUT_KERNEL_WIDTH + +template +__global__ static void max_pool3d_with_indices_backward_single_out_frame( + scalar_t *gradInputData, + const scalar_t *gradOutputData, + const int64_t *indicesData, + int features, + int itime, int iheight, int iwidth, + int obatch, int otime, int oheight, int owidth, + int offsetZ, + bool channels_last) +{ + int64_t oColumn = blockIdx.x * blockDim.x + threadIdx.x; + int64_t oRow = blockIdx.y * blockDim.y + threadIdx.y; + + int64_t oFrame = 0; + // used only for channels-first indexing + int64_t slice = 0; + // used only for channels-last indexing + int batch = 0; + int channel = 0; + if (!channels_last) { + // indexing order: batch, channel, time + oFrame = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) % otime; // output frame/time + slice = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) / otime; // output slice/feature + } else { + // indexing order: batch, time, channel + channel = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) % features; // output feature (channel) + slice = (blockIdx.z * blockDim.z + threadIdx.z + offsetZ) / features; // output slice (batch + time) + batch = slice / otime; + oFrame = slice % otime; + } + + if (oRow < oheight && oColumn < owidth && oFrame < otime && batch < obatch && channel < features) + { + int64_t out_index; + if (!channels_last) { + out_index = slice*otime*oheight*owidth + oFrame*oheight*owidth + oRow*owidth + oColumn; + } else { + out_index = ((int64_t) batch*otime*oheight*owidth + oFrame*oheight*owidth + oRow*owidth + oColumn)*features + channel; + } + int64_t maxIndex = indicesData[out_index]; + if (maxIndex != -1) { + if (!channels_last) { + gpuAtomicAddNoReturn(&gradInputData[slice * itime * iheight * iwidth + maxIndex], + gradOutputData[out_index]); + } else { + gpuAtomicAddNoReturn(&gradInputData[((int64_t) batch * itime * iheight * iwidth + maxIndex) * features + channel], + gradOutputData[out_index]); + } + } + } +} + +template +void max_pool3d_with_indices_backward_out_frame( + scalar_t *gradInputData, + const Tensor& gradOutput, + const Tensor& indices, + int features, + int64_t totalZ, + int itime, int iheight, int iwidth, + int obatch, int otime, int oheight, int owidth, + bool channels_last) +{ + int offsetZ = 0; + int threadX = 32; + int threadY = 8; + int threadZ = 1; + int stepZ = 65535; + if (channels_last) { + threadX = 2; + threadY = 4; + threadZ = 64; + } + dim3 block(threadX, threadY, threadZ); + + while (totalZ > 0) { + dim3 grid(ceil_div(owidth, static_cast(block.x)), + ceil_div(oheight, static_cast(block.y)), + totalZ > stepZ*threadZ ? stepZ : ceil_div(totalZ, static_cast(block.z))); + + max_pool3d_with_indices_backward_single_out_frame + <<>>( + gradInputData, + gradOutput.const_data_ptr(), + indices.const_data_ptr(), + features, + itime, iheight, iwidth, + obatch, otime, oheight, owidth, + offsetZ, + channels_last); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + totalZ -= threadZ*stepZ; + offsetZ += threadZ*stepZ; + } +} + +void max_pool3d_with_indices_out_cuda_template( + Tensor& output, + Tensor& indices, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) +{ + TensorArg output_arg{ output, "output", 1 }; + TensorArg indices_arg{ indices, "indices", 2 }; + TensorArg input_arg{ input, "input", 3 }; + + checkAllSameGPU(__func__, + {output_arg, indices_arg, input_arg}); + + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, + "max_pool3d: kernel_size must either be a single int, or a tuple of three ints") + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, + "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints") + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 3, + "max_pool3d: padding must either be a single int, or a tuple of three ints"); + const int pT = c10::checked_convert(padding[0], "int"); + const int pH = padding.size() == 1 ? pT : c10::checked_convert(padding[1], "int"); + const int pW = padding.size() == 1 ? pT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK(dilation.size() == 1 || dilation.size() == 3, + "max_pool3d: dilation must be either a single int, or a tuple of three ints"); + const int dilationT = c10::checked_convert(dilation[0], "int"); + const int dilationH = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[1], "int"); + const int dilationW = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[2], "int"); + + const int64_t nbatch = input.ndimension() == 5 ? input.size(-5) : 1; + const int64_t nslices = input.size(-4); + const int64_t itime = input.size(-3); + const int64_t iheight = input.size(-2); + const int64_t iwidth = input.size(-1); + + const int64_t otime = pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode); + const int64_t oheight = pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode); + const int64_t owidth = pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode); + + pool3d_shape_check( + input, + nslices, + kT, kH, kW, + dT, dH, dW, + pT, pH, pW, + dilationT, dilationH, dilationW, + itime, iheight, iwidth, + otime, oheight, owidth, + "max_pool3d_with_indices_out_cuda_template()"); + + bool channels_last = input.ndimension() == 5 && input.suggest_memory_format() == at::MemoryFormat::ChannelsLast3d; + Tensor _input = input; + if (input.ndimension() == 4) { + Tensor input_channels_last_check = input.unsqueeze(0); + // work around buggy behavior of suggest_memory_format here where + // suggested format of unsqueezed tensor is contiguous while it is + // really only contiguous in ChannelsLast3d + channels_last = (!input_channels_last_check.is_contiguous()) && + input_channels_last_check.is_contiguous(at::MemoryFormat::ChannelsLast3d); + if (!channels_last) { + output.resize_({ nslices, otime, oheight, owidth}); + indices.resize_({nslices, otime, oheight, owidth}); + } else { + _input = input_channels_last_check; + output.resize_({1, nslices, otime, oheight, owidth}, at::MemoryFormat::ChannelsLast3d); + indices.resize_({1, nslices, otime, oheight, owidth}, at::MemoryFormat::ChannelsLast3d); + output = output.squeeze(0); + indices = indices.squeeze(0); + } + } else { + if (!channels_last) { + output.resize_({nbatch, nslices, otime, oheight, owidth}); + indices.resize_({nbatch, nslices, otime, oheight, owidth}); + } else { + output.resize_({nbatch, nslices, otime, oheight, owidth}, at::MemoryFormat::ChannelsLast3d); + indices.resize_({nbatch, nslices, otime, oheight, owidth}, at::MemoryFormat::ChannelsLast3d); + } + } + + if (input.numel() == 0) { + return; + } + + Tensor work_input; + Tensor work_output = output; + if (!channels_last) { + work_input = input.contiguous(); + } else { + work_input = _input.contiguous(at::MemoryFormat::ChannelsLast3d); + } + Tensor work_indices = indices; + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, + input.scalar_type(), + "max_pool3d_with_indices_out_frame", + [&]{ + const scalar_t *input_data = work_input.const_data_ptr(); + const int64_t totalZ = otime * nslices * nbatch; + + max_pool3d_with_indices_out_frame( + input_data, work_output, work_indices, + nslices, // features + totalZ, + itime, iheight, iwidth, + nbatch, otime, oheight, owidth, + kT, kH, kW, + dT, dH, dW, + pT, pH, pW, + dilationT, dilationH, dilationW, channels_last); + } + ); +} + +void max_pool3d_with_indices_backward_out_cuda_template( + Tensor& gradInput, + const Tensor& gradOutput, + const Tensor& input, + const Tensor& indices, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) +{ + TensorArg gradInput_arg{ gradInput, "gradInput", 1 }; + TensorArg gradOutput_arg{ gradOutput, "gradOutput", 2 }; + TensorArg input_arg{ input, "input", 3 }; + TensorArg indices_arg{ indices, "indices", 4 }; + + checkAllSameGPU(__func__, + {gradInput_arg, gradOutput_arg, input_arg, indices_arg}); + + // #20866, #22032: Guarantee this for the official C++ API? + TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, + "max_pool3d: kernel_size must either be a single int, or a tuple of three ints") + const int kT = c10::checked_convert(kernel_size[0], "int"); + const int kH = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[1], "int"); + const int kW = kernel_size.size() == 1 ? kT : c10::checked_convert(kernel_size[2], "int"); + + TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, + "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints") + const int dT = stride.empty() ? kT : c10::checked_convert(stride[0], "int"); + const int dH = stride.empty() ? kH : + stride.size() == 1 ? dT : c10::checked_convert(stride[1], "int"); + const int dW = stride.empty() ? kW : + stride.size() == 1 ? dT : c10::checked_convert(stride[2], "int"); + + TORCH_CHECK(padding.size() == 1 || padding.size() == 3, + "max_pool3d: padding must either be a single int, or a tuple of three ints"); + const int pT = c10::checked_convert(padding[0], "int"); + const int pH = padding.size() == 1 ? pT : c10::checked_convert(padding[1], "int"); + const int pW = padding.size() == 1 ? pT : c10::checked_convert(padding[2], "int"); + + TORCH_CHECK(dilation.size() == 1 || dilation.size() == 3, + "max_pool3d: dilation must be either a single int, or a tuple of three ints"); + const int dilationT = c10::checked_convert(dilation[0], "int"); + const int dilationH = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[1], "int"); + const int dilationW = dilation.size() == 1 ? dilationT : c10::checked_convert(dilation[2], "int"); + + TORCH_CHECK((input.ndimension() == 4 || input.ndimension() == 5), + "max_pool2d_with_indices_backward_out_cuda_template(): ", + "Expected 4D or 5D input tensor, but got ", input.sizes()); + + TORCH_CHECK((gradOutput.ndimension() == 4 || gradOutput.ndimension() == 5), + "max_pool2d_with_indices_backward_out_cuda_template(): ", + "Expected 4D or 5D gradOutput tensor, but got ", gradOutput.sizes()); + + // Resize and initialize result tensor. + bool channels_last = input.ndimension() == 5 && input.suggest_memory_format() == at::MemoryFormat::ChannelsLast3d; + Tensor _input = input; + if (input.ndimension() == 4) { + Tensor input_channels_last_check = input.unsqueeze(0); + // work around buggy behavior of suggest_memory_format here where + // suggested format of unsqueezed tensor is contiguous while it is + // really only contiguous in ChannelsLast3d + channels_last = (!input_channels_last_check.is_contiguous()) && + input_channels_last_check.is_contiguous(at::MemoryFormat::ChannelsLast3d); + if (channels_last) { + _input = input_channels_last_check; + } + } + if (!channels_last) { + gradInput.resize_as_(input); + } else { + gradInput.resize_as_(_input, at::MemoryFormat::ChannelsLast3d); + } + gradInput.zero_(); + + const int64_t nbatch = input.ndimension() == 5 ? input.size(-5) : 1; + const int64_t nslices = input.size(-4); + + const int64_t otime = gradOutput.size(-3); + const int64_t oheight = gradOutput.size(-2); + const int64_t owidth = gradOutput.size(-1); + + const int64_t itime = gradInput.size(-3); + const int64_t iheight = gradInput.size(-2); + const int64_t iwidth = gradInput.size(-1); + + max_pool3d_backward_shape_check( + input, + gradOutput, + indices, + nslices, + kT, kH, kW, + dT, dH, dW, + pT, pH, pW, + dilationT, dilationH, dilationW, + itime, iheight, iwidth, + otime, oheight, owidth, + "max_pool3d_with_indices_backward_out_cuda_template()"); + + if (gradOutput.numel() == 0) { + return; + } + + Tensor work_grad_input = gradInput; + Tensor work_grad_output; + Tensor work_indices; + if (!channels_last) { + work_grad_output = gradOutput.contiguous(); + work_indices = indices.contiguous(); + } else { + if (input.ndimension() == 4) { + work_grad_output = gradOutput.unsqueeze(0).contiguous(at::MemoryFormat::ChannelsLast3d); + work_indices = indices.unsqueeze(0).contiguous(at::MemoryFormat::ChannelsLast3d); + } else { + work_grad_output = gradOutput.contiguous(at::MemoryFormat::ChannelsLast3d); + work_indices = indices.contiguous(at::MemoryFormat::ChannelsLast3d); + } + } + + AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, input.scalar_type(), + "max_pool3d_with_indices_backward_out_frame", + [&] { + const int64_t totalZ = otime * nslices * nbatch; + scalar_t *grad_input_data = work_grad_input.mutable_data_ptr(); + + max_pool3d_with_indices_backward_out_frame( + grad_input_data, work_grad_output, work_indices, + nslices, + totalZ, + itime, iheight, iwidth, + nbatch, otime, oheight, owidth, + channels_last); + } + ); +} + +} // namespace + +std::tuple max_pool3d_with_indices_out_cuda(const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode, + Tensor& output, + Tensor& indices) +{ + max_pool3d_with_indices_out_cuda_template( + output, + indices, + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + return std::tuple(output, indices); +} + +std::tuple max_pool3d_with_indices_cuda( + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode) +{ + + Tensor output = at::empty({0}, input.options()); + Tensor indices = at::empty({0}, input.options().dtype(kLong)); + max_pool3d_with_indices_out_cuda_template( + output, + indices, + input, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + + return std::tuple(output, indices); +} + +Tensor& max_pool3d_with_indices_backward_out_cuda(const Tensor& gradOutput, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode, + const Tensor& indices, + Tensor& gradInput) +{ + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("max_pool3d_with_indices_backward_out_cuda"); + max_pool3d_with_indices_backward_out_cuda_template( + gradInput, + gradOutput, + input, + indices, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + return gradInput; +} + +Tensor max_pool3d_with_indices_backward_cuda( + const Tensor& gradOutput, + const Tensor& input, + IntArrayRef kernel_size, + IntArrayRef stride, + IntArrayRef padding, + IntArrayRef dilation, + bool ceil_mode, + const Tensor& indices) +{ + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("max_pool3d_with_indices_backward_cuda"); + auto gradInput = at::empty(input.sizes(), input.options()); + max_pool3d_with_indices_backward_out_cuda_template( + gradInput, + gradOutput, + input, + indices, + kernel_size, + stride, + padding, + dilation, + ceil_mode); + return gradInput; +} + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistanceKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistanceKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..2e9039dac3e0ab2783a2eb67a59e0aeaa6073af8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistanceKernel.cu @@ -0,0 +1,372 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +#include + +namespace at::native { + +namespace { + +constexpr int kCUDANumThreads = 256; + +template +struct dists { + + static __forceinline__ __device__ scalar_t sign(scalar_t val) { + return (0 < val) - (val < 0); + } + + // Zero norm + struct zero { + static __forceinline__ __device__ void inc(scalar_t& agg, const scalar_t diff, const scalar_t /*p*/) { + if (diff != diff) { // NaN + agg = diff; + } else if (diff != 0.0) { + agg += 1.0; + } + } + static __forceinline__ __device__ scalar_t finish(const scalar_t agg, const scalar_t /*p*/) { return agg; } + static __forceinline__ __device__ void agg(scalar_t& update, const scalar_t other) { update += other; } + }; + + // One norm + struct one { + static __forceinline__ __device__ void inc(scalar_t& agg, const scalar_t diff, const scalar_t /*p*/) { agg += diff; } + static __forceinline__ __device__ scalar_t finish(const scalar_t agg, const scalar_t /*p*/) { return agg; } + static __forceinline__ __device__ void agg(scalar_t& update, const scalar_t other) { update += other; } + static __forceinline__ __device__ scalar_t backward(const scalar_t diff, const scalar_t grad, const scalar_t /*dist*/, const scalar_t /*p*/) { return grad * sign(diff); } + }; + + // Special case backward when p is less than two + struct lt_two { + static __forceinline__ __device__ scalar_t backward(const scalar_t diff, const scalar_t grad, const scalar_t dist, const scalar_t p) { + return (dist == 0.0 || (diff == 0.0 && p < 1)) ? 0 : (sign(diff) * std::pow(std::abs(diff), p - 1) * grad / std::pow(dist, p - 1)); + } + }; + + // Two norm + struct two { + static __forceinline__ __device__ void inc(scalar_t& agg, const scalar_t diff, const scalar_t /*p*/) { agg += diff * diff; } + static __forceinline__ __device__ scalar_t finish(const scalar_t agg, const scalar_t /*p*/) { return device_sqrt(agg); } + static __forceinline__ __device__ void agg(scalar_t& update, const scalar_t other) { update += other; } + static __forceinline__ __device__ scalar_t backward(const scalar_t diff, const scalar_t grad, const scalar_t dist, const scalar_t /*p*/) { return dist == 0.0 ? 0 : grad * diff / dist; } + }; + + // General p norm + struct p { + static __forceinline__ __device__ void inc(scalar_t& agg, const scalar_t diff, const scalar_t p) { agg += std::pow(diff, p); } + static __forceinline__ __device__ scalar_t finish(const scalar_t agg, const scalar_t p) { return std::pow(agg, static_cast(1) / p); } + static __forceinline__ __device__ void agg(scalar_t& update, const scalar_t other) { update += other; } + static __forceinline__ __device__ scalar_t backward(const scalar_t diff, const scalar_t grad, const scalar_t dist, const scalar_t p) { return dist == 0.0 ? 0 : diff * std::pow(std::abs(diff), p - 2) * grad / std::pow(dist, p - 1); } + }; + + // Inf norm + struct inf { + static __forceinline__ __device__ void inc(scalar_t& agg, const scalar_t diff, const scalar_t /*p*/) { if (diff > agg) { agg = diff; } } + static __forceinline__ __device__ scalar_t finish(const scalar_t agg, const scalar_t /*p*/) { return agg; } + static __forceinline__ __device__ void agg(scalar_t& update, const scalar_t other) { if (other > update) { update = other; } } + static __forceinline__ __device__ scalar_t backward(const scalar_t diff, const scalar_t grad, const scalar_t dist, const scalar_t /*p*/) { return grad * sign(diff) * (std::abs(diff) == dist); } + }; + +}; + +template +struct DistReduceOp { + __forceinline__ __device__ scalar_t combine(scalar_t a, scalar_t b) const { + F::agg(a, b); + return a; + } + + __forceinline__ __device__ scalar_t warp_shfl_down(scalar_t data, int offset) const { + return WARP_SHFL_DOWN(data, offset); + } +}; + +template +__global__ static void pdist_kernel_cuda_impl(scalar_t * result, const scalar_t * self, const int64_t n, const int64_t m, const scalar_t p, + const double n2, const double n2_squared_minus_1) { + const int64_t k = blockIdx.x; + const int stride = blockDim.x; + + // The -1 accounts for floating point truncation issues + int64_t i = static_cast((n2 - device_sqrt(n2_squared_minus_1 - 2 * k))); + int64_t j = k - n * i + i * (i + 1) / 2 + i + 1; + + const scalar_t * const start = self + i * m; + const scalar_t * const end = start + m; + const scalar_t * a = start + threadIdx.x; + const scalar_t * b = self + j * m + threadIdx.x; + scalar_t agg = 0.0; + for (; a < end; a += stride, b += stride) { + F::inc(agg, std::abs(*a - *b), p); + } + + __shared__ scalar_t agg_smem[kCUDANumThreads]; + scalar_t agg_init{0.0}; + agg = cuda_utils::BlockReduce(agg, DistReduceOp{}, agg_init, agg_smem); + if (threadIdx.x == 0) { + result[k] = F::finish(agg, p); + } +} + +template +__global__ static void cdist_backward_kernel_cuda_impl(scalar_t * buffer, const scalar_t * grad, const scalar_t * x1, const scalar_t * x2, const scalar_t * dist, + const scalar_t p, const int64_t r1, const int64_t r2, const int64_t m, const int64_t count, const int64_t r_size, const int64_t l1_size, const int64_t l2_size) { + const int y = (blockIdx.y * gridDim.z + blockIdx.z) * blockDim.y + threadIdx.y; + const int init = blockIdx.x * blockDim.x + threadIdx.x; + if (y >= count || init >= m) { + return; + } + const int l = y / r_size; + const int k = y % r_size; + const int stride = blockDim.x * gridDim.x; + const int l_size = r_size * m; + + int64_t i = k / r2; + int64_t j = k % r2; + + const scalar_t grad_k = grad[y]; + const scalar_t dist_k = dist[y]; + + const scalar_t * const start = x1 + l * l1_size + i * m; + const scalar_t * const end = start + m; + const scalar_t * self_i = start + init; + const scalar_t * self_j = x2 + l * l2_size + j * m + init; + + scalar_t * buff_i = buffer + l * l_size + (r1 * j + i) * m + init; + + for (; self_i < end; self_i += stride, self_j += stride, buff_i += stride) { + const scalar_t res = F::backward(*self_i - *self_j, grad_k, dist_k, p); + *buff_i = res; + } +} + +template +__global__ static void pdist_backward_kernel_cuda_impl(scalar_t * buffer, const scalar_t * grad, const scalar_t * self, const scalar_t * dist, int64_t gs, const int64_t n, const int64_t m, const int64_t combs, const scalar_t p, + const double n2, const double n2_squared_minus_1) { + const int64_t k = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x; + const int init = blockIdx.y * blockDim.y + threadIdx.y; + const int stride = blockDim.y * gridDim.y; + + if (k >= combs) { + return; + } + + // The -1 accounts for floating point truncation issues + int64_t i = static_cast((n2 - device_sqrt(n2_squared_minus_1 - 2 * k))); + int64_t j = k - n * i + i * (i + 1) / 2 + i + 1; + int64_t ib = j - i - 1; + int64_t jb = n - 2 - i; + + const scalar_t grad_k = grad[k * gs]; + const scalar_t dist_k = dist[k]; + + const scalar_t * const start = self + i * m; + const scalar_t * const end = start + m; + const scalar_t * self_i = start + init; + const scalar_t * self_j = self + j * m + init; + scalar_t * buff_i = buffer + (ib * n + i) * m + init; + scalar_t * buff_j = buffer + (jb * n + j) * m + init; + for (; self_i < end; self_i += stride, self_j += stride, buff_i += stride, buff_j += stride) { + const scalar_t res = F::backward(*self_i - *self_j, grad_k, dist_k, p); + *buff_i = res; + *buff_j = -res; + } +} + +template +__global__ static void cdist_kernel_cuda_impl(scalar_t * result, const scalar_t * x1, const scalar_t * x2, + const scalar_t p, const int64_t r2, const int64_t m, const int64_t r_size, const int64_t l1_size, const int64_t l2_size) { + const int64_t l = blockIdx.x / r_size; + const int64_t k = blockIdx.x % r_size; + const int64_t i = k / r2; + const int64_t j = k % r2; + const int stride = blockDim.x; + + const scalar_t * const start = x1 + l * l1_size + i * m; + const scalar_t * const end = start + m; + const scalar_t * a = start + threadIdx.x; + const scalar_t * b = x2 + l * l2_size + j * m + threadIdx.x; + + scalar_t agg = 0.0; + for (; a < end; a += stride, b += stride) { + F::inc(agg, std::abs(*a - *b), p); + } + __shared__ scalar_t agg_smem[kCUDANumThreads]; + scalar_t agg_init{0.0}; + agg = cuda_utils::BlockReduce(agg, DistReduceOp{}, agg_init, agg_smem); + if (threadIdx.x == 0) { + result[blockIdx.x] = F::finish(agg, p); + } +} + +void cdist_kernel_impl(Tensor& result, const Tensor& x1, const Tensor& x2, double p) { + const int64_t r1 = x1.size(-2); + const int64_t r2 = x2.size(-2); + const int64_t m = x1.size(-1); + const int64_t r_size = r1 * r2; + const int64_t l1_size = r1 * m; + const int64_t l2_size = r2 * m; + const dim3 grid(result.numel()); + const dim3 block(kCUDANumThreads); + + AT_DISPATCH_FLOATING_TYPES(x1.scalar_type(), "cdist_cuda", [&] { + auto impl_fptr = cdist_kernel_cuda_impl::p>; + if (p == 0.0) { + impl_fptr = cdist_kernel_cuda_impl::zero>; + } else if (p == 1.0) { + impl_fptr = cdist_kernel_cuda_impl::one>; + } else if (p == 2.0) { + impl_fptr = cdist_kernel_cuda_impl::two>; + } else if (std::isinf(p)) { + impl_fptr = cdist_kernel_cuda_impl::inf>; + } + impl_fptr<<>>(result.mutable_data_ptr(), x1.const_data_ptr(), x2.const_data_ptr(), p, r2, m, r_size, l1_size, l2_size); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); +} + +void pdist_forward_kernel_impl(Tensor& result, const Tensor& self, double p) { + const dim3 grid(result.numel()); + const dim3 block(kCUDANumThreads); + int64_t n = self.size(0); + int64_t m = self.size(1); + // https://github.com/pytorch/pytorch/issues/15511 demonstrated we need to do + // some math in fp64 -- this is just minimizing the amount of fp64 math we do on the device. + const double n2 = n - .5; + const double n2_squared_minus_1 = n2 * n2 - 1; + + AT_DISPATCH_FLOATING_TYPES(self.scalar_type(), "pdist_cuda", [&] { + auto impl_fptr = pdist_kernel_cuda_impl::p>; + if (p == 0.0) { + impl_fptr = pdist_kernel_cuda_impl::zero>; + } else if (p == 1.0) { + impl_fptr = pdist_kernel_cuda_impl::one>; + } else if (p == 2.0) { + impl_fptr = pdist_kernel_cuda_impl::two>; + } else if (std::isinf(p)) { + impl_fptr = pdist_kernel_cuda_impl::inf>; + } + impl_fptr<<>>(result.mutable_data_ptr(), self.const_data_ptr(), n, m, p, n2, n2_squared_minus_1); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); +} + +void pdist_backward_kernel_impl(Tensor& result, const Tensor& grad, const Tensor& self, const double p, const Tensor& dist) { + if (p == 0.0 || grad.numel() == 0 || self.numel() == 0) { + result.fill_(0); + return; + } + + const int64_t n = result.size(0); + int64_t m = self.size(1); + const int block_x = 16; + // NB: be careful with changing block_y; as it's currently written, grid_y is limited to be 2^16. + // block_y of 64 gives us max pdist dim1 of 2**24 + const int block_y = 64; + const int grid_x = (dist.numel() + block_x - 1) / block_x; + const int grid_y = (m + block_y * 8 - 1) / (block_y * 8); + const dim3 grid(grid_x, grid_y); + const dim3 block(block_x, block_y); + // https://github.com/pytorch/pytorch/issues/15511 demonstrated we need to do + // some math in fp64 -- this is just minimizing the amount of fp64 math we do on the device. + const double n2 = n - .5; + const double n2_squared_minus_1 = n2 * n2 - 1; + + Tensor buffer = at::empty({n - 1, result.size(0), result.size(1)}, result.options()); + AT_DISPATCH_FLOATING_TYPES(self.scalar_type(), "pdist_cuda_backward", [&] { + auto impl_fptr = pdist_backward_kernel_cuda_impl::p>; + if (p == 1.0) { + impl_fptr = pdist_backward_kernel_cuda_impl::one>; + } else if (p < 2.0) { + impl_fptr = pdist_backward_kernel_cuda_impl::lt_two>; + } else if (p == 2.0) { + impl_fptr = pdist_backward_kernel_cuda_impl::two>; + } else if (std::isinf(p)) { + impl_fptr = pdist_backward_kernel_cuda_impl::inf>; + } + impl_fptr<<>>(buffer.mutable_data_ptr(), grad.const_data_ptr(), self.const_data_ptr(), dist.const_data_ptr(), grad.stride(0), n, m, dist.numel(), p, n2, n2_squared_minus_1); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + + at::sum_out(result, buffer, 0); +} + +void cdist_backward_kernel_impl(Tensor& result, const Tensor& grad, const Tensor& x1, const Tensor& x2, const double p, const Tensor& dist) { + if (p == 0.0 || grad.numel() == 0 || x1.numel() == 0 || x2.numel() == 0) { + result.fill_(0); + return; + } + + const int64_t r1 = x1.size(-2); + const int64_t r2 = x2.size(-2); + const int64_t m = x1.size(-1); + // Just like we do in the CPU code, assume that result is always batched + int64_t batch = result.size(0); + const int block_x = 64; + const int block_y = 16; + const int grid_x = (m + block_x * 8 - 1) / (block_x * 8); + + const int64_t count = dist.numel(); + const int64_t grid_temp = (count + block_y - 1) / block_y; + + const int grid_y = (grid_temp - 1) / 65535 + 1; + const int grid_z = (grid_temp - 1) / grid_y + 1; + + const dim3 grid(grid_x, grid_y, grid_z); + const dim3 block(block_x, block_y); + + const int64_t r_size = r1 * r2; + const int64_t l1_size = r1 * m; + const int64_t l2_size = r2 * m; + //current implementation supports only gradient that can be collapsed to 1D. However, to avoid checking this assumption, + //we call grad.contiguous() before backward, so stride is guaranteed to be 1 + + Tensor buffer = at::empty({batch, r2, r1, m}, result.options()); + AT_DISPATCH_FLOATING_TYPES(result.scalar_type(), "cdist_cuda_backward", [&] { + auto impl_fptr = cdist_backward_kernel_cuda_impl::p>; + if (p == 1.0) { + impl_fptr = cdist_backward_kernel_cuda_impl::one>; + } else if (p < 2.0) { + impl_fptr = cdist_backward_kernel_cuda_impl::lt_two>; + } else if (p == 2.0) { + impl_fptr = cdist_backward_kernel_cuda_impl::two>; + } else if (std::isinf(p)) { + impl_fptr = cdist_backward_kernel_cuda_impl::inf>; + } + impl_fptr<<>>(buffer.mutable_data_ptr(), + grad.const_data_ptr(), x1.const_data_ptr(), x2.const_data_ptr(), dist.const_data_ptr(), + p, r1, r2, m, count, r_size, l1_size, l2_size); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + + at::sum_out(result, buffer, 1); + +} + + +} // anonymous namespace + +REGISTER_DISPATCH(pdist_forward_stub, &pdist_forward_kernel_impl) +REGISTER_DISPATCH(pdist_backward_stub, &pdist_backward_kernel_impl) +REGISTER_DISPATCH(cdist_stub, &cdist_kernel_impl) +REGISTER_DISPATCH(cdist_backward_stub, &cdist_backward_kernel_impl) + +} // at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionBernoulli.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionBernoulli.cu new file mode 100644 index 0000000000000000000000000000000000000000..6be50c393ce278e2f43b62137e55c5c2505100d7 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionBernoulli.cu @@ -0,0 +1,39 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +namespace at::native { + +void bernoulli_tensor_kernel(const TensorBase &self, const TensorBase &p_, std::optional gen_) { + auto generator = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::bernoulli_kernel(self, p_, generator); +} + +void bernoulli_scalar_kernel(const TensorBase &self, double p, std::optional gen) { + auto iter = TensorIterator::borrowing_nullary_op(self); + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::bernoulli_kernel(iter, p, generator); +} + +REGISTER_DISPATCH(bernoulli_tensor_stub, &bernoulli_tensor_kernel) +REGISTER_DISPATCH(bernoulli_scalar_stub, &bernoulli_scalar_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionCauchyKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionCauchyKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..3c0b5a44c2fd41036c02610ed37cd9fe0b56ecba --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionCauchyKernel.cu @@ -0,0 +1,15 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void cauchy_kernel(TensorIteratorBase& iter, double median, double sigma, std::optional gen) { + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::cauchy_kernel(iter, median, sigma, generator); +} + +REGISTER_DISPATCH(cauchy_stub, &cauchy_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionExponentialKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionExponentialKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..476ea4e57cd11536d541cbc840020389ae58a515 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionExponentialKernel.cu @@ -0,0 +1,15 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void exponential_kernel(TensorIteratorBase& iter, double lambda, std::optional gen) { + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::exponential_kernel(iter, lambda, generator); +} + +REGISTER_DISPATCH(exponential_stub, &exponential_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionGeometricKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionGeometricKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..3cacc1cfe801e1f745ed5c2c8b4f21cf7fb4b238 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionGeometricKernel.cu @@ -0,0 +1,15 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void geometric_kernel(TensorIteratorBase& iter, double p_, std::optional gen) { + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::geometric_kernel(iter, p_, generator); +} + +REGISTER_DISPATCH(geometric_stub, &geometric_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionLogNormalKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionLogNormalKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..e43d5b052775535fbd28be94f2edf033197741ed --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionLogNormalKernel.cu @@ -0,0 +1,15 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void log_normal_kernel(TensorIteratorBase& iter, double mean, double std, std::optional gen) { + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::log_normal_kernel(iter, mean, std, generator); +} + +REGISTER_DISPATCH(log_normal_stub, &log_normal_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionNormal.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionNormal.cu new file mode 100644 index 0000000000000000000000000000000000000000..747b3f6477d8d5f931d3828b887f8449927439dd --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionNormal.cu @@ -0,0 +1,15 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void normal_kernel(const TensorBase &self, double mean, double std, std::optional gen) { + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::normal_kernel(self, mean, std, generator); +} + +REGISTER_DISPATCH(normal_stub, &normal_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionRandomKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionRandomKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..c70602bf3dfcb88a8c6cfeece33f7e752eeb5e4f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionRandomKernel.cu @@ -0,0 +1,27 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional gen_) { + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::random_from_to_kernel(iter, range, base, gen); +} + +void random_full_64_bits_range_kernel(TensorIteratorBase& iter, std::optional gen_) { + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::random_full_64_bits_range_kernel(iter, gen); +} + +void random_kernel(TensorIteratorBase& iter, std::optional gen_) { + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + at::native::templates::cuda::random_kernel(iter, gen); +} + +REGISTER_DISPATCH(random_from_to_stub, &random_from_to_kernel) +REGISTER_DISPATCH(random_stub, &random_kernel) +REGISTER_DISPATCH(random_full_64_bits_range_stub, &random_full_64_bits_range_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionTemplates.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionTemplates.h new file mode 100644 index 0000000000000000000000000000000000000000..7c8b4dfec2a719d8fc574ddf32bca766ab4710bc --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionTemplates.h @@ -0,0 +1,697 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +namespace { + +// launch bounds used for kernels utilizing TensorIterator +const uint32_t block_size_bound = 256; +const uint32_t grid_size_bound = 4; +// At the time of writing, there is no curand_* call that increments the offset by more than 4. +// See: https://docs.nvidia.com/cuda/archive/11.8.0/curand/group__DEVICE.html +const uint32_t max_generator_offsets_per_curand_call = 4; + +// utility function that calculates proper philox_offset +// for distributions utilizing TensorIterator. For distributions using +// TensorIterator, we are using a grid-stride loop with each +// thread yielding one element per thread. For the edge of the grid-stride +// loop, if the tensor size is large, the unroll loop will kick in and the float4 +// from curand4 will start getting utilized (for common tensor sizes, we end up +// using rand.x from each thread). The philox_offset calculation was changed to +// (number of elements per thread * maximum generator increment per "curand_*" call), which makes +// sure that philox offset increment is not less than the number of randoms used +// in each thread. +std::tuple calc_execution_policy(const int64_t total_elements, const uint32_t unroll_factor) { + const uint64_t numel = static_cast(total_elements); + const uint32_t block_size = block_size_bound; + dim3 dim_block(block_size); + dim3 grid((numel + block_size - 1) / block_size); + uint32_t blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor / block_size; + grid.x = std::min( + static_cast(at::cuda::getCurrentDeviceProperties()->multiProcessorCount) * blocks_per_sm, + grid.x); + //number of times random will be generated per thread, to offset philox counter in thc random state + uint64_t counter_offset = ((numel - 1) / (block_size * grid.x * unroll_factor) + 1) * max_generator_offsets_per_curand_call; + return std::make_tuple(counter_offset, grid, dim_block); +} + +// grid stride loop kernel for distributions +template +C10_LAUNCH_BOUNDS_2(block_size_bound, grid_size_bound) +__global__ void distribution_elementwise_grid_stride_kernel(int64_t numel, + PhiloxCudaState philox_args, + const dist_t dist_func, + const transform_t transform_func) { + auto [seed, offset] = at::cuda::philox::unpack(philox_args); + int64_t idx = ((int64_t) blockIdx.x) * blockDim.x + threadIdx.x; + curandStatePhilox4_32_10_t state; + curand_init(seed, idx, offset, &state); + + int64_t rounded_size = ((numel - 1)/(blockDim.x * gridDim.x * unroll_factor)+1) * + blockDim.x * gridDim.x * unroll_factor; + for(int64_t linear_index = idx; linear_index < rounded_size; linear_index += blockDim.x * gridDim.x * unroll_factor) { + auto rand = dist_func(&state); + #pragma unroll + for (int ii = 0; ii < unroll_factor; ii++) { + int64_t li = linear_index + blockDim.x * gridDim.x * ii; + if (li < numel) { + transform_func(li, static_cast((&rand.x)[ii])); + } + } + __syncthreads(); + } +} + +/** + * distribution_nullary_kernel is analogous to gpu_kernel in + * ATen/native/cuda/Loops.cuh. Like gpu_kernel, it uses + * TensorIterator to launch a kernel. However, the differences are + * - it launches a grid-stride loop based kernel. The kernel is not + * generic like elementwise_kernel in Loops.cuh and is specialized + * for the distribution kernels here. + * - For big size tensors, we can launch multiple kernels recursively + * (i.e. if (!iter.can_use_32bit_indexing())) and hence, the philox + * offset calculation is done in this function. + * + * FIXME: Can we specialize elementwise_kernel and launch_kernel in Loops.cuh + * to have grid-stride loop kernel and then use that to launch our distribution + * kernels? Note that we need a grid-stride loop kernel because, we found by testing + * that it achieves peak effective bandwidth. + */ +template +void distribution_nullary_kernel(at::TensorIteratorBase& iter, + RNG gen, + const dist_t& dist_func, + const transform_t transform_func) { + const int unroll_factor = sizeof(dist_func_return_t) / sizeof(accscalar_t); + TORCH_CHECK(unroll_factor >= 1, "unroll_factor must be >= 1."); + int64_t numel = iter.numel(); + if (numel == 0) { + return; + } + + auto [counter_offset, grid, block] = calc_execution_policy(numel, unroll_factor); + PhiloxCudaState rng_engine_inputs; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + rng_engine_inputs = gen->philox_cuda_state(counter_offset); + } + + if (!iter.can_use_32bit_indexing()) { + for (auto& sub_iter : iter.with_32bit_indexing()) { + distribution_nullary_kernel(sub_iter, + gen, dist_func, transform_func); + } + return; + } + + char* out_data = (char*)iter.data_ptr(0); + + auto stream = at::cuda::getCurrentCUDAStream(); + if (iter.is_trivial_1d()) { + auto strides = iter.get_inner_strides(); + int stride0 = strides[0]; + distribution_elementwise_grid_stride_kernel<<>>( + numel, + rng_engine_inputs, + dist_func, + [=]__device__(int idx, accscalar_t rand) { + scalar_t* out = (scalar_t*)&out_data[stride0 * idx]; + *out = transform_func(rand); + } + ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + auto offset_calc = make_offset_calculator<1>(iter); + distribution_elementwise_grid_stride_kernel<<>>( + numel, + rng_engine_inputs, + dist_func, + [=]__device__(int idx, accscalar_t rand) { + auto offsets = offset_calc.get(idx); + scalar_t* out = (scalar_t*)&out_data[offsets[0]]; + *out = transform_func(rand); + } + ); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } +} + +// Binary kernel +template +__global__ void distribution_binary_elementwise_kernel( + int numel, + func_t f, + PhiloxCudaState philox_args, + typename function_traits::result_type *output_data, + const typename function_traits::template arg<1>::type *input_data_1, + const typename function_traits::template arg<2>::type *input_data_2, + inp_offset_calc_t inp_calc, + out_offset_calc_t out_calc) { + auto seeds = at::cuda::philox::unpack(philox_args); + + using input_t_1 = typename function_traits::template arg<1>::type; + using input_t_2 = typename function_traits::template arg<2>::type; + + input_t_1 inputs_1[thread_work_size()]; + input_t_2 inputs_2[thread_work_size()]; + + int base_index = block_work_size() * blockIdx.x; + int remaining = std::min(numel - base_index, block_work_size()); + + curandStatePhilox4_32_10_t state; + curand_init(std::get<0>(seeds), + blockIdx.x * blockDim.x + threadIdx.x, + std::get<1>(seeds), + &state); + + // load data into registers + int thread_idx = threadIdx.x; + #pragma unroll + for (int i = 0; i < thread_work_size(); i++) { + if (thread_idx >= remaining) { + break; + } + int input_idx = thread_idx + base_index; + auto offsets = inp_calc.get(input_idx); + inputs_1[i] = input_data_1[offsets[0]]; + inputs_2[i] = input_data_2[offsets[1]]; + + thread_idx += num_threads(); + } + + // compute and store + thread_idx = threadIdx.x; + #pragma unroll + for (int i = 0; i < thread_work_size(); i++) { + if (thread_idx >= remaining) { + break; + } + int input_idx = thread_idx + base_index; + auto offsets = out_calc.get(input_idx); + output_data[offsets[0]] = f(state, inputs_1[i], inputs_2[i]); + thread_idx += num_threads(); + } +} + +template +void distribution_binary_kernel(TensorIteratorBase &iter, PhiloxCudaState philox_args, const func_t &f) { + static_assert(std::is_same_v::template arg<0>::type, curandStatePhilox4_32_10_t&>, "the first argument of functor must be curandStatePhilox4_32_10_t"); + using input_t_1 = typename function_traits::template arg<1>::type; + using input_t_2 = typename function_traits::template arg<2>::type; + using output_t = typename function_traits::result_type; + + if (!iter.can_use_32bit_indexing()) { + for (auto& sub_iter : iter.with_32bit_indexing()) { + distribution_binary_kernel(sub_iter, philox_args, f); + } + return; + } + + TORCH_INTERNAL_ASSERT_DEBUG_ONLY(iter.can_use_32bit_indexing()); + + int64_t numel = iter.numel(); + if (numel == 0) { + return; + } + + output_t *output_data = static_cast(iter.data_ptr(0)); + const input_t_1 *input_data_1 = static_cast(iter.data_ptr(1)); + const input_t_2 *input_data_2 = static_cast(iter.data_ptr(2)); + + int64_t grid = (numel + block_work_size() - 1) / block_work_size(); + auto stream = at::cuda::getCurrentCUDAStream(); + + if (iter.is_contiguous()) { + distribution_binary_elementwise_kernel<<>>( + numel, f, philox_args, output_data, input_data_1, input_data_2, + TrivialOffsetCalculator<2>(), TrivialOffsetCalculator<1>()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + distribution_binary_elementwise_kernel<<>>( + numel, f, philox_args, output_data, input_data_1, input_data_2, + make_input_offset_calculator<2>(iter), make_output_offset_calculator(iter)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } +} + +} // namespace +}} // namespace at::native + + +namespace at { +namespace native { +namespace templates { +namespace cuda { + +// ==================================================== Random ======================================================== + +template +void random_from_to_kernel(TensorIteratorBase& iter, uint64_t range, int64_t base, RNG gen) { +#ifdef FBCODE_CAFFE2 + AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cuda", AT_WRAP([&] { + if (( + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v) && range >= 1ULL << 32) + { + // define lambda to mod with range and add base + auto random_func = [range, base] __device__ (uint64_t rand) { + return transformation::uniform_int_from_to(rand, range, base); + }; + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 { + ulonglong2 ret; + uint4 rand_val = curand4(state); + ret.x = (static_cast(rand_val.x) << 32) | rand_val.y; + ret.y = (static_cast(rand_val.z) << 32) | rand_val.w; + return ret; + }, + random_func); + } else { + auto random_func = [range, base] __device__ (uint32_t rand) { + return transformation::uniform_int_from_to(rand, range, base); + }; + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> uint4 { + return curand4(state); + }, + random_func); + } + }), AT_EXPAND(AT_ALL_TYPES), kBool, kHalf, kBFloat16, AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)); +#else + AT_DISPATCH_V2(iter.dtype(), "random_from_to_kernel_cuda", AT_WRAP([&] { + if (range >= 1ULL << 28) // allow approx 5% skew in uniform int generation using % + { + // define lambda to mod with range and add base + auto random_func = [range, base] __device__ (uint64_t rand) { + return transformation::uniform_int_from_to(rand, range, base); + }; + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 { + ulonglong2 ret; + uint4 rand_val = curand4(state); + ret.x = (static_cast(rand_val.x) << 32) | rand_val.y; + ret.y = (static_cast(rand_val.z) << 32) | rand_val.w; + return ret; + }, + random_func); + } else { + auto random_func = [range, base] __device__ (uint32_t rand) { + return transformation::uniform_int_from_to(rand, range, base); + }; + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> uint4 { + return curand4(state); + }, + random_func); + } + }), AT_EXPAND(AT_ALL_TYPES), kBool, kHalf, kBFloat16, AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)); +#endif +} + +// This is the special kernel to handle single specific case: +// from(inclusive) = std::numeric_limits::lowest() +// to(exclusive) = None (= std::numeric_limits::max() + 1) +template +void random_full_64_bits_range_kernel(TensorIteratorBase& iter, RNG gen) { + AT_DISPATCH_ALL_TYPES_AND(at::ScalarType::BFloat16, iter.dtype(), "random_full_64_bits_range_kernel_cuda", [&] { + if (std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v) { + auto random_func = [] __device__ (uint64_t rand) { + return transformation::uniform_int_full_range(rand); + }; + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 { + ulonglong2 ret; + uint4 rand_val = curand4(state); + ret.x = (static_cast(rand_val.x) << 32) | rand_val.y; + ret.y = (static_cast(rand_val.z) << 32) | rand_val.w; + return ret; + }, + random_func); + } else { + TORCH_CHECK(false, "random_full_64_bits_range_kernel_cuda handles only int64, double, float and bfloat16"); + } + }); +} + +template +struct RandomFromToKernel { + void operator()(TensorIteratorBase& iter, uint64_t range, int64_t base, std::optional gen) { + random_from_to_kernel(iter, range, base, check_generator(gen)); + } + void operator()(TensorIteratorBase& iter, std::optional gen) { + random_full_64_bits_range_kernel(iter, check_generator(gen)); + } +}; + +template +void random_kernel(TensorIteratorBase& iter, RNG gen) { + AT_DISPATCH_ALL_TYPES_AND3(at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "random_kernel_cuda", [&] { + if (std::is_same_v || std::is_same_v) { + auto random_func = [] __device__ (uint64_t rand) { + return transformation::uniform_int(rand); + }; + distribution_nullary_kernel(iter, gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> ulonglong2 { + ulonglong2 ret; + uint4 rand_val = curand4(state); + ret.x = (static_cast(rand_val.x) << 32) | rand_val.y; + ret.y = (static_cast(rand_val.z) << 32) | rand_val.w; + return ret; + }, + random_func); + } else { + auto random_func = [] __device__ (uint32_t rand) { + return transformation::uniform_int(rand); + }; + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> uint4 { + return curand4(state); + }, + random_func); + } + }); +} + +template +struct RandomKernel { + void operator()(TensorIteratorBase& iter, RNG gen) { + random_kernel(iter, gen); + } +}; + +// ==================================================================================================================== + +template +void uniform_and_transform(TensorIteratorBase& iter, RNG gen, transform_t transform) { + if (std::is_same_v) { + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> double2 { return curand_uniform2_double(state); }, + transform); + } else { + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> float4 { return curand_uniform4(state); }, + transform); + } +} + +template +void normal_and_transform(TensorIteratorBase& iter, RNG gen, transform_t transform) { + if (std::is_same_v) { + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> double2 { return curand_normal2_double(state); }, + transform); + } else { + distribution_nullary_kernel(iter, + gen, + [] __device__ (curandStatePhilox4_32_10_t* state) -> float4 { return curand_normal4(state); }, + transform); + } +} + +// ==================================================== Normal ======================================================== + +template +void normal_kernel(const TensorBase &self, double mean_, double std_, RNG gen) { + auto iter = TensorIterator::borrowing_nullary_op(self); + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "normal_kernel_cuda", [&] { + using accscalar_t = at::acc_type; + auto mean = static_cast(mean_); + auto std = static_cast(std_); + // define lambda to multiply std and add mean + auto normal_func = [mean, std] __device__ (accscalar_t rand) { + return static_cast(transformation::normal(rand, mean, std)); + }; + normal_and_transform(iter, gen, normal_func); + }); +} + +template +struct NormalKernel { + void operator()(const TensorBase &self, double mean, double std, std::optional gen) { + normal_kernel(self, mean, std, check_generator(gen)); + } +}; + +// ==================================================== Uniform ======================================================== + +template +void uniform_kernel(TensorIteratorBase& iter, double from_, double to_, RNG gen) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "uniform_kernel_cuda", [&] { + auto from = static_cast(from_); + auto to = static_cast(to_); + using opmath_t = at::opmath_type; + auto range = static_cast(to-from); + // define lambda to reverse bounds, multiply 'range' and add 'from_' + auto uniform_func = [range, from, to] __device__ (opmath_t rand) { + // Compute output value before reversing the bounds + // BEFORE TOUCHING THIS CODE READ: https://github.com/pytorch/pytorch/issues/96947 + auto value = static_cast(rand * range + from); + // reverse the bounds of curand4 from (0, 1] to [0, 1) + // Note that this method is from legacy THCTensorRandom and is likely to give + // you more 0-s, since, the probability of getting 1-s is higher than 0-s and + // by reversing the bounds, we are flipping the probabilities of 1-s and 0-s. + // BEFORE TOUCHING THIS CODE READ: https://github.com/pytorch/pytorch/issues/16706 + auto reverse_bound_value = value == to ? from : value; + return reverse_bound_value; + }; + uniform_and_transform(iter, gen, uniform_func); + }); +} + +template +struct UniformKernel { + void operator()(TensorIteratorBase& iter, double from, double to, std::optional gen) { + uniform_kernel(iter, from, to, check_generator(gen)); + } +}; + +// ================================================== LogNormal ======================================================= + +template +void log_normal_kernel(TensorIteratorBase& iter, double mean_, double std_, RNG gen) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "log_normal_cuda", [&] { + using accscalar_t = at::acc_type; + auto mean = static_cast(mean_); + auto std = static_cast(std_); + // define lambda for log_normal transformation + auto log_normal_func = [mean, std] __device__ (accscalar_t rand) { + return static_cast(transformation::log_normal(transformation::normal(rand, mean, std))); + }; + normal_and_transform(iter, gen, log_normal_func); + }); +} + +template +struct LogNormalKernel { + void operator()(TensorIteratorBase& iter, double mean, double std, std::optional gen) { + log_normal_kernel(iter, mean, std, check_generator(gen)); + } +}; + +// =================================================== Geometric ====================================================== + +template +void geometric_kernel(TensorIteratorBase& iter, double p, RNG gen) { + AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "geometric_cuda", [&] { + using accscalar_t = at::DiscreteDistributionType::type; + // define lambda for geometric transformation + auto geometric_func = [p] __device__ (accscalar_t rand) { + return static_cast(transformation::geometric(rand, p)); + }; + uniform_and_transform(iter, gen, geometric_func); + }); +} + +template +struct GeometricKernel { + void operator()(TensorIteratorBase& iter, double p, std::optional gen) { + geometric_kernel(iter, p, check_generator(gen)); + } +}; + +// ================================================== Exponential ===================================================== + +template +void exponential_kernel(TensorIteratorBase& iter, double lambda_, RNG gen) { + TORCH_CHECK(isFloatingType(iter.dtype()), "Exponential distribution is a continuous probability distribution. dtype must be a floating point but you specified ", iter.dtype()); + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "exponential_cuda", [&] { + using accscalar_t = at::acc_type; + auto lambda = static_cast(lambda_); + // define lambda for exponential transformation + auto exponential_func = [lambda] __device__ (accscalar_t rand) { + return static_cast(transformation::exponential(rand, lambda)); + }; + uniform_and_transform(iter, gen, exponential_func); + }); +} + +template +struct ExponentialKernel { + void operator()(TensorIteratorBase& iter, double lambda, std::optional gen) { + exponential_kernel(iter, lambda, check_generator(gen)); + } +}; + +// ==================================================== Cauchy ======================================================== + +template +void cauchy_kernel(TensorIteratorBase& iter, double median_, double sigma_, RNG gen) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.dtype(), "cauchy_cuda", [&] { + using accscalar_t = at::acc_type; + auto median = static_cast(median_); + auto sigma = static_cast(sigma_); + // define lambda for cauchy transformation + auto cauchy_func = [median, sigma] __device__ (accscalar_t rand) { + return static_cast(transformation::cauchy(rand, median, sigma)); + }; + uniform_and_transform(iter, gen, cauchy_func); + }); +} + +template +struct CauchyKernel { + void operator()(TensorIteratorBase& iter, double median, double sigma, std::optional gen) { + cauchy_kernel(iter, median, sigma, check_generator(gen)); + } +}; + +// ==================================================== Bernoulli ===================================================== + +template +void bernoulli_tensor_cuda_kernel( + const TensorBase &ret, const at::TensorBase &p, + PhiloxCudaState philox_args) { + auto functor = [philox_args] __device__( + int n, scalar_t& v1, scalar_t& v2, scalar_t& v3, scalar_t& v4, + const prob_t& p1, const prob_t& p2, const prob_t& p3, const prob_t& p4) { + auto seeds = at::cuda::philox::unpack(philox_args); + curandStatePhilox4_32_10_t state; + curand_init(std::get<0>(seeds), + blockIdx.x * blockDim.x + threadIdx.x, + std::get<1>(seeds), + &state); + + // See Note [Register spilling in curand call for CUDA < 10] + float4 rand = curand_uniform4(&state); + switch (n) { + case 4: { + CUDA_KERNEL_ASSERT(0 <= p4 && p4 <= 1); + v4 = static_cast(rand.w <= p4); + [[fallthrough]]; + } + case 3: { + CUDA_KERNEL_ASSERT(0 <= p3 && p3 <= 1); + v3 = static_cast(rand.z <= p3); + [[fallthrough]]; + } + case 2: { + CUDA_KERNEL_ASSERT(0 <= p2 && p2 <= 1); + v2 = static_cast(rand.y <= p2); + [[fallthrough]]; + } + case 1: { + CUDA_KERNEL_ASSERT(0 <= p1 && p1 <= 1); + v1 = static_cast(rand.x <= p1); + } + } + }; + // The template argument `4` below indicates that we want to operate on four + // element at each time. See NOTE [ CUDA_tensor_applyN helpers ] for details. + at::cuda::CUDA_tensor_apply2(ret, p, functor); +} + +template +void bernoulli_kernel(const TensorBase &self, const TensorBase &p_, RNG gen) { + PhiloxCudaState rng_engine_inputs; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + rng_engine_inputs = gen->philox_cuda_state(10); + } + TORCH_CHECK(at::isFloatingType(p_.scalar_type()), "expected probabilities tensor to have floating type, got ", p_.scalar_type()); + // cast probabilities tensor to double for double `self` tensor, and to `float` for everything else + const auto p_type = self.dtype() == at::kDouble ? at::kDouble : at::kFloat; + auto p_cuda = p_.to(TensorOptions().device(self.device()).dtype(p_type)); + auto p = expand_inplace(self, p_cuda); + AT_DISPATCH_ALL_TYPES_AND3( + at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, self.scalar_type(), "bernoulli_tensor_cuda_self_", [&] { + if (std::is_same_v) { + return bernoulli_tensor_cuda_kernel(self, *p, rng_engine_inputs); + } else { + return bernoulli_tensor_cuda_kernel(self, *p, rng_engine_inputs); + } + }); +} + +template +void bernoulli_kernel(TensorIteratorBase& iter, double p, RNG gen) { + AT_DISPATCH_ALL_TYPES_AND3( + at::ScalarType::Half, at::ScalarType::BFloat16, at::ScalarType::Bool, iter.dtype(), "bernoulli_scalar_cuda_", [&] { + using accscalar_t = at::DiscreteDistributionType::type; + // define lambda for bernoulli transformation + auto bernoulli_func = [p] __device__ (accscalar_t rand) { + return static_cast(transformation::bernoulli(rand, p)); + }; + uniform_and_transform(iter, gen, bernoulli_func); + }); +} + +template +struct BernoulliKernel { + void operator()(TensorIteratorBase& iter, double p, std::optional gen) { + bernoulli_kernel(iter, p, check_generator(gen)); + } + void operator()(const TensorBase &self, const TensorBase &p_, std::optional gen) { + bernoulli_kernel(self, p_, check_generator(gen)); + } +}; + +}}}} diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionUniform.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionUniform.cu new file mode 100644 index 0000000000000000000000000000000000000000..9fea33ecd215b42790081433c4ffe6a51b5a78d4 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/DistributionUniform.cu @@ -0,0 +1,15 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include + +namespace at::native { + +void uniform_kernel(TensorIteratorBase& iter, double from, double to, std::optional gen) { + auto generator = get_generator_or_default(gen, cuda::detail::getDefaultCUDAGenerator()); + templates::cuda::uniform_kernel(iter, from, to, generator); +} + +REGISTER_DISPATCH(uniform_stub, &uniform_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f817e94b8388d6c03aa2bf1545beddd54c403864 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.cpp @@ -0,0 +1,96 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +// NOLINTNEXTLINE(performance-unnecessary-value-param) +Tensor _s_poisson_cuda(const Tensor& lambda, std::optional gen_) { + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + Tensor ret = at::empty(lambda.sizes(), lambda.options()); + launch_poisson_cuda_kernel(ret, lambda, gen); + return ret; +} + +// NOLINTNEXTLINE(performance-unnecessary-value-param) +Tensor _s_binomial_cuda(const Tensor& count, const Tensor& prob, std::optional gen_) { + TORCH_CHECK_VALUE( + at::isFloatingType(count.scalar_type()), + "binomial only supports floating-point dtypes for count, got: ", + count.scalar_type()); + TORCH_CHECK_VALUE( + at::isFloatingType(prob.scalar_type()), + "binomial only supports floating-point dtypes for prob, got: ", + prob.scalar_type()); + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + Tensor ret = at::empty(count.sizes(), count.options()); + at::TensorIterator iter = at::TensorIteratorConfig() + .add_output(ret) + .add_input(count) + .add_input(prob) + .build(); + launch_binomial_cuda_kernel(iter, gen); + return ret; +} + +// NOLINTNEXTLINE(performance-unnecessary-value-param) +Tensor _s_gamma_cuda(const Tensor& alpha, std::optional gen_) { + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + Tensor ret = at::empty(alpha.sizes(), alpha.options()); + launch_gamma_kernel(ret, alpha, gen); + return ret; +} + +// NOLINTNEXTLINE(performance-unnecessary-value-param) +Tensor _s_dirichlet_cuda(const Tensor& alpha, std::optional gen_) { + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + Tensor ret = at::empty(alpha.sizes(), alpha.options()); + launch_gamma_kernel(ret, alpha, gen); + auto gamma_sum = ret.sum(/*dim=*/-1, /*keepdim=*/true); + at::TensorIterator iter = at::TensorIteratorConfig() + .add_output(ret) + .add_input(ret) + .add_input(gamma_sum) + .build(); + launch_dirichlet_kernel(iter); + return ret; +} + +Tensor _standard_gamma_grad_cuda(const Tensor& self, const Tensor& output) { + Tensor ret = at::empty(self.sizes(), self.options()); + TensorIterator iter = at::TensorIteratorConfig() + .add_output(ret) + .add_input(self) + .add_input(output) + .build(); + launch_standard_gamma_grad_kernel(iter); + return ret; +} + +Tensor _dirichlet_grad_cuda(const Tensor& x, const Tensor& alpha, const Tensor& total) { + Tensor ret = at::empty(x.sizes(), x.options()); + TensorIterator iter = at::TensorIteratorConfig() + .add_output(ret) + .add_input(x) + .add_input(alpha) + .add_input(total) + .build(); + launch_dirichlet_grad_kernel(iter); + return ret; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.cu new file mode 100644 index 0000000000000000000000000000000000000000..6c32dd6dc90bda80d6dce05e1639ec7fe186f071 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.cu @@ -0,0 +1,203 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +/** + * Note [Register spilling in curand call for CUDA < 10] + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * For CUDA < 10, curandStatePhilox4_32_10_t engine achieves poor performance (60% SOL bandwidth) + * when called to generate one random number at a time. This is because the line + * unsigned ret = (&state->output.x)[state->STATE++]; + * in + * QUALIFIERS unsigned int curand(curandStatePhilox4_32_10_t *state) + * in curand_kernel.h dynamically indexes into state.output, preventing the compiler from ever + * storing state.output in registers. + * + * CUDA 10 fixed this problem. However, for backwards compatibility, in the following kernels + * we are using curand distributions that utilize curand4 call. curand4 call doesn't have the + * register spilling problem. + */ + +namespace { + +template +void poisson_cuda_kernel( + const at::TensorBase &ret, + const at::TensorBase &lambda, + at::PhiloxCudaState philox_args) { + auto functor = [philox_args] __device__( + scalar_t & ret_val, const scalar_t& lambda) { + CUDA_KERNEL_ASSERT(lambda >= 0 && "invalid Poisson rate, expected rate to be non-negative"); + auto seeds = at::cuda::philox::unpack(philox_args); + curandStatePhilox4_32_10_t state; + curand_init(std::get<0>(seeds), + blockIdx.x * blockDim.x + threadIdx.x, + std::get<1>(seeds), + &state); + ret_val = static_cast(curand_poisson(&state, lambda)); + }; + at::cuda::CUDA_tensor_apply2(ret, lambda, functor); +} + +struct curand_uniform_wrapper { + curandStatePhilox4_32_10_t &state; + __device__ curand_uniform_wrapper(curandStatePhilox4_32_10_t &state): state(state) {} + __device__ float operator()() { + + uint32_t val = curand(&state); //need just bits + constexpr auto MASK = static_cast((static_cast(1) << std::numeric_limits::digits) - 1); + constexpr auto DIVISOR = static_cast(1) / (static_cast(1) << std::numeric_limits::digits); + return (val & MASK) * DIVISOR; + } +}; + +template +void binomial_cuda_kernel( + at::TensorIteratorBase &iter, + at::PhiloxCudaState philox_args) { + using accscalar_t = at::acc_type; + + at::native::distribution_binary_kernel(iter, philox_args, + [] GPU_LAMBDA (curandStatePhilox4_32_10_t& state, scalar_t count, scalar_t prob) { + auto uniform_lambda = curand_uniform_wrapper(state); + BaseSampler standard_uniform(uniform_lambda); + auto sample = sample_binomial(count, prob, standard_uniform); + return static_cast(sample); + } + ); +} + +template +void gamma_cuda_kernel( + const at::TensorBase &ret, + const at::TensorBase &alpha, + at::PhiloxCudaState philox_args) { + using accscalar_t = at::acc_type; + auto functor = [philox_args] __device__( + scalar_t & ret_val, const scalar_t& alpha) { + auto seeds = at::cuda::philox::unpack(philox_args); + curandStatePhilox4_32_10_t state; + curand_init(std::get<0>(seeds), + blockIdx.x * blockDim.x + threadIdx.x, + std::get<1>(seeds), + &state); + + auto uniform_lambda = [&state] __device__ () { + return curand_uniform(&state); + }; + BaseSampler standard_uniform(uniform_lambda); + + auto normal_lambda = [&state] __device__ () { + return curand_normal(&state); + }; + BaseSampler standard_normal(normal_lambda); + auto sample = sample_gamma(alpha, standard_uniform, standard_normal); + auto min_value = std::numeric_limits::min(); + ret_val = (min_value > sample) ? min_value : sample; + }; + at::cuda::CUDA_tensor_apply2(ret, alpha, functor); +} + +} // namespace + +namespace at::native { + +void launch_dirichlet_kernel(at::TensorIteratorBase &iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, + iter.input_dtype(), "dirichlet_cuda", [&] { + at::native::gpu_kernel( + iter, + [] GPU_LAMBDA (scalar_t gamma, scalar_t gamma_sum) { + auto ret_val = gamma / gamma_sum; + auto min_value = std::numeric_limits::min(); + auto max_value = 1 - std::numeric_limits::epsilon(); + ret_val = (min_value > ret_val) ? min_value : ret_val; + ret_val = (max_value < ret_val) ? max_value : ret_val; + return ret_val; + }); + }); +} + +void launch_poisson_cuda_kernel( + const TensorBase &ret, const TensorBase &lambda, CUDAGeneratorImpl *gen) { + PhiloxCudaState rng_engine_inputs; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + rng_engine_inputs = gen->philox_cuda_state(20); + } + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, ret.scalar_type(), "poisson_cuda", [&] { + poisson_cuda_kernel(ret, lambda, rng_engine_inputs); + }); +} + +void launch_binomial_cuda_kernel( + TensorIteratorBase &iter, CUDAGeneratorImpl *gen) { + PhiloxCudaState rng_engine_inputs; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + rng_engine_inputs = gen->philox_cuda_state(42); + } + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(), "binomial_cuda", [&] { + binomial_cuda_kernel(iter, rng_engine_inputs); + }); +} + +void launch_gamma_kernel( + const TensorBase &ret, const TensorBase &alpha, CUDAGeneratorImpl *gen) { + PhiloxCudaState rng_engine_inputs; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + rng_engine_inputs = gen->philox_cuda_state(10); + } + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, ret.scalar_type(), "gamma_cuda", [&] { + gamma_cuda_kernel(ret, alpha, rng_engine_inputs); + }); +} + +void launch_standard_gamma_grad_kernel(TensorIteratorBase &iter) { + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, iter.input_dtype(), "_standard_gamma_grad_cuda", [&] { + using accscalar_t = at::acc_type; + gpu_kernel(iter, + [] GPU_LAMBDA (scalar_t self_val, scalar_t output_val) { + return standard_gamma_grad_one(self_val, output_val); + }); + }); +} + +void launch_dirichlet_grad_kernel(TensorIteratorBase &iter) { + AT_DISPATCH_FLOATING_TYPES(iter.input_dtype(), "_dirichlet_grad_cuda", [&] { + using accscalar_t = at::acc_type; + at::native::gpu_kernel(iter, + [] GPU_LAMBDA (scalar_t x_val, scalar_t alpha_val, scalar_t total_val) -> scalar_t { + return dirichlet_grad_one(x_val, alpha_val, total_val); + }); + }); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.h b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.h new file mode 100644 index 0000000000000000000000000000000000000000..053eff0c7d7a5a84db1601bf17fd19dc2cc35382 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Distributions.h @@ -0,0 +1,25 @@ +#pragma once + +namespace at { +struct CUDAGeneratorImpl; +struct TensorIteratorBase; +class TensorBase; + +namespace native { + +void launch_poisson_cuda_kernel( + const TensorBase &ret, const TensorBase &lambda, CUDAGeneratorImpl *gen); + +void launch_gamma_kernel( + const TensorBase &ret, const TensorBase &alpha, CUDAGeneratorImpl *gen); + +void launch_binomial_cuda_kernel( + TensorIteratorBase &iter, CUDAGeneratorImpl *gen); + +void launch_dirichlet_kernel(TensorIteratorBase &iter); + +void launch_standard_gamma_grad_kernel(TensorIteratorBase &iter); + +void launch_dirichlet_grad_kernel(TensorIteratorBase &iter); + +}} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Dropout.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Dropout.cu new file mode 100644 index 0000000000000000000000000000000000000000..100725e08ac83a254c9fd12ea207aed635fa8c95 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Dropout.cu @@ -0,0 +1,464 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +// philox generates 128 bits of randomness at a time. Kernel uses this explicitly by putting suitably transformed result into float4 +// for all members of float4 to be consumed UNROLL has to be 4. Don't change! +// Note: VEC <= 4 (and in most real-world cases will be 4), so same logic applies. +const int UNROLL = 4; + +template < + typename scalar_t, + typename accscalar_t, + typename IndexType, + int ADims, + int VEC, + typename mask_t> +C10_LAUNCH_BOUNDS_2(256, 4) +__global__ void +fused_dropout_kernel_vec(at::cuda::detail::TensorInfo a, + at::cuda::detail::TensorInfo b, + at::cuda::detail::TensorInfo c, + IndexType totalElements, accscalar_t p, + PhiloxCudaState philox_args) { + using LoadT = memory::aligned_vector; + using MaskLoadT = memory::aligned_vector; + + auto [seed, offset] = at::cuda::philox::unpack(philox_args); + IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; + curandStatePhilox4_32_10_t state; + curand_init(seed, idx, offset, &state); + + // Helps align the total number of times curand_uniform4 is called by each thread for the same totalElements + // in the vec=2 and vec=4 cases. + bool gridxvec_loop_state = false; + accscalar_t scale = 1.0 / p; + + constexpr int RAND_SIZE = (VEC + 4 - 1) / 4; + float4 rand[RAND_SIZE]; + + // Note: Vectorized loads means we'll stride each thread by an additional VEC factor, as we'll load VEC elements at a time + for (IndexType linearIndex = idx * VEC; + linearIndex < totalElements; + linearIndex += gridDim.x * blockDim.x * VEC) { + // local storage + scalar_t src[VEC]; + // We'll use this to actually cause vectorized loads later + LoadT *value = reinterpret_cast(&src); + + //curand_uniform_double was pure evil anyway, not doing what it promises, and there's nothing for Halfs, so generate float for everything + // Note: need a new set of random values per 4 elements -- we'll handle VEC elements in this thread, so need ceil(VEC / 4) + // sets of rand. + if ((VEC >= 4) || (gridxvec_loop_state == 0)) { + #pragma unroll + for (int ii = 0; ii < RAND_SIZE; ii++) { + rand[ii] = curand_uniform4(&state); + } + } else { + // sets up the last two values we generated last iteration to be used this iteration. + rand[0].x = rand[0].z; + rand[0].y = rand[0].w; + gridxvec_loop_state ^= 1; + } + + rand[0].x = rand[0].x < p; + rand[0].y = rand[0].y < p; + if constexpr (VEC >= 4) { + rand[0].z = rand[0].z < p; + rand[0].w = rand[0].w < p; + } + + #pragma unroll + for (int ii = 1; ii < RAND_SIZE; ii++) { + rand[ii].x = rand[ii].x < p; + rand[ii].y = rand[ii].y < p; + rand[ii].z = rand[ii].z < p; + rand[ii].w = rand[ii].w < p; + } + + // Note: We explicitly check for is_contiguous() before launching the vectorized kernel + // and replace IndexToOffset call with linearIndex to allow vectorization of NHWC (or other) + // ordering. + // Single vectorized load + *value = *reinterpret_cast(&a.data[linearIndex]); + + scalar_t r[VEC]; + mask_t mask[VEC]; + + // Perform the actual computation + #pragma unroll + for (int jj = 0; jj < RAND_SIZE; jj++) { + #pragma unroll + for (int ii = 0; ii < std::min(VEC, 4); ii++) { + r[jj * 4 + ii] = src[jj * 4 + ii]*(&rand[jj].x)[ii]*scale; + mask[jj * 4 + ii] = (mask_t)(&rand[jj].x)[ii]; + } + } + + // Vectorized writes for both mask & result + *(reinterpret_cast(&b.data[linearIndex])) = *reinterpret_cast(&r[0]); + *(reinterpret_cast(&c.data[linearIndex])) = *reinterpret_cast(&mask[0]); + + __syncthreads(); + } +} + +template < + typename scalar_t, + typename accscalar_t, + typename IndexType, + int ADims, + int BDims = ADims, + typename mask_t> +C10_LAUNCH_BOUNDS_2(256, 4) +__global__ void +fused_dropout_kernel(cuda::detail::TensorInfo a, + cuda::detail::TensorInfo b, + cuda::detail::TensorInfo c, + IndexType totalElements, accscalar_t p, + PhiloxCudaState philox_args) { + auto [seed, offset] = at::cuda::philox::unpack(philox_args); + IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; + curandStatePhilox4_32_10_t state; + curand_init(seed, idx, offset, &state); + accscalar_t scale = 1.0 / p; + + IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * + blockDim.x * gridDim.x * UNROLL; + for (IndexType linearIndex = idx; + linearIndex < rounded_size; + linearIndex += gridDim.x * blockDim.x*UNROLL) { +//curand_uniform_double was pure evil anyway, not doing what it promises, and there's nothing for Halfs, so generate float for everything + float4 rand = curand_uniform4(&state); + scalar_t src[UNROLL]; + rand.x = rand.x < p; + rand.y = rand.y < p; + rand.z = rand.z < p; + rand.w = rand.w < p; + for (int ii = 0; ii < UNROLL; ii++) { + IndexType li = linearIndex + blockDim.x * gridDim.x * ii; + if (li < totalElements) { + // Convert `linearIndex` into an offset of `a` + const IndexType aOffset = + cuda::detail::IndexToOffset::get(li, a); + src[ii] = a.data[aOffset]; + } + } + for (int ii = 0; ii < UNROLL; ii++) { + IndexType li = linearIndex + blockDim.x * gridDim.x * ii; + if (li < totalElements) { + // Convert `linearIndex` into an offset of `b` + const IndexType bOffset = + cuda::detail::IndexToOffset::get(li, b); + b.data[bOffset] = src[ii]*(&rand.x)[ii]*scale; + c.data[bOffset] = (mask_t)(&rand.x)[ii]; + } + } + __syncthreads(); + } +} + +template +void masked_scale_kernel(at::Tensor& ret, const at::Tensor& src, const at::Tensor& mask, accscalar_t scale){ + auto iter = at::TensorIteratorConfig() + .check_all_same_dtype(false) + .add_output(ret) + .add_const_input(src) + .add_const_input(mask) + .build(); + + at::native::gpu_kernel( + iter, + [=]GPU_LAMBDA(const scalar_t src_val, const mask_t mask_val) -> scalar_t { + return (float)mask_val * src_val * scale; + }); +} + +template +int get_vector_size(at::Tensor self, at::Tensor ret, at::Tensor mask) { + int vec_size = 4; + // get the vector size + if (!self.is_non_overlapping_and_dense() || !ret.is_non_overlapping_and_dense() || !mask.is_non_overlapping_and_dense()) { + vec_size = 1; + } else { + vec_size = memory::can_vectorize_up_to((const char*)self.const_data_ptr()); +#ifdef USE_ROCM + // make sure we don't break assumption that we can't have > 16 elements / thread + TORCH_INTERNAL_ASSERT(vec_size <= 16, "Value of VEC must be in [2, 4, 8, 16]"); +#else + const int optimal_vec_size = 16 / static_cast(sizeof(scalar_t)); + vec_size = std::min(optimal_vec_size, vec_size); + + // make sure we don't break assumption that we can't have > 4 elements / thread + TORCH_INTERNAL_ASSERT(vec_size <= 8, "Value of VEC must be in [2, 4, 8]"); +#endif + } + + // check that we'd have no remainders - prefer a smaller vector size with no remainders over a larger vector and remainder. + bool can_vectorize = true; + do { + can_vectorize = self.numel() % vec_size == 0 && ret.numel() % vec_size == 0 && mask.numel() % vec_size == 0; + if (!can_vectorize) vec_size /= 2; + } while (vec_size > 1 && !can_vectorize); + return can_vectorize ? vec_size : 1; +} + +template +inline void launcher( + const Tensor& self, + Tensor& ret, + Tensor& mask, + double p, + const int64_t nelem, + const PhiloxCudaState rng_engine_inputs, + dim3 grid, + dim3 dim_block) { + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, + at::ScalarType::BFloat16, + self.scalar_type(), + "fused_dropout", + [&] { + using accscalar_t = acc_type; + accscalar_t pa = (accscalar_t)(p); + auto self_info = + cuda::detail::getTensorInfo(self); + auto ret_info = + cuda::detail::getTensorInfo(ret); + auto mask_info = + cuda::detail::getTensorInfo(mask); + self_info.collapseDims(); + ret_info.collapseDims(); + mask_info.collapseDims(); // ret and mask are collapsed to 1d + // contiguous tensor + + int vec_size = get_vector_size(self, ret, mask); + + if (vec_size > 1) { + switch (vec_size) { + case 16: + fused_dropout_kernel_vec< + scalar_t, + accscalar_t, + index_type, + 1, + 16> + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 8: + fused_dropout_kernel_vec< + scalar_t, + accscalar_t, + index_type, + 1, + 8> + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 4: + fused_dropout_kernel_vec< + scalar_t, + accscalar_t, + index_type, + 1, + 4> + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + case 2: + fused_dropout_kernel_vec< + scalar_t, + accscalar_t, + index_type, + 1, + 2> + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + default: + TORCH_INTERNAL_ASSERT(false, "Unexpected vectorization size"); + } + } else { + switch (self_info.dims) { + case 1: + fused_dropout_kernel + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + break; + default: + if (!self.is_contiguous() && ret.is_contiguous() && + mask.is_contiguous()) { + fused_dropout_kernel + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + fused_dropout_kernel + <<>>( + self_info, + ret_info, + mask_info, + nelem, + pa, + rng_engine_inputs); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + } + } + }); +} + +} //anonymous namespace + +template +std::tuple +dropout_cuda(CUDAGeneratorImpl* gen, const Tensor& self, double p){ + Tensor mask = at::empty_like(self, self.options().dtype(c10::CppTypeToScalarType::value)); + const int64_t nelem = self.numel(); + // empty tensors should not get here, but just in case, avoid FPE + // non-training shot-cut + if (nelem==0) return std::tuple(self.clone(), mask); + + Tensor ret = at::empty_like(self); + const int64_t block_size = 256; + unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; + dim3 dim_block(block_size); + dim3 grid((nelem + block_size -1)/block_size); + grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); +//number of times random will be generated per thread, to offset philox counter in thc random state + int64_t counter_offset = ((nelem - 1)/(block_size*grid.x*UNROLL)+1)*UNROLL; + PhiloxCudaState rng_engine_inputs; + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen->mutex_); + rng_engine_inputs = gen->philox_cuda_state(counter_offset); + } + if (cuda::detail::canUse32BitIndexMath(self)){ + launcher( + self, ret, mask, p, nelem, rng_engine_inputs, grid, dim_block); + } else { + launcher( + self, ret, mask, p, nelem, rng_engine_inputs, grid, dim_block); + } + return std::tuple(ret, mask); +} + +std::tuple +native_dropout_cuda(const Tensor& self, double p, std::optional train){ + // short-cut for train == false + if (train.has_value() && !train.value()) { + return std::make_tuple(self.clone(), at::ones_like(self, self.options().dtype(c10::CppTypeToScalarType::value))); + } + // short-cut + if (p == 1) { + // native_dropout_cuda is in derivatives.yaml, so we don't need to add data + // dependency from output to input for autograd + auto ret = at::zeros_like(self); + auto mask = at::zeros_like(self, self.options().dtype(c10::CppTypeToScalarType::value)); + return std::tuple(std::move(ret), std::move(mask)); + } + + auto gen = get_generator_or_default(std::nullopt, cuda::detail::getDefaultCUDAGenerator()); + double p1m = 1. - p; + return dropout_cuda(gen, self, p1m); +} + +// TODO: _fused_dropout_cuda is to be removed, see PR #63937 +std::tuple +fused_dropout_cuda(const Tensor& self, double p, std::optional gen_){ + auto gen = get_generator_or_default(gen_, cuda::detail::getDefaultCUDAGenerator()); + return dropout_cuda(gen, self, p); +} + +template +Tensor dropout_backward_cuda(const Tensor& grad, const Tensor& mask, double scale){ + Tensor ret = at::empty_like(grad, grad.suggest_memory_format()); + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, ret.scalar_type(), "masked_scale", [&] { + using accscalar_t = acc_type; + masked_scale_kernel(ret, grad, mask, (accscalar_t)scale); + }); + return ret; +} + +Tensor native_dropout_backward_cuda(const Tensor& grad, const Tensor& mask, double scale){ + TORCH_CHECK(mask.scalar_type() == at::ScalarType::Bool, "Mask should be Bool Scalar Type", mask.scalar_type()); + return dropout_backward_cuda(grad, mask, scale); +} + +// TODO: masked_scale_cuda is to be removed, see PR #63937 +Tensor masked_scale_cuda(const Tensor& self, const Tensor& mask, double scale){ + TORCH_CHECK(mask.scalar_type() == at::ScalarType::Byte, "mask should be torch.uint8 dtype"); + return dropout_backward_cuda(self, mask, scale); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Embedding.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Embedding.cu new file mode 100644 index 0000000000000000000000000000000000000000..9fe2b48520acd3f6cd905eba9ede34e5bc8e0faf --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Embedding.cu @@ -0,0 +1,421 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace at::native { + +namespace { + +#if defined(USE_ROCM) +static constexpr int BLOCKDIMY = 16; +#else +static constexpr int BLOCKDIMY = 32; +#endif + +template + +__global__ void embedding_backward_feature_kernel + (const index_t* indices, + const scalar_t* __restrict__ grad, + scalar_t* __restrict__ grad_weight, + int n, // OK to pass as int, we don't expect 2 billion+ samples in one shot + int64_t stride, + int padding_idx) +{ + extern __shared__ char buf[]; + accscalar_t* smem = (accscalar_t*)buf; + accscalar_t* my_s = smem + C10_WARP_SIZE*threadIdx.y; + int* indices_batch = (int*)(buf + sizeof(accscalar_t)*C10_WARP_SIZE*blockDim.y); + + const int s = (int)stride; // OK to make int, we don't expect 2 billion+ embedding row size + + const int f = threadIdx.x + blockIdx.x*blockDim.x; // feature_dim + + for(int batch_start = 0; batch_start < n; batch_start += blockDim.x*blockDim.y) + { + // Entire block cooperates to load a batch of 1024 indices to process + int tid = threadIdx.x + threadIdx.y*blockDim.x; + if(batch_start + tid < n) + indices_batch[tid] = (int)indices[batch_start + tid]; + + int batch_end = batch_start + blockDim.x*blockDim.y < n ? + batch_start + blockDim.x*blockDim.y : n; + + // Loop over the batch of <= 1024 loaded indices in chunks of blockDim.y = 32 + for(int chunk_start = batch_start; chunk_start < batch_end; chunk_start += blockDim.y) + { + // This does double duty: it makes sure indices_batch is ready, and it makes sure match-group + // leaders are done with their accumulates before other warps start loading again. + __syncthreads(); + + int n_this_chunk = (batch_end - chunk_start) < blockDim.y ? + (batch_end - chunk_start) : blockDim.y; + + int src_row = chunk_start + threadIdx.y; + int dst_row = indices_batch[src_row - batch_start]; // This warp's target row in grad_weight + + // All warps load their smem segments with incoming grad data + if(src_row < n && f < s && dst_row != padding_idx) + my_s[threadIdx.x] = static_cast(grad[src_row*stride + f]); + + __syncthreads(); + + // To ensure determinism, we can't just have each warp add its grad data to its dst_row. + // We need to check if any other warps pulled grad data targeting dst_row. + // If so, we elect the first warp in each matching group as the leader. + // Each leader warp serializes the accumulates targeting dst_row in shared memory, + // then finishes by adding the accumulated buffer to dst_row in grad_weight. + if(dst_row != padding_idx && src_row < n) // Per-warp exit condition, safe with ballot_sync + { + int match_found_this_thread = 0; + if(threadIdx.x < n_this_chunk) + match_found_this_thread = (dst_row == indices_batch[chunk_start - batch_start + threadIdx.x]); +#if defined(USE_ROCM) + unsigned long long int matchmask = WARP_BALLOT(match_found_this_thread); + int first_remaining_peer = __ffsll(matchmask) - 1; +#else + unsigned int matchmask = WARP_BALLOT(match_found_this_thread); + int first_remaining_peer = __ffs(matchmask) - 1; +#endif + + if(threadIdx.y == first_remaining_peer) // Nominate lowest-indexed warp as the leader + { + matchmask ^= (1 << first_remaining_peer); + while(matchmask) + { +#if defined(USE_ROCM) + first_remaining_peer = __ffsll(matchmask) - 1; +#else + first_remaining_peer = __ffs(matchmask) - 1; +#endif + my_s[threadIdx.x] += smem[threadIdx.x + C10_WARP_SIZE*first_remaining_peer]; + matchmask ^= (1 << first_remaining_peer); + } + if(f < s) + grad_weight[dst_row*stride + f] += static_cast(my_s[threadIdx.x]); + } + } + } + } +} + + +template +__global__ void embedding_backward_kernel( + index_t* input, index_t* indices, scalar_t* grad_output, scalar_t* grad_weight, + index_t* count, int64_t numel, int64_t stride, int padding_idx) { + + using accscalar_t = acc_type; + int idx = blockIdx.x * 4 + threadIdx.y; + + // Each warp is responsible for an input into the LookupTable. + // If the preceding input has the same as this input, then the warp + // exits immediately. The warp also processes subsequent inputs with the + // same value. + // + // Input Warp + // 1 + // 1 ( exits without doing any work) + // 5 + // 8 + + // Number of values processed by each thread (grain size) + const int SZ = 4; + + if (idx < numel + && (idx == 0 || input[idx] != input[idx - 1]) + && input[idx] != padding_idx) { + do { + const int start_feature = threadIdx.x + blockIdx.y * blockDim.x * SZ; + const int weight_row = ((int) input[idx]) * stride; + const int grad_row = ((int) indices[idx]) * stride; + const accscalar_t scale = count ? (accscalar_t)1.0 / count[idx] : 1.0; + + accscalar_t gradient[SZ]; + accscalar_t weight[SZ]; + + #pragma unroll + for (int ii = 0; ii < SZ; ii++) { + int feature_dim = start_feature + ii * C10_WARP_SIZE; + if (feature_dim < stride) { + gradient[ii] = static_cast(grad_output[grad_row + feature_dim]); + weight[ii] = static_cast(grad_weight[weight_row + feature_dim]); + } + } + + #pragma unroll + for (int ii = 0; ii < SZ; ii++) { + weight[ii] += gradient[ii] * scale; + } + + #pragma unroll + for (int ii = 0; ii < SZ; ii++) { + int feature_dim = start_feature + ii * C10_WARP_SIZE; + if (feature_dim < stride) { + grad_weight[weight_row + feature_dim] = static_cast(weight[ii]); + } + } + + idx++; + } while (idx < numel && input[idx] == input[idx - 1]); + } +} + +/* Calculate norms of the rows of weight_ptr given by idx_ptr and capture them in norms */ +template +__global__ void renorm_kernel( + scalar_t* weights, index_t* indices, accscalar_t max_norm, + accscalar_t norm_type, int64_t dim, + int64_t num_weights, int64_t weights_stride0, int64_t weights_stride1, + const int64_t *num_unique_indices) { + if (blockIdx.x >= *num_unique_indices) { + return; + } + + // Some casting hacks since dynamic shared memory and templates don't work together: + extern __shared__ unsigned char smem[]; + auto sdata = reinterpret_cast(smem); + + int tid = threadIdx.x; + int64_t index = static_cast(indices[blockIdx.x]); + CUDA_KERNEL_ASSERT(index >= 0 && index < num_weights && + "embedding_renorm_: index out of bounds"); + int64_t base_index = index * weights_stride0; + + accscalar_t v = 0; + for (int i = tid; i < dim; i += blockDim.x) { + auto x = static_cast(weights[base_index + i * weights_stride1]); + if (norm_type == 1) { + v += std::abs(x); + } else if (norm_type == 2) { + v += x * x; + } else { + v += std::pow(x, norm_type); + } + } + + v = cuda_utils::BlockReduceSum(v, sdata); + + if (tid == 0) { + sdata[0] = std::pow(v, static_cast(1.0 / norm_type)); + } + __syncthreads(); + + // now we renormalize the blocks that need it + if (sdata[0] > max_norm) { + auto factor = static_cast(max_norm / (sdata[0] + 1e-7)); + for (int i = tid; i < dim; i += blockDim.x) { + weights[base_index + i * weights_stride1] *= factor; + } + } +} + +template +__global__ void embedding_renorm_wrap_indices_kernel( + const index_t* indices, + index_t* wrapped_indices, + int64_t num_indices, + int64_t num_weights) { + auto offset = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (offset >= num_indices) { + return; + } + + int64_t index = static_cast(indices[offset]); + CUDA_KERNEL_ASSERT(index >= -num_weights && index < num_weights && + "embedding_renorm_: index out of bounds"); + if (index < 0) { + index += num_weights; + } + wrapped_indices[offset] = static_cast(index); +} + +} // anonymous namespace + + +Tensor embedding_dense_backward_cuda(const Tensor & grad_, const Tensor & indices_, + int64_t num_weights, int64_t padding_idx, + bool scale_grad_by_freq) { + auto grad_arg = TensorArg(grad_, "grad", 1); + auto indices_arg = TensorArg(indices_, "indices", 1); + checkScalarTypes("embedding_backward", indices_arg, {kLong, kInt}); + checkSameGPU("embedding_backward", grad_arg, indices_arg); + + auto indices = indices_.contiguous(); + + auto num_indices = indices.numel(); + auto grad = grad_.contiguous().view({num_indices, grad_.size(-1)}); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + if (num_indices <= 3072 && !scale_grad_by_freq) { + auto indices_contig = indices.contiguous(); + auto grad_weight = at::zeros({num_weights, grad_.size(-1)}, grad_.options()); + int64_t stride = grad_weight.stride(0); + int warp_size = at::cuda::warp_size(); + dim3 grid(ceil_div(stride, (int64_t)warp_size)); + dim3 block(warp_size, BLOCKDIMY); + + AT_DISPATCH_FLOATING_TYPES_AND2( + at::ScalarType::Half, at::ScalarType::BFloat16, + grad.scalar_type(), + "embedding_backward", + [&] + { + using accscalar_t = acc_type; + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_dense_backward_cuda", [&] () { + embedding_backward_feature_kernel + <<>> + (indices_contig.const_data_ptr(), + grad.const_data_ptr(), + grad_weight.mutable_data_ptr(), + static_cast(num_indices), + static_cast(stride), + static_cast(padding_idx)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + }); + return grad_weight; + } + + auto sorted_indices = at::empty_like(indices, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + auto orig_indices = at::empty_like(indices, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + Tensor count; + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_dense_backward_cuda", [&] () { + auto range = at::arange(num_indices, indices.options()); + int64_t nbits = padding_idx >= 0 + ? cuda::cub::get_num_bits(num_weights) + : cuda::cub::get_num_bits(num_weights - 1 - padding_idx); + cuda::cub::radix_sort_pairs( + indices.const_data_ptr(), sorted_indices.mutable_data_ptr(), + range.const_data_ptr(), orig_indices.mutable_data_ptr(), + num_indices, false, 0, nbits); + }); + + if (scale_grad_by_freq) { + count = at::empty_like(indices, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_dense_backward_cuda", [&] () { + // Compute an increasing sequence per unique item in sortedIndices: + // sorted: 2 5 5 5 7 7 8 9 9 + // count: 1 1 2 3 1 2 1 1 2 + auto sorted_data = sorted_indices.const_data_ptr(); + auto count_data = count.mutable_data_ptr(); + cuda::cub::inclusive_sum_by_key( + sorted_data, + ATEN_CUB_CONSTANT_ITERATOR(index_t)(1), + count_data, + num_indices + ); + + // Take the maximum of each count per unique key in reverse: + // sorted: 2 5 5 5 7 7 8 9 9 + // count: 1 3 3 3 2 2 1 2 2 + cuda::cub::inclusive_scan_by_key( + cccl_make_reverse_iterator(sorted_data + num_indices), + cccl_make_reverse_iterator(static_cast(count_data) + num_indices), + cccl_make_reverse_iterator(count_data + num_indices), + ATEN_CUB_MAXIMUM(), + num_indices + ); + }); + } + + return embedding_backward_cuda_kernel(grad, orig_indices, + sorted_indices, count, num_weights, padding_idx); +} + +Tensor & embedding_renorm_cuda_(Tensor & self, const Tensor & indices, + double max_norm, double norm_type) { + auto self_arg = TensorArg(self, "self", 1); + auto indices_arg = TensorArg(indices, "indices", 1); + checkDim("embedding_renorm_", self_arg, 2); + checkScalarTypes("embedding_renorm_", indices_arg, {kLong, kInt}); + checkSameGPU("embedding_renorm", self_arg, indices_arg); + + auto num_indices = indices.numel(); + if (num_indices == 0) { + return self; + } + + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_renorm_cuda_", [&] () { + + auto indices_contig = indices.expect_contiguous(); + const auto num_weights = self.size(0); + auto wrapped_indices = at::empty({num_indices}, indices.options()); + constexpr int64_t threads = 256; + embedding_renorm_wrap_indices_kernel<<< + ceil_div(num_indices, threads), threads, 0, stream>>>( + (*indices_contig).const_data_ptr(), + wrapped_indices.mutable_data_ptr(), + num_indices, + num_weights); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + auto sorted_indices = std::get<0>(wrapped_indices.sort()).contiguous(); + auto unique_indices = at::empty({num_indices}, indices.options()); + auto num_unique_indices = at::empty({}, indices.options().dtype(kLong)); + + cuda::cub::unique( + sorted_indices.const_data_ptr(), + unique_indices.mutable_data_ptr(), + num_unique_indices.mutable_data_ptr(), + num_indices + ); + + int warp_size = at::cuda::warp_size(); + TORCH_INTERNAL_ASSERT(num_threads() % warp_size == 0 && + num_threads() <= static_cast(cuda_utils::kCUDABlockReduceMaxThreads()), + "BlockReduceSum requires all warps be active"); + const int64_t *num_unique_indices_ptr = num_unique_indices.const_data_ptr(); + dim3 grid = unique_indices.numel(); + dim3 block = num_threads(); + int dim = self.stride(0); + + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, self.scalar_type(), "embedding_renorm_cuda_", [&] { + using accscalar_t = acc_type; + renorm_kernel<<>>( + self.mutable_data_ptr(), + unique_indices.const_data_ptr(), + static_cast(max_norm), + static_cast(norm_type), + dim, num_weights, self.stride(0), self.stride(1), + num_unique_indices_ptr); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + }); + return self; +} + + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBackwardKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBackwardKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..f2265503a4acf260aaabbd18e62c94193c875769 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBackwardKernel.cu @@ -0,0 +1,495 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#endif + +namespace at::native { + +namespace { + +/* This code computes the sum of the weights in two-steps: + 1) Each GPU warp sums `NROWS_PER_THREAD` number of row given by `indices` + 2) Each partial-sum from 1) are summed and scatter into `grad_weight` + + Notice, `NROWS_PER_THREAD` impacts the Achieved Occupancy of the + kernel execution. If it is high, the size of the thread blocks will be + too small to achieve good occupancy. Similarly, a very low value will + make the size of the thread blocks in the final sum in step 2) too small. +*/ +constexpr int NROWS_PER_THREAD = 10; + +// If the number of blocks processed by each SM is larger than this value, +// we will use the two-step sum and scatter approach. +constexpr int32_t MAX_ATOMIC_ACCUM_BLOCKS_PER_SM = 4; + +// Fast ceil division (no overflow checking) +__host__ __device__ __forceinline__ +int64_t ceil_div(int64_t x, int64_t y) { + return (x + y - 1) / y; +} + +template +__global__ +void krn_partials_per_segment(index_t *ret, const index_t *segment_offsets, + const int64_t *num_of_segments_ptr, int64_t numel) { + int64_t num_of_segments = *num_of_segments_ptr; + const int id = blockIdx.x * blockDim.x + threadIdx.x; + if(id < num_of_segments) { + const int64_t idx_start = segment_offsets[id]; + const int64_t idx_end = (id == num_of_segments-1)?numel:segment_offsets[id+1]; + const int64_t size = idx_end - idx_start; + ret[id] = ceil_div(size, NROWS_PER_THREAD); + } +} + +template +__global__ +void krn_partial_segment_offset( + index_t *ret, + const index_t *partials_per_segment, + const index_t *partials_per_segment_offset, + const index_t *segment_offsets, + const int64_t *num_of_segments_ptr) { + int64_t num_of_segments = *num_of_segments_ptr; + const int id = blockIdx.x * blockDim.x + threadIdx.x; + if(id < num_of_segments) { + index_t idx = partials_per_segment_offset[id]; + const index_t num_partials = partials_per_segment[id]; + const index_t segment_offset = segment_offsets[id]; + for (int64_t i=0; i +__global__ void compute_grad_weight_bags( + const index_t *indices, const scalar_t *gradOutput, + const index_t *offset2bag, const index_t *count, ptrdiff_t numel, + int64_t stride, int mode_mean, const index_t *bag_size, + const scalar_t* per_sample_weights, int64_t per_sample_weights_stride, + const index_t* segment_offsets, const int64_t *num_of_segments_ptr, + acc_type *grad_weight_per_segment, + const int64_t stride_warped) { + + int64_t num_of_segments = *num_of_segments_ptr; + const int64_t gid = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const int64_t id = gid / stride_warped; + const int64_t startFeature = gid % stride_warped; + if (startFeature >= stride) { + return; + } + if (id >= num_of_segments) { + return; + } + const int idx_begin = segment_offsets[id]; + const int idx_end = (id == num_of_segments-1)?numel:segment_offsets[id+1]; + + acc_type weight = 0; + for (int idx=idx_begin; idx < idx_end; ++idx) { + const int origRow = indices[idx]; + const int seq_number = offset2bag[origRow]; + const int gradOutputRow = seq_number * stride; + + acc_type scale = count ? 1.0 / count[idx] : 1.0; + if (per_sample_weights) { + scale *= per_sample_weights[origRow * per_sample_weights_stride]; + } + + acc_type gradient = gradOutput[gradOutputRow + startFeature]; + if (mode_mean) { + gradient /= bag_size[seq_number]; + } + weight += gradient * scale; + } + grad_weight_per_segment[id * stride + startFeature] = weight; +} + +template +__global__ void compute_grad_weight( + const index_t *indices, + const scalar_t *gradOutput, + const index_t *count, + ptrdiff_t numel, + int64_t stride, + const index_t* segment_offsets, + const int64_t *num_of_segments_ptr, + acc_type *grad_weight_per_segment, + const int64_t stride_warped) { + + int64_t num_of_segments = *num_of_segments_ptr; + using accscalar_t = acc_type; + const int64_t gid = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const int64_t id = gid / stride_warped; + const int64_t startFeature = gid % stride_warped; + if (startFeature >= stride) { + return; + } + if (id >= num_of_segments) { + return; + } + const int idx_begin = segment_offsets[id]; + const int idx_end = (id == num_of_segments-1)?numel:segment_offsets[id+1]; + + accscalar_t weight = 0; + for (int idx=idx_begin; idx < idx_end; ++idx) { + const index_t target_row = indices[idx]; + const accscalar_t scale = count ? (accscalar_t)1.0 / count[idx] : 1.0; + weight += gradOutput[target_row * stride + startFeature] * scale; + } + grad_weight_per_segment[id * stride + startFeature] = weight; +} + +// Fused kernel that combines compute_grad_weight and sum_and_scatter using atomic adds. +// This eliminates the serialization bottleneck when num_of_segments is small. +// Each partial segment atomically adds its contribution directly to grad_weight. +// Template parameters: +// scalar_t: input gradient type +// output_t: output gradient weight type (float for half/bf16 atomic accumulation) +template +__global__ void compute_grad_weight_atomic_accumulate( + const index_t *orig_indices, + const scalar_t *gradOutput, + const index_t *count, + ptrdiff_t numel, + int64_t stride, + const index_t *partial_segment_offsets, + const int64_t *num_of_partial_segments_ptr, + const index_t *sorted_indices, + const index_t *partial_to_segment_idx, + const index_t *segment_offsets, + output_t *grad_weight, + const int64_t padding_idx, + const int64_t stride_warped) { + + int64_t num_of_partial_segments = *num_of_partial_segments_ptr; + using accscalar_t = acc_type; + const int32_t gid = blockIdx.x * blockDim.x + threadIdx.x; + const int32_t partial_id = gid / stride_warped; + const int32_t startFeature = gid % stride_warped; + + if (startFeature >= stride) { + return; + } + if (partial_id >= num_of_partial_segments) { + return; + } + + const index_t idx_begin = partial_segment_offsets[partial_id]; + const index_t idx_end = (partial_id == num_of_partial_segments - 1) + ? numel + : partial_segment_offsets[partial_id + 1]; + + accscalar_t weight = 0; + for (index_t idx = idx_begin; idx < idx_end; ++idx) { + const index_t target_row = orig_indices[idx]; + const accscalar_t scale = count ? (accscalar_t)1.0 / count[idx] : 1.0; + weight += gradOutput[target_row * stride + startFeature] * scale; + } + + // Get the target row for this partial segment from the segment info + const index_t segment_id = partial_to_segment_idx[partial_id]; + const index_t target_row = sorted_indices[segment_offsets[segment_id]]; + + if (target_row != padding_idx) { + gpuAtomicAddNoReturn( + &grad_weight[target_row * stride + startFeature], + static_cast(weight)); + } +} + +// Kernel to build mapping from partial segment ID to segment ID +template +__global__ void krn_partial_to_segment_idx( + index_t *partial_to_segment_idx, + const index_t *partials_per_segment, + const index_t *partials_per_segment_offset, + const int64_t *num_of_segments_ptr) { + int64_t num_of_segments = *num_of_segments_ptr; + const int32_t id = blockIdx.x * blockDim.x + threadIdx.x; + if (id < num_of_segments) { + index_t idx = partials_per_segment_offset[id]; + const index_t num_partials = partials_per_segment[id]; + for (index_t i = 0; i < num_partials; ++i) { + partial_to_segment_idx[idx++] = id; + } + } +} + +// This kernel assumes that all input tensors are contiguous. +template +__global__ void sum_and_scatter( + const index_t *input, scalar_t *gradWeight, int64_t stride, + const index_t* segment_offsets, const int64_t *num_of_segments_ptr, + const acc_type *grad_weight_per_segment, + const index_t *segment_sizes_offsets, const int64_t *num_of_partial_segments_ptr, + const int64_t padding_idx, + const int64_t stride_warped) { + + int64_t num_of_segments = *num_of_segments_ptr; + int64_t num_of_partial_segments = *num_of_partial_segments_ptr; + const int64_t gid = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + const int64_t id = gid / stride_warped; + const int64_t startFeature = gid % stride_warped; + if (startFeature >= stride) { + return; + } + if (id >= num_of_segments) { + return; + } + + const int idx_begin = segment_sizes_offsets[id]; + const int idx_end = (id == num_of_segments-1)?num_of_partial_segments:segment_sizes_offsets[id+1]; + acc_type weight = 0; + for (int idx=idx_begin; idx < idx_end; ++idx) { + weight += grad_weight_per_segment[idx*stride + startFeature]; + } + int64_t target_row = input[segment_offsets[id]]; + if (target_row != padding_idx) { + gradWeight[target_row * stride + startFeature] = weight; + } +} + +template +__global__ void compute_num_of_partial_segments(const index_t *partials_per_segment, const index_t *partials_per_segment_offset, const int64_t *num_of_segments_ptr, int64_t *output) { + int64_t num_of_segments = *num_of_segments_ptr; + *output = partials_per_segment[num_of_segments-1] + + partials_per_segment_offset[num_of_segments-1]; +} + + +} // anon namespace + + +Tensor embedding_backward_cuda_kernel( + const Tensor &grad, + const Tensor &orig_indices, + const Tensor &sorted_indices, + const Tensor &count, + int64_t num_weights, + int padding_idx, + bool mode_mean, + const Tensor &offset2bag, + const Tensor &bag_size, + const Tensor &per_sample_weights) { + + auto stream = at::cuda::getCurrentCUDAStream(); + const ptrdiff_t numel = sorted_indices.numel(); + + auto grad_weight = at::zeros({num_weights, grad.size(-1)}, grad.options()); + const int64_t stride = grad_weight.stride(0); + + // Compute the number of segments and their start position so that we do not have to + // spawn a warp per index. In this context, a segment is a number of rows that should + // be summarized. + // Unit: index in `sorted_indices` and `orig_indices` + auto segment_offsets = at::empty({numel}, orig_indices.options()); + auto num_of_segments_tensor = at::empty({}, grad.options().dtype(kLong)); + int64_t *num_of_segments_ptr = num_of_segments_tensor.mutable_data_ptr(); + AT_DISPATCH_INDEX_TYPES(orig_indices.scalar_type(), "embedding_backward_cuda_kernel", [&] () { + cuda::cub::unique_by_key( + sorted_indices.const_data_ptr(), cccl_counting_iterator{0}, + segment_offsets.mutable_data_ptr(), + num_of_segments_ptr, sorted_indices.numel()); + }); + + int64_t max_segments = std::min(numel, num_weights); + + AT_DISPATCH_INDEX_TYPES(orig_indices.scalar_type(), "embedding_backward_cuda_kernel", [&] () { + // We split the segments up into sizes of `NROWS_PER_THREAD` + // Compute the number partial-segments per segment (some partial-segments + // may not be the full `NROWS_PER_THREAD` number of rows) + auto partials_per_segment = at::empty({max_segments}, orig_indices.options()); + { + krn_partials_per_segment<<>> ( + partials_per_segment.mutable_data_ptr(), + segment_offsets.const_data_ptr(), + num_of_segments_ptr, + numel); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + + // In order to compute `partial_segment_offset`, which is the start index + // of each partial-segment in `sorted_indices`, we need to compute the + // start position of each _segment_ in `partial_segment_offset`. + // Unit: index in `partial_segment_offset` + auto partials_per_segment_offset = at::empty({max_segments}, orig_indices.options()); + cuda::cub::exclusive_sum( + partials_per_segment.const_data_ptr(), + partials_per_segment_offset.mutable_data_ptr(), + max_segments); + + // The total number of partial-segments is the sum of `partials_per_segment_offset` + auto num_of_partial_segments_tensor = at::empty({}, grad.options().dtype(kLong)); + int64_t *num_of_partial_segments_ptr = num_of_partial_segments_tensor.mutable_data_ptr(); + compute_num_of_partial_segments<<<1, 1, 0, c10::cuda::getCurrentCUDAStream()>>>( + partials_per_segment.const_data_ptr(), + partials_per_segment_offset.const_data_ptr(), + num_of_segments_ptr, num_of_partial_segments_ptr); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + + auto max_partial_segment = numel / NROWS_PER_THREAD + max_segments; + + // Now we can compute the start position of each partial-segment + // Unit: index in `sorted_indices` and `orig_indices` + auto partial_segment_offset = at::empty({max_partial_segment}, orig_indices.options()); + { + krn_partial_segment_offset<<>> ( + partial_segment_offset.mutable_data_ptr(), + partials_per_segment.const_data_ptr(), + partials_per_segment_offset.const_data_ptr(), + segment_offsets.const_data_ptr(), + num_of_segments_ptr); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + + const int warp_size = at::cuda::warp_size(); + const int stride_warped = ceil_div(stride, warp_size)*warp_size; + const int block = std::min(stride_warped, MAX_BLOCK_SIZE); + const int grid = ceil_div(max_partial_segment*stride_warped, block); + + // Heuristic: Use fused kernel when sum_and_scatter would have poor parallelism + // This happens when max_segments * stride_warped is small relative to GPU capacity + // The fused kernel uses atomic adds but has grid size proportional to max_partial_segment + // instead of max_segments, giving much better parallelism when segments are few but large + // Note: Fused kernel uses atomics which are non-deterministic, so we skip it + // when deterministic algorithms are requested + const int32_t sum_scatter_grid = ceil_div(max_segments * stride_warped, block); + const int32_t num_sms = at::cuda::getCurrentDeviceProperties()->multiProcessorCount; + const int32_t min_blocks_for_good_occupancy = num_sms * MAX_ATOMIC_ACCUM_BLOCKS_PER_SM; + const bool use_fused_kernel = !offset2bag.defined() && + sum_scatter_grid < min_blocks_for_good_occupancy && + max_partial_segment > sum_scatter_grid * 4 && + !at::globalContext().deterministicAlgorithms(); + + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, + grad.scalar_type(), "embedding_bag_backward_cuda_compute_grad_weight", [&] { + // For numerical stability, the dtype of `grad_weight_per_segment` + // should match `acc_type` + using partial_weight_t = acc_type; + + if (use_fused_kernel) { + // This eliminates the serialization bottleneck in sum_and_scatter + // by directly accumulating into grad_weight from all partial segments + + // Build mapping from partial segment ID to segment ID + auto partial_to_segment_idx = at::empty({max_partial_segment}, orig_indices.options()); + { + krn_partial_to_segment_idx<<>>( + partial_to_segment_idx.mutable_data_ptr(), + partials_per_segment.const_data_ptr(), + partials_per_segment_offset.const_data_ptr(), + num_of_segments_ptr); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + + // For half/bfloat16 types, use opmath_type (float) intermediate buffer for atomic adds + // (float atomics are faster and more precise than half/bf16 atomics) + // For float/double, accumulate directly into grad_weight + if constexpr (!std::is_same_v>) { + auto grad_weight_acc = at::zeros( + {num_weights, stride}, + grad.options().dtype(toOpMathType(grad.scalar_type()))); + compute_grad_weight_atomic_accumulate<<>>( + orig_indices.const_data_ptr(), + grad.const_data_ptr(), + count.defined() ? count.const_data_ptr() : nullptr, + numel, stride, + partial_segment_offset.const_data_ptr(), + num_of_partial_segments_ptr, + sorted_indices.const_data_ptr(), + partial_to_segment_idx.const_data_ptr(), + segment_offsets.const_data_ptr(), + grad_weight_acc.mutable_data_ptr(), + padding_idx, + stride_warped); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + // Convert back to original dtype + grad_weight.copy_(grad_weight_acc); + } else { + // For float/double, accumulate directly into grad_weight + compute_grad_weight_atomic_accumulate<<>>( + orig_indices.const_data_ptr(), + grad.const_data_ptr(), + count.defined() ? count.const_data_ptr() : nullptr, + numel, stride, + partial_segment_offset.const_data_ptr(), + num_of_partial_segments_ptr, + sorted_indices.const_data_ptr(), + partial_to_segment_idx.const_data_ptr(), + segment_offsets.const_data_ptr(), + grad_weight.mutable_data_ptr(), + padding_idx, + stride_warped); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + } else { + + // Two-pass path: compute_grad_weight + sum_and_scatter + auto grad_weight_per_segment = at::empty( + {max_partial_segment, stride}, + grad.options().dtype(toOpMathType(grad.scalar_type()))); + // Compute the sum of each partial-segment and handle bags + if (offset2bag.defined()) { + compute_grad_weight_bags<<>>( + orig_indices.const_data_ptr(), + grad.const_data_ptr(), + offset2bag.const_data_ptr(), + count.defined() ? count.const_data_ptr() : nullptr, numel, stride, + mode_mean, bag_size.const_data_ptr(), + per_sample_weights.defined() ? per_sample_weights.const_data_ptr() : nullptr, + per_sample_weights.defined() ? per_sample_weights.stride(0) : 0, + partial_segment_offset.const_data_ptr(), + num_of_partial_segments_ptr, grad_weight_per_segment.mutable_data_ptr(), + stride_warped); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + compute_grad_weight<<>>( + orig_indices.const_data_ptr(), + grad.const_data_ptr(), + count.defined() ? count.const_data_ptr() : nullptr, + numel, stride, + partial_segment_offset.const_data_ptr(), + num_of_partial_segments_ptr, + grad_weight_per_segment.mutable_data_ptr(), + stride_warped); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + + // Finally, we sum all the partial-sums and scatter them + // into `grad_weight`. + const int grid2 = ceil_div(max_segments*stride_warped, block); + sum_and_scatter<<>>( + sorted_indices.const_data_ptr(), + grad_weight.mutable_data_ptr(), + stride, + segment_offsets.const_data_ptr(), + num_of_segments_ptr, grad_weight_per_segment.const_data_ptr(), + partials_per_segment_offset.const_data_ptr(), + num_of_partial_segments_ptr, + padding_idx, + stride_warped); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); + }); + return grad_weight; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBackwardKernel.cuh b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBackwardKernel.cuh new file mode 100644 index 0000000000000000000000000000000000000000..6fce8d6eb6d2ab28547ee321bc74bb71a774687f --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBackwardKernel.cuh @@ -0,0 +1,21 @@ +#pragma once +#include +#include +#include +#include + +namespace at::native { + +Tensor embedding_backward_cuda_kernel( + const Tensor &grad, + const Tensor &orig_indices, + const Tensor &sorted_indices, + const Tensor &count, + int64_t num_weights, + int padding_idx = -1, + bool mode_mean = false, + const Tensor &offset2bag = Tensor(), + const Tensor &bag_size = Tensor(), + const Tensor &per_sample_weights = Tensor()); + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBag.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBag.cu new file mode 100644 index 0000000000000000000000000000000000000000..71d44e73651145b56705f08600bb892e801af4a8 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/EmbeddingBag.cu @@ -0,0 +1,574 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include + +#include + +namespace at::native { + + +namespace { + +std::pair promoteIndicesAndOffsets( + const Tensor& indices, + const Tensor& offsets) { + const auto commonType = + promoteTypes(offsets.scalar_type(), indices.scalar_type()); + return { + indices.scalar_type() == commonType ? indices + : indices.toType(commonType), + offsets.scalar_type() == commonType ? offsets + : offsets.toType(commonType)}; +} + +// This kernel assumes that all input tensors except `weight` and +// per_sample_weights are contiguous. +template +__global__ void EmbeddingBag_updateOutputKernel_max( + const index_t *input, const index_t *offsets, const scalar_t *weight, scalar_t *output, + index_t *offset2bag, int64_t numIndices, int64_t numBags, + int64_t featureSize, int64_t weight_stride0, int64_t weight_stride1, + index_t *bag_size, index_t *max_indices, + index_t padding_idx, int64_t numRows) { + + // the strategy here is that each bag x feature is handled by a single thread + + int64_t chunksPerBag = ceil_div(featureSize, (int64_t)blockDim.x); + int64_t numChunks = numBags * chunksPerBag; + int64_t chunkOffset = blockIdx.x * blockDim.y + threadIdx.y; + int64_t chunkStride = gridDim.x * blockDim.y; + + for (int64_t chunk = chunkOffset; chunk < numChunks; chunk += chunkStride) { + int64_t featureDim = (chunk % chunksPerBag) * blockDim.x + threadIdx.x; + if (featureDim < featureSize) { + int64_t bag = chunk / chunksPerBag; + const scalar_t *weightFeat = weight + featureDim * weight_stride1; + int64_t begin = bag == 0 ? 0 : offsets[bag]; // forces first offset to be 0 instead of asserting on it + int64_t end = (bag < numBags - 1) ? (offsets[bag + 1]) : numIndices; + CUDA_KERNEL_ASSERT(end >= begin); + scalar_t weightFeatMax = 0; + int64_t bag_size_ = 0; + int64_t maxWord = -1; + + // Separate validation loop reduces register pressure in the main loop below. + // No early exit (break) on invalid input as benchmarking shows it degrades performance. + bool has_invalid_index = false; + for (int64_t emb = begin; emb < end; emb++) { + index_t input_idx = input[emb]; + has_invalid_index = has_invalid_index || (input_idx < 0 || input_idx >= numRows); + } + CUDA_KERNEL_ASSERT(!has_invalid_index && "Invalid input index in EmbeddingBag: index out of range [0, numRows)"); + + for (int64_t emb = begin; emb < end; emb++) { + bool pad = (input[emb] == padding_idx); + const int64_t weightRow = input[emb] * weight_stride0; + scalar_t weightValue = weightFeat[weightRow]; + if (bag_size_ == 0 || weightValue > weightFeatMax) { + weightFeatMax = pad ? weightFeatMax : weightValue; + maxWord = pad ? maxWord : input[emb]; + } + bag_size_ += pad ? 0 : 1; + + if (featureDim == 0) { + offset2bag[emb] = bag; + } + } + bag_size[bag] = bag_size_; + max_indices[bag * featureSize + featureDim] = maxWord; + output[bag * featureSize + featureDim] = weightFeatMax; + } + } +} + +// This kernel assumes that all input tensors except `weight` and +// per_sample_weights are contiguous. +template +__global__ void EmbeddingBag_updateOutputKernel_sum_mean( + const index_t *input, const index_t *offsets, const scalar_t *weight, scalar_t *output, + index_t *offset2bag, int64_t numIndices, int64_t numBags, + int64_t featureSize, int64_t weight_stride0, int64_t weight_stride1, + int mode, index_t *bag_size, + const scalar_t* per_sample_weights, int64_t per_sample_weights_stride, + index_t padding_idx, int64_t numRows) { + + // the strategy here is that each bag x feature is handled by a single thread + + using accscalar_t = acc_type; + int64_t chunksPerBag = ceil_div(featureSize, (int64_t)blockDim.x); + int64_t numChunks = numBags * chunksPerBag; + int64_t chunkOffset = blockIdx.x * blockDim.y + threadIdx.y; + int64_t chunkStride = gridDim.x * blockDim.y; + + for (int64_t chunk = chunkOffset; chunk < numChunks; chunk += chunkStride) { + int64_t featureDim = (chunk % chunksPerBag) * blockDim.x + threadIdx.x; + if (featureDim < featureSize) { + int64_t bag = chunk / chunksPerBag; + const scalar_t *weightFeat = weight + featureDim * weight_stride1; + int64_t begin = bag == 0 ? 0 : offsets[bag]; // forces first offset to be 0 instead of asserting on it + int64_t end = (bag < numBags - 1) ? (offsets[bag + 1]) : numIndices; + CUDA_KERNEL_ASSERT(end >= begin); + accscalar_t weightFeatSum = 0; + int64_t bag_size_ = 0; + + // Separate validation loop reduces register pressure in the main loop below. + // No early exit (break) on invalid input as benchmarking shows it degrades performance. + bool has_invalid_index = false; + for (int64_t emb = begin; emb < end; emb++) { + index_t input_idx = input[emb]; + has_invalid_index = has_invalid_index || (input_idx < 0 || input_idx >= numRows); + } + CUDA_KERNEL_ASSERT(!has_invalid_index && "Invalid input index in EmbeddingBag: index out of range [0, numRows)"); + + for (int64_t emb = begin; emb < end; emb++) { + index_t input_idx = input[emb]; + bool pad = (input_idx == padding_idx); + const int64_t weightRow = input_idx * weight_stride0; + scalar_t weightValue = weightFeat[weightRow]; + weightValue = pad ? static_cast(0) : weightValue; + if (per_sample_weights) { + accscalar_t scaleWeightBy = static_cast( + per_sample_weights[emb * per_sample_weights_stride]); + weightFeatSum += scaleWeightBy * static_cast(weightValue); + } else { + weightFeatSum += static_cast(weightValue); + } + bag_size_ += pad ? 0 : 1; + + if (featureDim == 0) { + offset2bag[emb] = bag; + } + } + if (mode == static_cast(EmbeddingBagMode::MEAN)) { + if (bag_size_ != 0) { + weightFeatSum = weightFeatSum / static_cast(bag_size_); + } + } + bag_size[bag] = bag_size_; + output[bag * featureSize + featureDim] = static_cast(weightFeatSum); + } + } +} + +Tensor embedding_bag_backward_cuda_sum_avg( + const Tensor &grad, + const Tensor &indices_, + const Tensor &offset2bag, + const Tensor &bag_size, + int64_t num_weights, + bool scale_grad_by_freq, int64_t mode, + const Tensor& per_sample_weights, + int64_t padding_idx) { + auto indices = indices_.contiguous(); + + ptrdiff_t num_indices = indices.numel(); + + if (num_indices == 0) { + // all empty bags + return at::zeros({num_weights, grad.size(1)}, grad.options()); + } + + auto sorted_indices = at::empty_like(indices, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + auto orig_indices = at::empty_like(indices, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + Tensor count; + + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_bag_backward_cuda_sum_avg", [&] () { + auto range = at::arange(num_indices, indices.options()); + int64_t nbits = padding_idx >= 0 + ? cuda::cub::get_num_bits(num_weights) + : cuda::cub::get_num_bits(num_weights - 1 - padding_idx); + cuda::cub::radix_sort_pairs( + indices.const_data_ptr(), sorted_indices.mutable_data_ptr(), + range.const_data_ptr(), orig_indices.mutable_data_ptr(), + num_indices, false, 0, nbits); + }); + + if (scale_grad_by_freq) { + count = at::empty_like(indices, LEGACY_CONTIGUOUS_MEMORY_FORMAT); + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_bag_backward_cuda_sum_avg", [&] () { + // Compute an increasing sequence per unique item in sortedIndices: + // sorted: 2 5 5 5 7 7 8 9 9 + // count: 1 1 2 3 1 2 1 1 2 + auto sorted_data = sorted_indices.const_data_ptr(); + auto count_data = count.mutable_data_ptr(); + cuda::cub::inclusive_sum_by_key( + sorted_data, + ATEN_CUB_CONSTANT_ITERATOR(index_t)(1), + count_data, + num_indices + ); + + // Take the maximum of each count per unique key in reverse: + // sorted: 2 5 5 5 7 7 8 9 9 + // count: 1 3 3 3 2 2 1 2 2 + cuda::cub::inclusive_scan_by_key( + cccl_make_reverse_iterator(sorted_data + num_indices), + cccl_make_reverse_iterator(count_data + num_indices), + cccl_make_reverse_iterator(count_data + num_indices), + ATEN_CUB_MAXIMUM(), + num_indices + ); + }); + } + return embedding_backward_cuda_kernel(grad, orig_indices, sorted_indices, + count, num_weights, padding_idx, mode == EmbeddingBagMode::MEAN, offset2bag, + bag_size, per_sample_weights); +} + +template +__global__ void EmbeddingBag_accGradParametersKernel_max( + const index_t *max_indices, const scalar_t *gradOutput, + scalar_t *gradWeight, int64_t stride, int64_t numBags, + index_t padding_idx, const int64_t numel) { + + using accscalar_t = acc_type; + + int64_t chunksPerBag = ceil_div(stride, (int64_t)blockDim.x); + int64_t numChunks = numBags * chunksPerBag; + int64_t chunkOffset = blockIdx.x * blockDim.y + threadIdx.y; + int64_t chunkStride = gridDim.x * blockDim.y; + + for (int64_t chunk = chunkOffset; chunk < numChunks; chunk += chunkStride) { + int64_t featureDim = (chunk % chunksPerBag) * blockDim.x + threadIdx.x; + if (featureDim < stride) { + int64_t bag = chunk / chunksPerBag; + + index_t word_idx = max_indices[bag * stride + featureDim]; + if (word_idx >= 0 && word_idx != padding_idx) { + // If bag is empty, we have max_indices[idx] set to -1 in forward. + fastAtomicAdd( + gradWeight, static_cast(word_idx) * stride + featureDim, + numel, gradOutput[bag * stride + featureDim], true); + } + } + } +} + +Tensor embedding_bag_backward_cuda_max(const Tensor &grad, + const Tensor &max_indices, + int64_t num_weights, + int64_t padding_idx) { + // See Note [Writing Nondeterministic Operations] + // Nondeterministic because of atomicAdd usage + globalContext().alertNotDeterministic("embedding_bag_backward_cuda_max"); + + auto grad_weight = at::zeros({num_weights, grad.size(1)}, grad.options()); + + int64_t stride = grad_weight.stride(0); + + int64_t numBags = grad.size(0); + + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + +#if defined(USE_ROCM) + dim3 block = dim3(64, 4); +#else + dim3 block = dim3(32, 8); +#endif + int grid = 1024; + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + grad.scalar_type(), "embedding_bag_backward_cuda_max", [&] { + AT_DISPATCH_INDEX_TYPES(max_indices.scalar_type(), "embedding_bag_backward_cuda_max", [&] () { + EmbeddingBag_accGradParametersKernel_max< + scalar_t, index_t><<>>( + max_indices.const_data_ptr(), grad.const_data_ptr(), + grad_weight.mutable_data_ptr(), stride, numBags, + padding_idx, grad_weight.numel()); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + }); + + return grad_weight; +} +} + +// Assumes all input tensors are contiguous. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +std::tuple +_embedding_bag_forward_only_cuda(const Tensor &weight, const Tensor &indices, + const Tensor &offsets, const bool scale_grad_by_freq, + const int64_t mode, bool sparse, const std::optional& per_sample_weights_opt, + bool include_last_offset, int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + + return _embedding_bag_cuda( + weight, + indices, + offsets, + scale_grad_by_freq, + mode, + sparse, + per_sample_weights, + include_last_offset, + padding_idx); +} + +// Assumes all input tensors are contiguous. +// See NOTE [ embedding_bag Native Functions ] in native_functions.yaml for details +std::tuple +_embedding_bag_cuda(const Tensor &weight, const Tensor &indices_, + const Tensor &offsets_, const bool scale_grad_by_freq, + const int64_t mode, bool sparse, const std::optional& per_sample_weights_opt, + bool include_last_offset, int64_t padding_idx) { + TORCH_CHECK(indices_.dim() == 1 || indices_.dim() == 2, + "input has to be a 1D or 2D Tensor, but got Tensor of dimension ", + indices_.dim()); + if (indices_.dim() == 1) { + TORCH_CHECK(offsets_.dim() == 1, + "offsets has to be a 1D Tensor, but got Tensor of dimension ", + offsets_.dim()); + } + TORCH_CHECK(weight.dim() == 2, + "weight has to be a 2D Tensor, but got Tensor of dimension ", + weight.dim()); + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + + Tensor indices, offsets; + std::tie(indices, offsets) = promoteIndicesAndOffsets(indices_, offsets_); + auto indices_arg = TensorArg(indices, "indices", 1); + checkScalarTypes("embedding_bag_cuda", indices_arg, {kLong, kInt}); + auto offsets_arg = TensorArg(offsets, "offsets", 1); + checkScalarTypes("embedding_bag_cuda", offsets_arg, {kLong, kInt}); + checkSameType("embedding_bag_cuda", indices_arg, offsets_arg); + auto weight_arg = TensorArg(weight, "weight", 1); + checkSameGPU("embedding_bag_cuda", weight_arg, indices_arg); + checkSameGPU("embedding_bag_cuda", weight_arg, offsets_arg); + + int64_t numIndices = indices.size(0); + int64_t numBags = offsets.size(0); + if (include_last_offset) { + // Check https://github.com/pytorch/pytorch/issues/29019 + // We plan to add one more element in offsets, which is equal to the size of + // indices. Currently for cuda devices, we still use the legacy + // implementation even this flag is enabled. + TORCH_CHECK( + numBags >= 1, "include_last_offset: numBags should be at least 1"); + numBags -= 1; + } + int64_t featureSize = weight.size(1); + + auto bag_size = at::empty(offsets.sizes(), indices.options()); + auto offset2bag = + at::empty({indices.size(0)}, indices.options()); // offset2bag = [0 0 0 0 0] + + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + auto output = at::empty({numBags, featureSize}, weight.options()); + + Tensor max_indices; + + if (mode == EmbeddingBagMode::MAX) { + max_indices = at::empty({numBags, featureSize}, indices.options()); + } else { + // No need to allocate if we aren't doing a backwards pass + max_indices = at::empty({0}, indices.options()); + } + +#if defined(USE_ROCM) + dim3 block = dim3(64, 4); +#else + dim3 block = dim3(32, 8); +#endif + int grid = 1024; + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, weight.scalar_type(), "embedding_bag_cuda", [&] { + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "embedding_bag_cuda", [&] () { + if (mode == EmbeddingBagMode::MAX) { + EmbeddingBag_updateOutputKernel_max<<>>( + indices.const_data_ptr(), offsets.const_data_ptr(), + weight.const_data_ptr(), output.mutable_data_ptr(), + offset2bag.mutable_data_ptr(), numIndices, numBags, featureSize, + weight.stride(0), weight.stride(1), bag_size.mutable_data_ptr(), + max_indices.mutable_data_ptr(), + padding_idx, weight.size(0)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } else { + EmbeddingBag_updateOutputKernel_sum_mean<<>>( + indices.const_data_ptr(), offsets.const_data_ptr(), + weight.const_data_ptr(), output.mutable_data_ptr(), + offset2bag.mutable_data_ptr(), numIndices, numBags, featureSize, + weight.stride(0), weight.stride(1), mode, bag_size.mutable_data_ptr(), + per_sample_weights.defined() ? per_sample_weights.const_data_ptr() : nullptr, + per_sample_weights.defined() ? per_sample_weights.stride(0) : 0, + padding_idx, weight.size(0)); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + } + }); + }); + + return std::tuple( + std::move(output), + std::move(offset2bag), + std::move(bag_size), + std::move(max_indices)); +} + +Tensor _embedding_bag_dense_backward_cuda(const Tensor &grad_, const Tensor &indices, + const Tensor &offset2bag, + const Tensor &bag_size_, + const Tensor &max_indices, + int64_t num_weights, + bool scale_grad_by_freq, int64_t mode, const std::optional& per_sample_weights_opt, + int64_t padding_idx) { + // See [Note: hacky wrapper removal for optional tensor] + c10::MaybeOwned per_sample_weights_maybe_owned = at::borrow_from_optional_tensor(per_sample_weights_opt); + const Tensor& per_sample_weights = *per_sample_weights_maybe_owned; + + // indices, offsets and offset2bag are assumed having correct dtypes and + // contiguous here due to the checks in _embedding_bag_backward in + // EmbeddingBag.cpp. + // Also see NOTE [ embedding_bag Native Functions ] in native_functions.yaml + // for more details. + + Tensor grad = grad_.contiguous(); + auto indices_arg = TensorArg(indices, "indices", 1); + auto grad_arg = TensorArg(grad, "grad", 1); + checkSameGPU("embedding_bag_cuda", grad_arg, indices_arg); + + + switch (static_cast(mode)) { + case EmbeddingBagMode::SUM: + case EmbeddingBagMode::MEAN: + if (mode == EmbeddingBagMode::MEAN) + AT_ASSERT(!per_sample_weights.defined()); + return embedding_bag_backward_cuda_sum_avg(grad, indices, offset2bag, + bag_size_, num_weights, scale_grad_by_freq, mode, + per_sample_weights, padding_idx); + + case EmbeddingBagMode::MAX: + AT_ASSERT(!per_sample_weights.defined()); + return embedding_bag_backward_cuda_max(grad, max_indices, num_weights, + padding_idx); + + default: + TORCH_CHECK(false, + "Unknown mode for embedding_bag_backward_cuda ", mode); + } +} + +template +__global__ static void _embedding_bag_per_sample_weights_backward_kernel( + const scalar_t* grad, int64_t grad_stride0, int64_t grad_stride1, + const scalar_t* weight, int64_t weight_stride0, int64_t weight_stride1, + const index_t* indices, // contiguous + const index_t* offset2bag, // contiguous + int64_t num_samples, + int64_t embedding_features, + scalar_t* output, + index_t padding_idx) { + using accscalar_t = acc_type; + const int idx = threadIdx.x + blockIdx.x * blockDim.x; + const int warp = idx / C10_WARP_SIZE; + const int thread_in_warp = idx % C10_WARP_SIZE; + const int num_warps = blockDim.x * gridDim.x / C10_WARP_SIZE; + + // Each warp is responsible for the accumulation of one sample. + // This involves doing one dot product between grad[bag_idx] and weight[embedding_idx]. + for (int sample_idx = warp; sample_idx < num_samples; sample_idx += num_warps) { + accscalar_t result = 0.; + const int bag_idx = (int)offset2bag[sample_idx]; + const int embedding_idx = (int)indices[sample_idx]; + if (embedding_idx != padding_idx) { + for (int feature_idx = thread_in_warp; feature_idx < embedding_features; + feature_idx += C10_WARP_SIZE) { + result += + grad[grad_stride0 * bag_idx + grad_stride1 * feature_idx] * + weight[weight_stride0 * embedding_idx + weight_stride1 * feature_idx]; + } + } + result = cuda_utils::WarpReduceSum(result); + if (thread_in_warp == 0) { + output[sample_idx] = result; + } + } +} + +Tensor _embedding_bag_per_sample_weights_backward_cuda( + const Tensor& grad, + const Tensor& weight, // NB: embedding table, not per_sample_weights + const Tensor& indices_, + const Tensor& offsets_, + const Tensor& offset2bag, + int64_t mode, + int64_t padding_idx) { + TORCH_CHECK( + mode == EmbeddingBagMode::SUM, + "embedding_bag_backward: per_sample_weights only supported for mode='sum'"); + + AT_ASSERT(grad.dim() == 2); + auto embedding_features = grad.size(1); + + Tensor indices, offsets; + std::tie(indices, offsets) = promoteIndicesAndOffsets(indices_, offsets_); + AT_ASSERT(indices.dim() == 1); + auto num_samples = indices.size(0); + + AT_ASSERT(weight.dim() == 2); + AT_ASSERT(weight.size(1) == embedding_features); + + const int threads_per_block = 512; + const int warps_per_block = threads_per_block / at::cuda::warp_size(); + + dim3 block(threads_per_block); + dim3 grid((num_samples + warps_per_block - 1) / warps_per_block); + + auto output = at::empty({num_samples}, grad.options()); + + // Early return when there is no samples in the batch. This saves unnecessary kernel + // launch, but also prevents cudaGetLastError() to complain about invalid launch args + if (num_samples == 0) { + return output; + } + + AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, + grad.scalar_type(), "_embedding_bag_per_sample_weights_backward_cuda", [&]() { + AT_DISPATCH_INDEX_TYPES(indices.scalar_type(), "_embedding_bag_per_sample_weights_backward_cuda", [&]() { + _embedding_bag_per_sample_weights_backward_kernel + <<>>( + grad.const_data_ptr(), grad.stride(0), grad.stride(1), + weight.const_data_ptr(), weight.stride(0), weight.stride(1), + indices.const_data_ptr(), + offset2bag.const_data_ptr(), + num_samples, + embedding_features, + output.mutable_data_ptr(), + padding_idx); + C10_CUDA_KERNEL_LAUNCH_CHECK(); + }); + } + ); + return output; +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Equal.cpp b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Equal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba7aeff8ce83b35dfa97fa7ee69046857db0dbd5 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/Equal.cpp @@ -0,0 +1,40 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#include +#else +#include +#include +#endif + +namespace at::native { + +bool cuda_equal(const Tensor& self, const Tensor &src) { + if (self.sizes() != src.sizes()) { + return false; + } + if (self.numel() == 0) { + return true; + } + + // This is the same optimization done in the cpu_equal. Since the flags like neg/conj should be already handled outside the + // cuda_equal, it should be safe to have the following fast path by + // ensuring the storage and strides exactly the same. + if (self.is_alias_of(src) + && self.storage_offset() == src.storage_offset() + && self.dtype() == src.dtype() + && self.is_contiguous() == src.is_contiguous() + && self.strides().equals(src.strides()) + // Extra checks to ensure the safety in case cuda_equal is directly called in C++. + && self.layout() == src.layout() + && self.is_neg() == src.is_neg() + && self.is_conj() == src.is_conj()) { + return true; + } + + return at::cuda::eq(self, src).all().item().to(); +} + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/FillKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/FillKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..f6677a3282cc8541bf881433ee88e882fb09144a --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/FillKernel.cu @@ -0,0 +1,30 @@ +#define TORCH_ASSERT_NO_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +namespace at::native { + +template +struct FillFunctor { + FillFunctor(scalar_t v): value(v) {} + __device__ __forceinline__ scalar_t operator() () const { + return value; + } + private: + scalar_t value; +}; + +void fill_kernel_cuda(TensorIterator& iter, const Scalar& value) { + AT_DISPATCH_V2(iter.dtype(), "fill_cuda", AT_WRAP([&]() { + gpu_kernel(iter, FillFunctor(value.to())); + }), AT_EXPAND(AT_ALL_TYPES_AND_COMPLEX), kComplexHalf, kBComplex32, kBool, kHalf, kBFloat16, AT_EXPAND(AT_FLOAT8_TYPES), AT_EXPAND(AT_BAREBONES_UNSIGNED_TYPES)); +} + +REGISTER_DISPATCH(fill_stub, &fill_kernel_cuda) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/FlattenIndicesKernel.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/FlattenIndicesKernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..383f87e6e8830c0f6b0021ce42f616017168bcc0 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/FlattenIndicesKernel.cu @@ -0,0 +1,28 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include + +namespace at::native { + +namespace { + +template +struct CUDAKernelLauncher { + static void launch(TensorIteratorBase& iter, const func_t& f) { + gpu_kernel(iter, f); + } +}; + +Tensor flatten_indices_cuda_kernel(const Tensor& indices, IntArrayRef size) { + return _flatten_indices(indices, size); +} + +} + +REGISTER_CUDA_DISPATCH(flatten_indices_stub, &flatten_indices_cuda_kernel) + +} // namespace at::native diff --git a/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ForeachBinaryOpList.cu b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ForeachBinaryOpList.cu new file mode 100644 index 0000000000000000000000000000000000000000..54d6d025558636129e42d1f13312cf6e67601248 --- /dev/null +++ b/western_ai/usa/pytorch/aten/src/ATen/native/cuda/ForeachBinaryOpList.cu @@ -0,0 +1,484 @@ +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include +#include +#include +#include +#include +#include + +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#endif + +namespace at::native { + +template class Op> +std::vector foreach_tensor_list_op( + TensorList tensors1, + TensorList tensors2, + const Scalar& alpha = 1) { + std::vector> tensor_lists; + std::vector vec_res; + vec_res.reserve(tensors1.size()); + for (const auto& t : tensors1) { + vec_res.emplace_back(at::native::empty_like(t)); + } + + tensor_lists.emplace_back(tensors1.vec()); + tensor_lists.emplace_back(tensors2.vec()); + tensor_lists.emplace_back(std::move(vec_res)); + + using opmath_t = at::opmath_type; + multi_tensor_apply<3>( + tensor_lists, + BinaryOpListAlphaFunctor< + T, + /* depth */ 3, + /* r_args_depth */ 2, + /* res_arg_index */ 2>(), + Op(), + alpha.to()); + + return std::move(tensor_lists[2]); +} + +template class Op> +void foreach_tensor_list_op_( + TensorList tensors1, + TensorList tensors2, + const Scalar& alpha = 1) { + std::vector> tensor_lists; + tensor_lists.emplace_back(tensors1.vec()); + tensor_lists.emplace_back(tensors2.vec()); + + using opmath_t = at::opmath_type; + multi_tensor_apply<2>( + tensor_lists, + BinaryOpListAlphaFunctor< + T, + /* depth */ 2, + /* r_args_depth */ 2, + /* res_arg_index */ 0>(), + Op(), + alpha.to()); + increment_version(tensors1); +} + +template